Introduction
Ansible is a powerful automation tool that helps manage and configure servers without requiring manual intervention. However, many Ansible tasks require elevated permissions to execute properly. When running commands that need administrator privileges, Ansible uses the sudo mechanism, which might prompt for a password.
In this lab, you will learn how to properly configure sudo password settings in Ansible playbooks, understand common sudo-related issues, and implement best practices to ensure your automation runs smoothly with the necessary permissions.
Installing Ansible and Creating a Basic Playbook
In this first step, we will install Ansible and create a simple playbook that requires sudo privileges. This will help us understand the basic requirements for running Ansible tasks with elevated permissions.
Installing Ansible
Let's start by installing Ansible on our system. Open a terminal and run the following commands:
sudo apt update
sudo apt install -y ansible
After the installation completes, verify that Ansible was installed correctly:
ansible --version
You should see output similar to this, showing the Ansible version and configuration information:
ansible [core 2.12.x]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/labex/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
ansible collection location = /home/labex/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible
python version = 3.10.x (main, Ubuntu, linux/x86_64)
jinja version = 3.0.3
libyaml = True
Create a Basic Ansible Playbook
Now, let's create a simple Ansible playbook that requires sudo privileges. This playbook will install the htop package on the local system.
Create a new directory for your Ansible project:
mkdir -p ~/project/ansible-sudo-lab
cd ~/project/ansible-sudo-lab
Next, create the inventory file that defines the hosts Ansible will manage. For this lab, we'll use localhost:
echo "localhost ansible_connection=local" > inventory
Now, create a basic playbook that requires sudo privileges. Open VSCode editor and create a new file named basic_playbook.yml:
- Click on "File" in the WebIDE menu
- Select "New File"
- Copy and paste the following content:
---
- name: Basic sudo operation
hosts: localhost
become: true ## This enables sudo
tasks:
- name: Install htop
apt:
name: htop
state: present
update_cache: yes
- Save the file as
~/project/ansible-sudo-lab/basic_playbook.yml
This playbook has the become: true directive, which tells Ansible to use sudo for running the tasks. The task itself attempts to install the htop package using the apt module.
Run the Playbook
Now, let's run our playbook and observe what happens:
cd ~/project/ansible-sudo-lab
ansible-playbook -i inventory basic_playbook.yml
Since the labex user has password-less sudo access, the playbook should run successfully without prompting for a password. You should see output similar to this:
PLAY [Basic sudo operation] ******************************************
TASK [Gathering Facts] **********************************************
ok: [localhost]
TASK [Install htop] ************************************************
ok: [localhost]
PLAY RECAP *********************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
The playbook ran successfully because our current user (labex) is already configured with password-less sudo access. In the next steps, we'll explore how to handle scenarios where a sudo password is required.
Understanding Sudo Password Configuration in Ansible
In the previous step, we created a basic playbook that used sudo privileges without requiring a password. However, in many real-world scenarios, you will need to provide a sudo password to execute privileged commands. Let's explore how to handle sudo passwords in Ansible.
How Ansible Handles Sudo Passwords
When Ansible needs to run a command with elevated privileges on a remote system, it uses the become functionality. By default, Ansible uses the sudo command for privilege escalation, but you can configure it to use other methods like su, pbrun, or pfexec.
If the user running Ansible requires a password to use sudo, Ansible needs to know this password. There are several ways to provide the sudo password to Ansible:
- Command-line option:
-Kor--ask-become-pass - Playbook variable:
become_password - Configuration file:
ansible.cfg - Ansible Vault: For securely storing passwords
Creating a Test User with Sudo Password Requirement
To demonstrate how to handle sudo passwords, let's create a test user that requires a password for sudo operations:
sudo adduser ansible_test
When prompted, enter the password ansible123 and complete the user creation process.
Next, let's give this user sudo privileges but require a password:
echo "ansible_test ALL=(ALL) ALL" | sudo tee /etc/sudoers.d/ansible_test
This configuration allows the ansible_test user to use sudo, but it will require the user's password each time.
Creating a Playbook with Sudo Password Handling
Now, let's create a playbook that demonstrates how to handle sudo passwords. Create a new file named sudo_password_playbook.yml in the WebIDE:
---
- name: Playbook with sudo password handling
hosts: localhost
become: true
## We'll provide the become_password when running the playbook
tasks:
- name: Get current user
command: whoami
register: current_user
become: false ## This task doesn't need sudo
- name: Print current user
debug:
msg: "Current user is {{ current_user.stdout }}"
become: false ## This task doesn't need sudo
- name: Run a command with sudo
command: apt update
register: sudo_output
- name: Print sudo command result
debug:
msg: "Command ran with sudo: {{ sudo_output.rc == 0 }}"
Save this file as ~/project/ansible-sudo-lab/sudo_password_playbook.yml
Running the Playbook with Password Input
When you want to run a playbook as a user that requires a sudo password, you can use the -K (or --ask-become-pass) option to prompt for the password:
ansible-playbook -i inventory sudo_password_playbook.yml -K
Since we're running as the labex user which has password-less sudo, you won't actually be prompted for a password. However, in a production environment where password-less sudo is not configured, Ansible would prompt you to enter the sudo password.
To simulate this scenario with our test user, you can run the following command (although it won't fully work in this lab environment due to missing SSH setup):
ansible-playbook -i inventory sudo_password_playbook.yml -u ansible_test -K
When prompted for the BECOME password, you would enter ansible123.
Specifying the Sudo Password in an Ansible Variable
Instead of entering the password interactively, you can provide the sudo password as a variable when running the playbook:
ansible-playbook -i inventory sudo_password_playbook.yml -e "ansible_become_password=ansible123"
This approach is useful for automated scripts where interactive input is not possible. However, it exposes the password in command-line history, which is a security risk. In a production environment, you should use Ansible Vault to securely store sensitive information.
Using Ansible Vault for Secure Password Management
In the previous step, we explored different ways to provide sudo passwords to Ansible playbooks. However, storing passwords in plaintext files or passing them on the command line is not secure. In this step, we'll learn how to use Ansible Vault to securely manage sensitive information like sudo passwords.
What is Ansible Vault?
Ansible Vault is a feature that allows you to encrypt sensitive data such as passwords, API keys, or certificates. The encrypted files can be safely stored in version control systems without exposing the sensitive information. Ansible can automatically decrypt these files during playbook execution.
Creating an Encrypted Vault File
Let's create an encrypted file to store our sudo password:
cd ~/project/ansible-sudo-lab
ansible-vault create vault.yml
You will be prompted to create a new vault password. Enter vaultpassword123 and confirm it.
After setting the vault password, an editor will open. Enter the following content in the editor:
---
vault_sudo_password: ansible123
Save the file and exit the editor.
Now, if you try to view the content of the vault file, you'll see that it's encrypted:
cat vault.yml
You should see output similar to:
$ANSIBLE_VAULT;1.1;AES256
32623438613466396238613731623338376461653866353031313632316237613561393639613131
3562626166616332386265373761653835356134613561380a363761333362323238663136633439
32343032333832313562353261333530666639643239303436643363393630643639316232303564
3962356162356361370a313038333432353162333462323035323262396233333039326535356662
31363539613432656362326565613232336535393232653939323466323131393362
Using Vault Variables in a Playbook
Now, let's create a playbook that uses the encrypted sudo password. Create a new file named secure_sudo_playbook.yml:
---
- name: Playbook with secure sudo password
hosts: localhost
become: true
become_password: "{{ vault_sudo_password }}"
vars_files:
- vault.yml
tasks:
- name: Get sudo user
command: whoami
register: sudo_user
- name: Print sudo user
debug:
msg: "Running as {{ sudo_user.stdout }}"
- name: Check sudo access
command: apt update
register: apt_result
failed_when: false
- name: Print result
debug:
msg: "Sudo access successful: {{ apt_result.rc == 0 }}"
Save this file as ~/project/ansible-sudo-lab/secure_sudo_playbook.yml
Running a Playbook with Vault
When you run a playbook that includes an encrypted vault file, you need to provide the vault password. There are several ways to do this:
- Using the
--ask-vault-passoption:
ansible-playbook -i inventory secure_sudo_playbook.yml --ask-vault-pass
When prompted, enter the vault password: vaultpassword123
- Using a vault password file:
First, create a file containing the vault password:
echo "vaultpassword123" > vault_password_file
chmod 600 vault_password_file
Then run the playbook with the password file:
ansible-playbook -i inventory secure_sudo_playbook.yml --vault-password-file vault_password_file
You should see output similar to:
PLAY [Playbook with secure sudo password] ***************************
TASK [Gathering Facts] **********************************************
ok: [localhost]
TASK [Get sudo user] ***********************************************
changed: [localhost]
TASK [Print sudo user] *********************************************
ok: [localhost] => {
"msg": "Running as root"
}
TASK [Check sudo access] *******************************************
changed: [localhost]
TASK [Print result] ************************************************
ok: [localhost] => {
"msg": "Sudo access successful: True"
}
PLAY RECAP *********************************************************
localhost : ok=5 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Best Practices for Sudo Password Management
Here are some best practices to follow when managing sudo passwords in Ansible:
- Always use Ansible Vault to encrypt sensitive information
- Never store vault passwords in version control
- Use a secure method to distribute vault passwords (e.g., password manager)
- Consider using a vault ID for different environments (dev, staging, production)
- Rotate vault passwords regularly
In a production environment, you might also consider using a tool like HashiCorp Vault or AWS Secrets Manager for even more secure secrets management.
Troubleshooting Common Sudo Password Issues
Even with proper configuration, you might encounter issues with sudo passwords in Ansible. In this step, we'll explore common problems and their solutions.
Common Sudo Password Issues
Here are some common issues you might encounter when using sudo with Ansible:
- Missing sudo password: Ansible cannot find the sudo password to execute privileged commands.
- Incorrect sudo password: The provided sudo password is incorrect.
- Sudo configuration issues: The target user does not have the correct sudo permissions.
- Sudo requires a TTY: Some systems require a TTY to be allocated for sudo commands.
Let's explore each of these issues and their solutions.
Creating a Problematic Environment for Testing
To better understand these issues, let's create a scenario where sudo requires a TTY. Edit the sudoers file for our test user:
sudo cp /etc/sudoers.d/ansible_test /etc/sudoers.d/ansible_test.bak
echo 'Defaults:ansible_test requiretty' | sudo tee -a /etc/sudoers.d/ansible_test
This configuration makes sudo require a TTY when the ansible_test user runs sudo commands, which can cause issues with Ansible.
Creating a Troubleshooting Playbook
Create a new playbook named troubleshoot_sudo.yml that includes some common sudo troubleshooting techniques:
---
- name: Troubleshoot sudo issues
hosts: localhost
become: true
become_method: sudo
## We'll provide the become_password when running the playbook
tasks:
- name: Check sudo version
command: sudo --version
register: sudo_version
become: false
- name: Print sudo version
debug:
msg: "{{ sudo_version.stdout_lines[0] }}"
become: false
- name: Check sudo configuration
command: sudo -l
register: sudo_config
become: false
failed_when: false
- name: Print sudo configuration
debug:
msg: "{{ sudo_config.stdout_lines }}"
become: false
when: sudo_config.rc == 0
- name: Test sudo command with pty
command: apt update
register: sudo_test
failed_when: false
vars:
ansible_become_flags: "-H"
- name: Print sudo test result
debug:
msg: "Sudo command {{ 'succeeded' if sudo_test.rc == 0 else 'failed' }}"
Save this file as ~/project/ansible-sudo-lab/troubleshoot_sudo.yml
Running the Troubleshooting Playbook
Run the troubleshooting playbook:
ansible-playbook -i inventory troubleshoot_sudo.yml -K
Since we're running as the labex user which has password-less sudo, the playbook should execute successfully.
Common Solutions to Sudo Password Issues
Here are solutions to common sudo password issues:
1. Missing sudo password
If Ansible fails with a message like "Missing sudo password", you can:
- Use the
-Koption to prompt for the sudo password - Set the
ansible_become_passwordvariable in your inventory or playbook - Use Ansible Vault to securely store and provide the sudo password
2. Incorrect sudo password
If the sudo password is incorrect:
- Double-check the password you're providing
- Verify that the user's password hasn't expired or been changed
- Check if the sudo configuration has changed on the target system
3. Sudo configuration issues
If the user doesn't have the correct sudo permissions:
- Check the sudoers file on the target system
- Verify that the user is in the correct groups
- Use
sudo -lto check the user's sudo privileges
4. Sudo requires a TTY
If sudo requires a TTY:
- Add
ansible_become_flags: "-H"to your playbook or inventory - Modify the sudoers file to remove the
requirettyoption - Use the
pty: trueoption in your tasks
Restore the Original Sudo Configuration
Let's restore the original sudo configuration for our test user:
sudo cp /etc/sudoers.d/ansible_test.bak /etc/sudoers.d/ansible_test
sudo rm /etc/sudoers.d/ansible_test.bak
This removes the requiretty option that we added earlier.
Summary
In this lab, you have learned how to handle sudo passwords in Ansible playbooks, a common challenge for many administrators and DevOps engineers. Here is a summary of what you accomplished:
- You installed Ansible and created a basic playbook that uses sudo privileges
- You learned different methods for providing sudo passwords to Ansible playbooks
- You used Ansible Vault to securely store and manage sensitive information
- You explored common sudo password issues and learned how to troubleshoot them
These skills will help you create more secure and reliable Ansible playbooks that can handle various sudo configurations across different environments.
Key takeaways from this lab:
- Always use secure methods like Ansible Vault to store sensitive information
- Understand the different ways to provide sudo passwords to Ansible
- Know how to troubleshoot common sudo password issues
- Follow best practices for sudo password management in Ansible
With these skills, you can now confidently use Ansible for tasks that require elevated privileges, ensuring your automation runs smoothly and securely.


