If you run an Ansible task that requires a privilege escalation, i.e. with become: true, you may get an error “sudo: a password is required”.
This happens when Ansible needs to run some command with sudo but it doesn’t know the password.
In this note i will show how to make the ansible-playbook command prompt for a password at a runtime and how to pass the password non-interactively during automated deployment.
Cool Tip: Enable DEBUG mode and increase VERBOSITY in Ansible! Read more →
Ansible – “sudo: a password is required”
A typical “sudo: a password is required” error in a verbose mode looks like this:
fatal: [hostname]: FAILED! => {
"changed": false,
"module_stderr": "sudo: a password is required\n",
"module_stdout": "",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
Method #1: Ask Sudo Password in Ansible
To ask for a sudo password at a runtime, use the --ask-become-pass option:
$ ansible-playbook playbook.yml -i inventory.ini --ask-become-pass ... BECOME password:
Method #2: Set Ansible Sudo Password Variable
Non-interactively the password can be passed as an ansible_become_password variable:
$ ansible-playbook playbook.yml -i inventory.ini -e "ansible_become_password=p@$$w0rd"
Warning: From the security perspective the method above is not recommended as the plain-text password may be stored in a commands history file and will be shown in the process list during the command execution, so the other users could see it!
Method #3: Store Sudo Password in Ansible Vault
Cool Tip: How to encrypt & decrypt a string using Ansible Vault! Read more →
The better way is to use an an Ansible Vault to create a new file named password.yml with the encrypted sudo password:
$ ansible-vault edit password.yml
password.yml file in a text editor where you can put your ansible_become_password:
ansible_become_password: p@$$w0rd
Save and exit. Next create a vault.txt file with the password that you used while creating the password.yml file, e.g:
$ echo "vaultPassw0rd" > vault.txt
Ensure permissions on vault.txt are such that no one else can access it and do not add this file to a source control:
$ chmod 600 vault.txt $ echo "vault.txt" >> .gitignore
Finally run your playbook as follows:
$ ansible-playbook playbook.yml -i inventory.ini -e '@password.yml' \
--vault-password-file=vault.txt
Method #4: Disable Sudo Password for Ansible User
Alternatively you can allow an Ansible user on a target machine to execute sudo without being prompted for a password – for this on the target machine execute:
$ sudo visudo
And append a line as follows:
ansibleUserName ALL=(ALL) NOPASSWD:ALL
Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →
This might also be due to `delegate_to: localhost` in your task, changing your user from root to whatever your local user is.