ansible ipv4 secondary IP filtering

2020-05-01 07:11发布

问题:

I have a jinja template that needs to be populated with my server's secondary ip's.

I tried running the following which provides me with a little bit more than what i need.

 tasks:
  - name: debug2
    debug: msg={{ ansible_enp0s8_iface1.ipv4_secondaries }}

Result

ok: [localhost] => {
"msg": [
    {
        "address": "172.16.2.20", 
        "broadcast": "172.16.2.255", 
        "netmask": "255.255.255.0", 
        "network": "172.16.2.0"
    }
]
}

However when i run the following

tasks:
  - name: debug2
    debug: msg={{ ansible_enp0s8_iface1.ipv4_secondaries.address }}

I get the following fatal error indicating "address" is undefined. I am not sure why this is happening since it works perfectly with the primary interface

fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'address'\n\nThe error appears to have been in '/root/test.yml': line 15, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    #debug: msg={{ ansible_enp0s8_iface1.ipv4_secondaries.address }}\n  - name: debug1\n    ^ here\n"}

回答1:

Note that ipv4_secondaries is displayed in a square brackets, this way you know that it's a list.

So you should choose an element from the list, e.g.:

ansible_enp0s8_iface1.ipv4_secondaries[0].address