Reputation: 159
I have written a playbook that will be adding a new IP address to the list of IP address. This is the code
- name: adding IP to faile2ban
lineinfile:
path: /home/ec2-user/test.conf
line: "{{ new_server_ip }}"
insertafter: "^#?ip_list"
https://github.com/shettypriy/ansible/blob/master/addingIPto%20the%20end .The IP gets added to the file but it does not get added at the end of the last added IP
I have a file test.conf where IP address are added. I want to add the new IP after the last updated IP Example: following is the sample content of the file test.conf
ip_list = xx.xx.xx.xx yy.yy.yy.zz aa.aa.aa.aa
My desired output should be 'new_server_ip' added after aa.aa.aa.aa
Upvotes: 0
Views: 271
Reputation: 67984
The task below does the job and is idempotent
"Modules should be idempotent, that is, running a module multiple times in a sequence should have the same effect as running it just once."
- lineinfile:
dest: /home/ec2-user/test.conf
regexp: '(?!.*{{ new_server_ip }}.*)^(ip_list.*)$'
line: '\1 {{ new_server_ip }}'
backrefs: yes
The regexp first look ahead and match the line only if new_server_ip is not present.
Upvotes: 1
Reputation: 111
I guess the following should work for you well:
- name: adding IP to faile2ban
lineinfile:
dest: /home/ec2-user/test.conf
state: present
regexp: "^(#?ip_list(.*)$)"
backrefs: yes
line: '\1 {{ new_server_ip }}'
So the point is that you find row started with 'ip_list', select whole line by the regexp and then backrefencing selected row in your line in front of new_server_ip.
Upvotes: 1