lipidal10
lipidal10

Reputation: 41

Replacing a word in a file with Ansible

I was trying to replace one string in a file. For example:

$PASSWORD="oldpassword"

with:

$PASSWORD="newpassword"

Here is the Ansible task which should do this:

- name: change password with lineinfile 
  lineinfile:
    dest: test.txt
    regexp: '^$PASSWORD='
    line: '^$PASSWORD="newpassword"'
    state: present
    backrefs: yes 

Unfortunately I can't find the reason why it isn't working. I cannot replace it with the new string.

I was also trying without backrefs and the string was added instead of replaced.

Please advise. Thank you.

Upvotes: 3

Views: 11850

Answers (2)

Rajesh gherade
Rajesh gherade

Reputation: 1

- lineinfile:
      dest: /tmp/test.txt
      regexp: "^PASSWORD=.+"
      line: "PASSWORD=\"newpassword"\"
  

Hi, this code worked for me.

Upvotes: -1

helloV
helloV

Reputation: 52375

From Regular expression operations:

$: Matches the end of the string or just before the newline at the end of the string

So, escape $ with backslash.

  - lineinfile:
      dest: /tmp/test.txt
      regexp: '^\$PASSWORD='
      line: '$PASSWORD="newpassword"'
      state: present

Also you don't need to use the backrefs parameter with your example, because your regular expression doesn't have backreferences.

Upvotes: 6

Related Questions