我需要从Ansible Jinja2模板中的hostvars中提取特定接口的IPv4地址,而无需使用循环。
尝试从hostvars中提取“ ansible_eth1”对象是成功的,而Ansible为我提供了有关“ eth1”接口的所有信息:
- debug:
msg: "{{ groups['my_hosts'] | map('extract', hostvars, 'ansible_eth1') | join(', ') }}"
TASK [my_task : debug] *****************************************************************************************************************************************************************************************************
ok: [server1] => {
"msg": [
{
"active": true,
"device": "eth1",
...
"ipv4": {
"address": "192.168.56.15",
"broadcast": "192.168.56.255",
"netmask": "255.255.255.0",
"network": "192.168.56.0"
},
...
但是,如果我尝试提取嵌套对象-'ipv4.address'-它会返回空列表:
- debug:
msg: "{{ groups['my_hosts'] | map('extract', hostvars, 'ansible_eth1.ipv4.address') | join(', ') }}"
TASK [my_task : debug] *****************************************************************************************************************************************************************************************************
ok: [server1] => {
"msg": ", "
}
ok: [server2] => {
"msg": ", "
}
有可能吗?
答案 0 :(得分:0)
您要执行的行为由extract
section的最后一行指定,其中说:“过滤器的第三个参数也可以是列表,以便在容器内进行递归查找”
因此,在您的情况下:
msg: "{{ groups['my_hosts']
| map('extract', hostvars, ['ansible_eth1', 'ipv4', 'address'])
| join(', ') }}"