In Ansible, is it possible to test if an IP address is part of a list of subnets?
I.e.: I have a list of subnets, ['10.10.10.0/24','10.10.12.0/24']
, and an IP address: 10.10.12.8
.
How would I test if the IP address is part of the subnets with a when
statement?
The IP manipulations tends to be in the ansible.utils
collection, and indeed the first test you can find in this collection is the test in_any_network
, which will help you achieve what you are looking for.
Given:
- ansible.builtin.debug:
msg: "{{ _ip }} is in {{ _networks }}"
when: _ip is ansible.utils.in_any_network _networks
vars:
_ip: 10.10.12.8
_networks: ['10.10.10.0/24','10.10.12.0/24']
You will get:
ok: [localhost] =>
msg: 10.10.12.8 is in ['10.10.10.0/24', '10.10.12.0/24']