I am new to ansible.
I have a file with multiple lines which has ipv4 address referenced in some lines. My use case is to replace the ipaddress in each of those lines with an incremented version of the same ip.
So if for example my file has lines as below:
The ip address in line is 10.1.1.1 and username test1
The ip address in line is 20.2.2.2 and username test2
I want to replace it as :
The ip address in line is 10.1.1.2 and username test1
The ip address in line is 20.2.2.3 and username test2
I am using the Ansible replace module to find ipv4 address in the line using regex and replace.
- name: Increment and Replace Ip address and
replace:
path: "config/changed-ip.txt"
regexp: "{{ '([0-9]{1,3}[\\.]){3}[0-9]{1,3}' }}"
replace: "{{ 'x.x.x.x' }}"
The above code replaces all ip address with the one I specified in the replace
Is there a way to extract the ip address from each line and increment it and replace the ipaddr in place of the old ip using any modules like lineinfile or replace?
I am running ansible 2.6
Try use this regex:
^(\d{1,3}\.){3}\d{1,3}
^
means start of string.
You can call a python script from the ansible playbook to execute the task you are interested in. The ipaddress module is useful if you want to do ip address arithmetics.
For instance:
---
- hosts: all
tasks:
- command: "python3 process_ip_addresses.py text"
The accompanying python is:
from ipaddress import IPv4Address
import re
import sys
file_path = sys.argv[1]
with open(file_path) as f:
text = f.read()
ip_addresses = re.findall( r'[0-9]+(?:\.[0-9]+){3}', text )
replacement_ip_addresses = [str(IPv4Address(address) + 1) for address in ip_addresses]
for old_address, new_addresss in zip(ip_addresses, replacement_ip_addresses):
text = text.replace(old_address, new_addresss)
with open(file_path, "w") as f:
f.write(text)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.