Lucky me
Lucky me

Reputation: 63

Ansible replace multiple lines from variable

I have the following Ansible variable:

test_entries:
    "
    test-auth-ip=192.168.1.22
    test-auth-serv=example1.com
    test-auth-net=192.168.1.254
    test-auth-blabla=test123 
    "

I also have a text file which contains the following lines:

   test-auth-str1=null
   test-auth-str2=null
   test-auth-serv=null
   test-auth-net=0.0.0.0
   test-auth-str3=null
   test-auth-str4=null

I would like to be able to replace any line from the file which matches line from the variable until the "=" sign. (regex: ^test-auth(.*?=))

I read the Ansible doc. for "lineinfile" and "replace" functionalities. However, I couldn't find how to match line by line with regex.

Expected result

 test-auth-str1=null
 test-auth-str2=null
 test-auth-serv=example1.com
 test-auth-net=192.168.1.254
 test-auth-str3=null
 test-auth-str4=null

Upvotes: 2

Views: 7897

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15273

Try

test_entries:
 test-auth-ip     : 192.168.1.22
 test-auth-serv   : example1.com
 test-auth-net    : 192.168.1.254
 test-auth-blabla : test123

then in your task -

- replace:
    path: /your/file
    regexp: '^{{ item.key }}=.*$'
    replace: '{{ item.key }}={{ item.value }}'
  with_dict: "{{ test_entries }}"

I also often use an array of anonymous dictionaries, and whatever I named the attributes instead of key and value. The major differences are that it lets you control order (which doesn't seem to matter here) and skip the key & value keywords.

Upvotes: 5

Related Questions