Reputation: 847
I am passing a variable to Ansible with --extra-vars "lan=10.10.10.1"
.
I now need to increment this IPaddress so that the last octet is .2
so it will equal 10.10.10.2
.
How would this be achieved in Ansible?
Upvotes: 4
Views: 9414
Reputation: 726
This can be helpful, if you want to do this with a subnet.
- name: Give IP addresses sequentially from a subnet
debug:
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index) }}"
loop: "{{ list }}"
loop_control:
index_var: loop_index
Please do not forget to install "netaddr" Python library before running the playbook via:
pip install netaddr
Lastly, please bear in mind that index_var starts from 0, so if you want to start it from the 1st IP address, switch the msg line with:
msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index |int + 1) }}"
Upvotes: 0
Reputation: 12745
Using the ipaddr
filter:
{{ ((lan | ipaddr('int')) + 1) | ipaddr }}
Be careful with the operator precedence of Jinja2, it's quite funky.
Use ipmath() filter. See the answer by Lars Francke.
Upvotes: 3
Reputation: 726
As of Ansible 2.7 this can be done using IP Math:
{{ lan | ipmath(1) }}
Upvotes: 11
Reputation: 52393
In one line:
- set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{lan.split('.')[3] | int + 1 }}"
How does it work?
tasks:
- name: Echo the passed IP
debug: var={{lan}}
- name: Extract the last octet, increment it and store it
set_fact: octet={{lan.split('.')[3] | int + 1 }}
- debug: var=octet
- name: Append the incremented octet to the first 3 octets
set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{octet}}"
- debug: var=new_ip
Output
TASK: [Echo the passed IP] ****************************************************
ok: [127.0.0.1] => {
"127.0.0.1": "{{ 127.0.0.1 }}"
}
TASK: [Extract the last octet, increment it and store it] *********************
ok: [127.0.0.1] => {"ansible_facts": {"octet": "2"}}
TASK: [debug var=octet] *******************************************************
ok: [127.0.0.1] => {
"octet": "2"
}
TASK: [Append the incremented octet to the first 3 octets] ********************
ok: [127.0.0.1] => {"ansible_facts": {"new_ip": "127.0.0.2"}}
TASK: [debug var=new_ip] ******************************************************
ok: [127.0.0.1] => {
"new_ip": "127.0.0.2"
}
Upvotes: 3