Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible sudo command without password checking

Tags:

sudo

ansible

I would like to use ansible in a full automated context, where I cannot manually type passwords. To deal with this, I connect the servers with SSH public key, and I whitelisted severals commands such as apt-get install * in my sudoers configuration so I do not need a password to run them. For instance sudo apt-get install git.

However if the setting become is True in a playbook, ansible asks me for a password it does not need.

  • How can I tell ansible to run a command as sudo, without asking me a password?
  • Do you know another way to install apt packages without password?
  • Should I use another become method?

sudoers conf

myuser ALL = NOPASSWD: /usr/bin/apt-get install *

ansible

- name: install the latest version of ntpdate
  package:
    name: ntpdate
    state: latest
  become: True

Produces this output:

failed: [x.x.x.x] (item=ntpdate) => {"failed": true, "item": "python3-dev", "module_stderr": "", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE", "rc": 1}
like image 928
azmeuk Avatar asked Oct 27 '25 14:10

azmeuk


2 Answers

The simple answer is that you cannot do it without enabling all commands (or at least python).

Ansible does not run the commands as you expect it to run. It runs Python scripts. You can see the exact command when you execute ansible-playbook with -vvv. They are much more complex and to enable them you would have to add them to sudoers, for example:

sudo -H -S -n -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-xxxxxx;
  /usr/bin/python /var/www/.ansible/tmp/ansible-tmp-xxxxxxxx/apt.py;
  rm -rf "/var/www/.ansible/tmp/ansible-tmp-xxxxxxxx/" > /dev/null 2>&1'"'"'
  && sleep 0

The tricky part is that all spaces, quotes, and other special characters are relevant and until you get the correct command pattern by trial and error, replacing characters with wildcards, the system will not allow the command to run with elevated privileges. Effectively you won't be able to whitelist all the commands Ansible runs.

The only exception is raw module which runs the given command intact.

like image 96
techraf Avatar answered Oct 29 '25 07:10

techraf


In all the Ansible playbooks I have worked on, I had to do only 2 things so that tasks run with become:True

  1. Create file /etc/sudoers.d/demo on the target hosts with below content:

    demo ALL=(ALL) NOPASSWD:ALL

  2. Copy ssh id from Ansible host to target host using ssh-copy-id

like image 32
Tejaswi Avatar answered Oct 29 '25 06:10

Tejaswi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!