Yaml 可变增量IP地址
我正在将一个变量传递给ansible,其中包含Yaml 可变增量IP地址,yaml,ip-address,jinja2,ansible,Yaml,Ip Address,Jinja2,Ansible,我正在将一个变量传递给ansible,其中包含--额外变量“lan=10.10.10.1” 我现在需要增加这个ip地址,使最后一个八位元为.2,这样它将等于10.10.10.2 在ansible中如何实现这一点?一行: - set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{lan.split('.')[3] | int + 1 }}" 它是如何工作的 tasks: - name: Echo the pas
--额外变量“lan=10.10.10.1”
我现在需要增加这个ip地址,使最后一个八位元为.2,这样它将等于10.10.10.2
在ansible中如何实现这一点?一行:
- set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{lan.split('.')[3] | int + 1 }}"
它是如何工作的
tasks:
- name: Echo the passed IP
debug: var={{lan}}
- name: Extract the last octet, increment it and store it
set_fact: octet={{lan.split('.')[3] | int + 1 }}
- debug: var=octet
- name: Append the incremented octet to the first 3 octets
set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{octet}}"
- debug: var=new_ip
输出
TASK: [Echo the passed IP] ****************************************************
ok: [127.0.0.1] => {
"127.0.0.1": "{{ 127.0.0.1 }}"
}
TASK: [Extract the last octet, increment it and store it] *********************
ok: [127.0.0.1] => {"ansible_facts": {"octet": "2"}}
TASK: [debug var=octet] *******************************************************
ok: [127.0.0.1] => {
"octet": "2"
}
TASK: [Append the incremented octet to the first 3 octets] ********************
ok: [127.0.0.1] => {"ansible_facts": {"new_ip": "127.0.0.2"}}
TASK: [debug var=new_ip] ******************************************************
ok: [127.0.0.1] => {
"new_ip": "127.0.0.2"
}
在Ansible 2.7之前,您可能需要先看一看 使用: 小心Jinja2的运算符优先级,它非常时髦 表2.7+
使用。请参阅。自Ansible 2.7起,可通过以下方式完成:
如果要对子网执行此操作,这可能会很有帮助
- name: Give IP addresses sequentially from a subnet
debug:
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index) }}"
loop: "{{ list }}"
loop_control:
index_var: loop_index
在通过以下方式运行playbook之前,请不要忘记安装“NetAddress”Python库:
pip install netaddr
最后,请记住,index\u var从0开始,因此如果要从第一个IP地址开始,请使用以下命令切换消息行:
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index |int + 1) }}"
再次感谢helloV。我会看一看这个,因为我可能出于其他目的需要它。请注意,如果您将它与CIDR样式的地址(例如“192.0.2.0/24”一起使用,并且您想将其递增1,那么您需要首先获得网络地址-如下所示:
-set_事实:\n routerip:{((lan | IPADR('subnet')| IPADR('int'))+1)|ipaddr}“
根据Ansible 2.7,现在有了一个更简单的解决方案。请看我的答案。现在支持IP数学:ipmath(1)
Great,在Ansible/control端,ipmath
需要pythonnetaddr
包的beaware。
pip install netaddr
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index |int + 1) }}"