Make Ansible retrieve the sudo password from my password manager. For a long time, I was wondering how to solve this issue. Ansible is my main tool to manage my own servers. All the infrastructure of the Services FACiLes project I contribute to (a future CHATONS is built with Ansible automation in mind, and even at my previous work, Ansible is used on a daily basis.
A thing that really annoyed me was that each time I run a playbook, I have to give Ansible my sudo password. Besides that, Ansible prompts for the password at an early stage of execution, even before trying to include all files or running a syntax check on them. Thus it isn't uncommon that Ansible fails immediately after because of a mistake I made in a playbook, and I have fix it, rerun the command, reenter my password… and so on. Which is very frustrated.
I know some workarounds exist to avoid dealing with the interactive sudo
password prompt: allowing Ansible to be executed without password on the servers (almost
equivalent to allowing any command to be executed without password…, which is
not an acceptable answer), storing your password into ansible_sudo_pass
variable in a cleartext file somewhere (yes you can encrypt it with
ansible-vault
but then you have to give the vault password each time you run
your playbook), trying to mess with except
…
The simple and elegant way of doing it for me would be that Ansible gets the password from an agent,
like gpg-agent
, or execute an arbitrary command to get it.
After a lot of research and experimentation, I found a pretty nice and clever
solution on Stackoverflow (far at the
bottom, it should be upvoted more than that IMHO). The idea is to combine --extra-var
ansible option (to which a file descriptor can be passed, while prefixing it with
@
) and <()
bash operator to convert a command's stdout to a file virtual
file descriptor. We end up with the following command:
$ ansible-playbook -e@<(echo "ansible_sudo_pass: $(pass Sysadmin/xxxx)") playbook.yml
This way my sudo password is retrieved from my pass
's password manager (which uses
gpg-agent) and I'm not bothered anymore with Ansible's interactive prompt \o/.
The only drawback is that I didn't find a way to set this into the ansible.cfg or somewhere else, except writing a bash alias or a small wrapper.