【发布时间】:2016-01-07 21:41:33
【问题描述】:
我正在使用--extra-vars "lan=10.10.10.1" 将变量传递给ansible
我现在需要增加这个 IP 地址,以便最后一个八位字节为 .2,因此它等于 10.10.10.2。
如何在 ansible 中实现这一点?
【问题讨论】:
标签: yaml ip-address jinja2 ansible
我正在使用--extra-vars "lan=10.10.10.1" 将变量传递给ansible
我现在需要增加这个 IP 地址,以便最后一个八位字节为 .2,因此它等于 10.10.10.2。
如何在 ansible 中实现这一点?
【问题讨论】:
标签: yaml ip-address jinja2 ansible
从 Ansible 2.7 开始,可以使用 IP Math:
{{ lan | ipmath(1) }}
【讨论】:
ipmath 在 Ansible/control 端需要 python netaddr 包。
一行:
- 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"
}
【讨论】:
您可能想看看ipaddr filter
【讨论】:
{{ ((lan | ipaddr('int')) + 1) | ipaddr }}
注意 Jinja2 的运算符优先级,它很时髦。
【讨论】:
- set_fact:\n router_ip: "{{ (( lan | ipaddr('subnet') | ipaddr('int') ) + 1) | ipaddr }}"
ipmath(1)
如果您想对子网执行此操作,这会很有帮助。
- 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 之前,请不要忘记安装“netaddr” Python 库:
pip install netaddr
最后,请记住index_var从0开始,所以如果你想从第一个IP地址开始,切换味精行:
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index |int + 1) }}"
【讨论】: