Miantian
Miantian

Reputation: 1075

How to replace character in files with Ansible?

For this ansible task:

- name: wheel sudoers
  shell: sed -i -e "s/# %wheel\tALL=(ALL)\tNOPASSWD: ALL/%wheel\tALL=(ALL)\tNOPASSWD: ALL/g" /etc/sudoers

Need to replace # %wheel\tALL=(ALL)\tNOPASSWD: ALL with %wheel\tALL=(ALL)\tNOPASSWD: ALL.

But this syntax got an error after the first NOPASSWD: area:

X mapping values are not allowed in this context

Why can't I use this syntax?

Upvotes: 2

Views: 1094

Answers (1)

toydarian
toydarian

Reputation: 4584

First of all:
You should not use shell with sed in ansible, but the replace module.
E.g.:

- name: Allow sudo without password
  ansible.builtin.replace:
    path: /etc/sudoers
    regexp: '# %wheel\tALL=\(ALL\)\tNOPASSWD: ALL'
    replace: '%wheel ALL=(ALL) NOPASSWD: ALL'

Check out the python doc on how to write a correct regex, espc. for tabs (\t) and brackets.
Check out this question about how to manage sudoers as well.

Second:
Your code is not working because you do not quote your string correctly.
This should work (kudos to Zeitonautor):

shell: "sed -i -e \"s/# %wheel\\tALL=(ALL)\\tNOPASSWD: ALL/%wheel\\tALL=(ALL)\\tNOPASSWD: ALL/g\" /etc/sudoers"

Also check this post about using \t with sed. Using \t will not work with every version of sed.

Again: Do NOT use this! Use the replace module instead!

Upvotes: 4

Related Questions