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
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With