Ansible - Determine if an IP address is valid in a Subnet using ansible.utils.ipaddr
by
Jeremy Canfield |
Updated: February 27 2024
| Ansible articles
There are two similar but distinct "ipaddr" modules.
- ansible.netcommon.ipaddr
- ansible.utils.ipaddr
ansible.netcommon.ipaddr is being deprecated, so you should almost always use ansible.utils.ipaddr.
[DEPRECATION WARNING]:
Use 'ansible.utils.ipaddr' module instead.
This feature will be removed from ansible.netcommon in a release after 2024-01-01.
You may need to install the ansible.utils collections.
ansible-galaxy collection install ansible.utils
ansible.utils.network_in_unable can be used to determine if an IP address is valid in a particular subnet. For example, in 10.0.0.0/24 the first available IP address is 10.0.0.1 and the last available IP address is 10.0.0.254.
---
- hosts: localhost
tasks:
- name: this will return "false" because 10.0.0.0 is NOT an available IP address in 10.0.0.0/24
debug:
msg: "{{ '10.0.0.0/24' | ansible.utils.network_in_usable('10.0.0.0') }}"
- name: this will return "true" because 10.0.0.1 is an available IP address in 10.0.0.0/24
debug:
msg: "{{ '10.0.0.0/24' | ansible.utils.network_in_usable('10.0.0.1') }}"
- name: this will return "true" because 10.0.0.254 is an available IP address in 10.0.0.0/24
debug:
msg: "{{ '10.0.0.0/24' | ansible.utils.network_in_usable('10.0.0.254') }}"
- name: this will return "false" because 10.0.0.255 NOT an available IP address in 10.0.0.0/24
debug:
msg: "{{ '10.0.0.0/24' | ansible.utils.network_in_usable('10.0.0.255') }}"
...
Running this playbook should return the following.
TASK [this will return "false" because 10.0.0.0 is NOT an available IP address in 10.0.0.0/24]
ok: [localhost] => {
"msg": false
}
TASK [this will return "true" because 10.0.0.1 is an available IP address in 10.0.0.0/24]
ok: [localhost] => {
"msg": true
}
TASK [this will return "true" because 10.0.0.254 is an available IP address in 10.0.0.0/24]
ok: [localhost] => {
"msg": true
}
TASK [this will return "false" because 10.0.0.255 NOT an available IP address in 10.0.0.0/24]
ok: [localhost] => {
"msg": false
}
Did you find this article helpful?
If so, consider buying me a coffee over at