Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a line from a file using ansible?

Tags:

ansible

I have a file called authorized_keys. I need to delete a particular line using an Ansible script.

The problem is when I try to remove a line that includes a '+' character. Ansible is not able to remove this line.

e.g authorized_keys file is:

 .....
 abhi foo+bar saken
 ......(EOF)

I want to remove the abhi foo+bar saken line but Ansible is not removing this line because of the + character.

I am able to remove lines that do not contain a + character .

Task:

- name: Delete keys in sysadmin/.ssh/authoriezd_keys
  lineinfile: dest=/home/{{name}}/.ssh/authorized_keys
              state=absent 
              regexp='^{{key}}$' 

PS: I am using Ansible's lineinfile module

like image 909
Birendra Kumar Avatar asked Feb 25 '15 11:02

Birendra Kumar


People also ask

How do you change a line in a file using Ansible?

To modify a line, you need to use the Ansible backrefs parameter along with the regexp parameter. This should be used with state=present. If the regexp does not match any line, then the file is not changed. If the regexp matches a line or multiple lines, then the last matched line will be replaced.

How do I use Lineinfile?

If specified, the line will be inserted after the last match of specified regular expression. If the first match is required, use(firstmatch=yes). A special value is available; EOF for inserting the line at the end of the file. If specified regular expression has no matches, EOF will be used instead.

What is Backrefs Ansible?

backrefs. boolean. added in 1.1 of ansible.builtin. Used with state=present . If set, line can contain backreferences (both positional and named) that will get populated if the regexp matches.


1 Answers

The problem probably is that + has a meaning in a regular expression.

You should be able to fix it by escaping the +. If you can't do that from the source where {{ key }} is defined, you can escape it with the replace Jinja filter:

- name: Delete keys in sysadmin/.ssh/authoriezd_keys
  lineinfile: dest=/home/{{name}}/.ssh/authorized_keys
              state=absent
              regexp='^{{ key | replace("+", "\+") }}$'

You might run into more problems if {{ key }} contains other characters which have a meaning in regular expressions. If that's the case I think the safe way would be to create your own filter plugin where you simply return the input passed through re.escape.

like image 109
udondan Avatar answered Sep 28 '22 03:09

udondan