Search code examples
ansiblesudo

How to let ansible to run sudo only once for multiple tasks requiring sudo?


When ansible runs multiple tasks as root (become: yes, become_method: sudo), I found that it runs each task in separate sessions:

john.doe    481901  481809  0 19:44 pts/0    00:00:00 /bin/sh -c sudo -H -S  -p "[sudo via ansible, key=blabla1] password:" -u root /bin/sh -c 'echo BECOME-SUCCESS-blabla1 ; /usr/bin/python3 /home/john.doe/.ansible/tmp/ansible-tmp-1609789454.667826-84063-275493394187528/AnsiballZ_command.py' && sleep 0

john.doe    481937  481809  0 19:44 pts/0    00:00:00 /bin/sh -c sudo -H -S  -p "[sudo via ansible, key=blabla2] password:" -u root /bin/sh -c 'echo BECOME-SUCCESS-blabla2 ; /usr/bin/python3 /home/john.doe/.ansible/tmp/ansible-tmp-1609789496.208312-84094-182235695212206/AnsiballZ_command.py' && sleep 0

and as a result of this, it does not use sudo cache (/var/run/sudo/ts/john.doe) but to authenticate each time. It is not an issue if you only use password authentication because you specify the password once using --ask-become-pass, however when I used Duo Mobile as a second factor to authenticate, it pushes each time when sudo is authenticated. So if you have multiple hosts and multiple tasks, you have to constantly answer the push, and when push is delayed when there is a "denial attack", ansible run will fail.

My questions:

  1. Is there a way to let ansible to sudo once, and then run multiple tasks? Using the above example, it can and should run each of the AnsiballZ_command.py files after a single sudo authentication.
  2. Is there another to prevent the Duo Mobile paging?

Solution

  • There is no answer for the question. The three workarounds are:

    1. At the beginning of the ansible task, disable sudo password:
    perl -i -pe 's/(?<=\s)PASSWD/NOPASSWD/' /etc/sudoers.d/$(who am i | sed "s/\./-/; s/ .*//")
    

    and at the end, enabled it (swap the PASSWD and NOPASSWD in above code).

    1. At the beginning of the run, disable the Duo authentication at the duo console (manually or with API call), and at the end re-enable it.
    2. Setup an ansible user without Duo authentication, but this is less secure as compared with #2, but still a workaround if your security requirement allows it.

    PS: You can use ssh keys to authenticate sudo, see this link.