Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match a specific word within square brackets using regex

Tags:

regex

ansible

I have a file /home/ec2-user/hosts in which there is a group called [sample_word_test] with the square brackets and I want to add an Ip address under this group using ansible playbook. I want to match [sample_word_test] using lineinfile regex expression and add Ip address under that matching group

Following is my playbook code

lineinfile:
    path: /home/ec2-user/hosts
    regexp: "\[.*?sample_word_test.*$\]"
    line: "{{ new_server_ip }}"
    backup: yes
like image 493
user11549576 Avatar asked Sep 13 '25 08:09

user11549576


1 Answers

The very simple solution is to use ini_file. The task below does what is requested.

- ini_file:
    path: /home/ec2-user/hosts
    section: sample_word_test
    option: "{{ new_server_ip }}"
    allow_no_value: yes
    backup: yes

For example

$ cat hosts
[all]
test1
test2

[sample_word_test]
192.168.1.99
like image 118
Vladimir Botka Avatar answered Sep 16 '25 05:09

Vladimir Botka