简体   繁体   中英

Conditional jinja2 ipaddr filter in ansible task

I'm trying to apply a task to hosts based on ip block so I've got this.

- name: Conditional task
  debug: msg="{{ ansible_all_ipv4_addresses | ipaddr('192.168.1.0/24') | length > 0 }}"
  when: { ansible_all_ip4_addresses | ipaddr('192.168.1.0/24') | length > 0 }

The debug statement is working as expected, returning the correct value for each host, but the condition is not working, it gets executed in all hosts. If I remove the brackets in the when clause, then I get

 ERROR! error while evaluating conditional

I've tried to define a fact with:

    - set_fact:
      local: "{{ ansible_all_ip4_addresses | ipaddr('192.168.1.0/24') | length > 0 }}"

But instead I get

 ERROR! One or more undefined variables: 'ansible_all_ip4_addresses' is undefined

Any help greatly appreciated

You got a typo there. ansible_all_ip4_addresses has to be ansible_all_ipv4_addresses , the v before 4 is missing.

Apart from that it would work with none or 2 curly brackets, but not with one:

when: ansible_all_ipv4_addresses | ipaddr('192.168.1.0/24') | length > 0

or

when: "{{ ansible_all_ipv4_addresses | ipaddr('192.168.1.0/24') | length > 0 }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM