Add line in visudo after root line

1.1k Views Asked by At

I'm testing some Ansible deployment and need to add ansible user to sudoers. Instead of editing I just every time copy this script:

echo 'ansible ALL=(ALL)       NOPASSWD: ALL' | sudo EDITOR='tee -a' visudo

Which is adds ansible ALL=(ALL) NOPASSWD: ALL to the end of file.

How to add it after root line to make it like this via script?

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
ansible ALL=(ALL)       NOPASSWD: ALL
2

There are 2 best solutions below

0
On BEST ANSWER

Well, it seems a little kludgy, but...

Create a file called add_ansible.sed with the following line:

/^root/aansible ALL=(ALL) NOPASSWD: ALL

Then run your visudo like this:

sudo EDITOR='sed -i -f add_ansible.sed' visudo
0
On

If you really have to do it, make it part of the playbook.
Configuration management should not happen outside the tool to prevent drift.

  • template:
    src: templates/sudoers
    dest: /etc/sudoers
    validate: '/usr/sbin/visudo -cf %s'