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?
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"
}