ansible - Add zero if the number of digits is less than three
问题描述
I have baremetal servers where I want to set a specific port for the serial console via proxying, and I decided to make the port from the last octet of the ip, but sometimes the servers have two digits in the last octet, and in such a situation I want zero added for them.
Example:
---
- name: Test
hosts: test
gather_facts: no
tasks:
- name: IPV4 address lookup for node
set_fact:
ip: "{{ lookup('community.general.dig', '{{ inventory_hostname }}-ipmi.mydomain.com') }}"
delegate_to: localhost
- name: Set port for serial console
debug:
msg: "Console port will set 48{{ ip.split('.')[3] }}"
Output:
TASK [IPV4 address lookup for node] ************************************************************************************************************************************************************************
ok: [hostA] => {
"ansible_facts": {
"ip": "10.100.100.25"
},
"changed": false
}
ok: [hostB] => {
"ansible_facts": {
"ip": "10.101.100.203"
},
"changed": false
}
TASK [Set port for serial console] *************************************************************************************************************************************************************************
ok: [hostA] => {
"msg": "Console port will set 4825"
}
ok: [hostB] => {
"msg": "Console port will set 48203"
}
The problem is that I also need to set the port after 48K for hostA. Can this be done with Ansible?
解决方案
You can use a jinja if/else
loop to set the value according to your desired logic. You will notice in one case we prefix the IP part with "48", while in the other with "480":
using a set_fact
task to calculate the port value:
- name: set the port with set_fact
set_fact:
console_port: "{% if ip.split('.')[3] | length == 3 %}48{{ ip.split('.')[3] }}{% elif ip.split('.')[3] | length == 2 %}480{{ ip.split('.')[3] }}{% endif %}"
Please note the current logic works only for 2 or 3 digits length, as you described it.
推荐阅读
- swift - 在编辑另一个 TextField 时更改一个 TextField
- javascript - React Slick Custom Carousel 与图像重叠 div
- glib - GLib-GIO-ERROR **:未安装设置架构“com.github.mfru.vala-todo”
- javascript - 如何使用循环创建 div。我在一本书中找到了这段代码,但它不起作用
- vue.js - 为什么 Vuex 的动作会返回一个承诺
? - javascript - Angular ngx-mat-datetime-picker 选择事件
- c# - Log4net 在记录几秒钟后将日志路径更改为安装文件夹。这是为什么?
- c++ - 将成员函数作为参数传递给不同标头中的父类
- android - 在自定义视图中处理变量 Drawable 的正确方法?
- python - 无法调用函数