I would like to find the value between IP and IP using Ansible.
For example, I want to find IP address that between 192.168.0.25
and 192.168.0.30
. The expected results are as follow
{
"results": [
"192.168.0.25",
"192.168.0.26",
"192.168.0.27",
"192.168.0.28",
"192.168.0.29"
]
}
How can we derive the result value as above?
I tried to find a way to use the ipaddr
filter, but I couldn’t find it.
Thanks.
1
Get the indexes
ip_start: 192.168.0.25
ip_stop: 192.168.0.30
index_start: "{{ ip_start | split('.') | last }}"
index_stop: "{{ ip_stop | split('.') | last }}"
Declare the subnet and create the list of IPs
subnet: "{{ (ip_start ~ '/24') | ansible.utils.ipsubnet }}"
ip_range: "{{ subnet | ansible.utils.usable_range }}"
Get the slice
results: "{{ ip_range.usable_ips[index_start|int:index_stop|int] }}"
gives
results:
- 192.168.0.25
- 192.168.0.26
- 192.168.0.27
- 192.168.0.28
- 192.168.0.29
Example of a complete playbook for testing
- hosts: localhost
vars:
ip_start: 192.168.0.25
ip_stop: 192.168.0.30
index_start: "{{ ip_start | split('.') | last }}"
index_stop: "{{ ip_stop | split('.') | last }}"
subnet: "{{ (ip_start ~ '/24') | ansible.utils.ipsubnet }}"
ip_range: "{{ subnet | ansible.utils.usable_range }}"
results: "{{ ip_range.usable_ips[index_start|int:index_stop|int] }}"
tasks:
- debug:
var: subnet
- debug:
var: ip_range
- debug:
var: results
Optionally, get the indexes from the list of IPs
index_start: "{{ ip_range.usable_ips.index(ip_start) }}"
index_stop: "{{ ip_range.usable_ips.index(ip_stop) }}"