Infrastructure and Automation with Ansible
local graph
Chapter 17 — Infrastructure and Automation with Ansible
Section titled “Chapter 17 — Infrastructure and Automation with Ansible”If your day-to-day system administration or development work involves tedious and repetitive operations, Ansible could help you run your tasks while saving you precious time. Ansible is a tool for automating software provisioning, configuration management, and application deployment workflows. Initially developed by Michael DeHaan in 2012, Ansible was acquired by Red Hat in 2015 and is now maintained as an open source project.
In this chapter, you’ll learn about the fundamental concepts of Ansible, along with a variety of hands-on examples. In particular, we’ll explore the following topics:
- Introducing Ansible architecture and configuration management
- Installing Ansible
- Working with Ansible
Technical requirements
Section titled “Technical requirements”First, you should be familiar with the Linux command-line Terminal in general. Intermediate knowledge of Linux will help you understand some of the intricacies of the practical illustrations used throughout this chapter. You should also be proficient in using a Linux-based text editor.
For the hands-on examples, we recommend setting up a lab environment similar to the one we’re using. To replicate this environment, your CPU will need to have at least 6 physical cores and 6 virtual cores (12 in total). A quad-core CPU with hyper-threading is not enough. Also, OpenSSH should be installed on all the hosts. You’ll find related instructions in the Setting up the lab environment section of this chapter. If you don’t configure a lab environment, you will still benefit from the detailed explanations associated with the practical examples in this chapter.
Now, let’s start our journey by covering introductory concepts surrounding Ansible.
Introducing Ansible architecture and configuration management
Section titled “Introducing Ansible architecture and configuration management”In the introduction to this chapter, we captured one of the essential aspects of Ansible – it’s a tool for automating workflows. Almost any Linux system administration task can be automated using Ansible. Using the Ansible CLI, we can invoke simple commands to change the desired state of a system. Usually, with Ansible, we execute tasks on a remote host or a group of hosts.
Let’s use the classic illustration of package management. Suppose you’re managing an infrastructure that includes a group of web servers, and you plan to install the latest version of a web server application (Nginx or Apache) on all of them. One way to accomplish this task is to SSH into each host and run the related shell commands to install the latest web server package. If you have a lot of machines, this will be a big task. You could argue that you can write a script to automate this job. This is possible, but then you’d have yet another job on your hands; that is, maintaining the script, fixing possible bugs, and, with your infrastructure growing, adding new features.
At some point, you may want to manage users or databases or configure network settings on multiple hosts. Soon, you’ll be looking at a Swiss Army knife tool, with capabilities that you’d rather get for free instead of writing them yourself. Here’s where Ansible comes in handy. With its myriad of modules – for almost any system administration task you can imagine – Ansible can remotely configure, run, or deploy your management jobs of choice, with minimal effort and in a very secure and efficient way.
We’ll consolidate these preliminary thoughts with a brief look at the Ansible architecture.
Understanding the Ansible architecture
Section titled “Understanding the Ansible architecture”The core Ansible framework is written in Python. Let’s mention upfront that Ansible has an agentless architecture. In other words, it runs on a control node that executes commands against remote hosts, without the need for a remote endpoint or service to be installed on the managed host to communicate with the control node. At a minimum, the only requirement for Ansible communication is SSH connectivity to the managed host. Yet, the number of Ansible operations would be relatively limited to only running scripts and raw SSH commands if the host didn’t have a Python framework installed. The vast majority of server OS platforms already have Python installed by default.
Ansible can manage a fleet of remote hosts from a single control node using secure SSH connections. The following diagram shows the logical layout of a managed infrastructure using Ansible:

Figure 17.1 – The logical layout of a managed infrastructure using Ansible
Production-grade enterprise environments usually include a configuration management database (CMDB) for organizing their IT infrastructure assets. Examples of IT infrastructure assets are servers, networks, services, and users. Although not directly part of the Ansible architecture, the CMDB describes the assets and their relationship within a managed infrastructure and can be leveraged to build an Ansible inventory.
The inventory is local storage on the Ansible control node – typically an INI or YAML file – that describes managed hosts or groups of hosts. The inventory is either inferred from the CMDB or manually created by the system administrator.
Now, let’s have a closer look at the high-level Ansible architecture shown in the following diagram:

Figure 17.2 – The Ansible architecture
The preceding diagram shows the Ansible control node interacting with managed hosts in a private or public cloud infrastructure. Here are some brief descriptions of the blocks featured in the architectural view:
- API and core framework: The main libraries encapsulating Ansible’s core functionality; the Ansible core framework is written in Python
- Plugins: Additional libraries extending the core framework’s functionality – for instance, the following:
- Connection plugins, such as cloud connectors
- Test plugins, verifying specific response data
- Callback plugins for responding to events
- Connection plugins, such as cloud connectors
- Modules: These encapsulate specific functions running on managed hosts, such as the following:
usermodule for managing userspackagemodule for managing software packages
- Inventory: The INI or YAML file describing the hosts and groups of hosts targeted by Ansible commands and playbooks
- Playbooks: The Ansible execution files describing a set of tasks that target managed hosts
- Private or public clouds: The managed infrastructure, hosted on-premises or in various cloud environments (for example, VMware, Amazon Web Services (AWS), and Azure)
- Managed hosts: The servers targeted by Ansible commands and playbooks
- CLI: The Ansible CLI tools, such as
ansible,ansible-playbook,ansible-doc, and so on - Users: The administrators, power users, and automated user processes running Ansible commands or playbooks
Now that we have a basic understanding of the Ansible architecture, let’s look at what makes Ansible a great tool for automating management workflows. We’ll introduce the concept of configuration management next.
Introducing configuration management
Section titled “Introducing configuration management”If we look back at the old days, system administrators usually managed a relatively low number of servers, running everyday administrative tasks by using a remote shell on each host. Relatively simple operations, such as copying files, updating software packages, and managing users, could easily be scripted and reused regularly. With the recent surge in apps and services, driven by the vast expansion of the internet, modern-day on-premises and cloud-based IT infrastructures – sustaining the related platforms – have grown significantly. The sheer amount of configuration changes involved would by far exceed the capacity of a single admin running and maintaining a handful of scripts. Here’s where configuration management comes to the rescue.
With configuration management, managed hosts and assets are grouped into logical categories, based on specific criteria, as suggested in Figure 17*.1*. Managing assets other than hosts ultimately comes down to performing specific tasks on the servers hosting those assets. The configuration management manifest is the Ansible inventory file that manages these hosts and assets. Thus, Ansible becomes the configuration management endpoint.
With Ansible, we can run single one-off commands to carry out specific tasks, but a far more efficient configuration management workflow can be achieved via playbooks. With Ansible playbooks, we can run multiple tasks that target various subsystems of a target platform against any number of hosts. Scheduling ansible-playbook runs for regular maintenance and configuration management tasks is a common practice in IT infrastructure automation. We will discuss Ansible playbooks later in this chapter.
Running Ansible tasks repeatedly (or on a scheduled basis) against a specific target raises the concern of unwanted changes in the desired state due to repetitive operations. This issue brings us to one of the essential aspects of configuration management – the idempotency of configuration changes. We’ll look at what idempotent changes are next.
Explaining idempotent operations
In configuration management, an operation is idempotent when running it multiple times yields the same result as running it once. In this sense, Ansible is an idempotent configuration management tool.
Let us explain how an idempotent operation works. Let us suppose we have an Ansible task creating a user. When the task runs for the first time, it creates the user. Running it for a second time – when the user has already been created – would result in a no-operation (no-op). Without idempotency, subsequent runs of the same task would produce errors due to attempting to create a user that already exists.
We should note that Ansible is not the only configuration management tool on the market. We have Chef, Puppet, and SaltStack, to name a few. Most of these platforms have been acquired by larger enterprises, such as SaltStack, being owned by VMware, and some may argue that Ansible’s success could be attributed to Red Hat’s open sourcing of the project. Ansible appears to be the most successful configuration management platform of our day. The industry consensus is that Ansible provides a user-friendly experience, high scalability, and affordable licensing tiers in enterprise-grade deployments.
With the introductory concepts covered, let’s roll up our sleeves and install Ansible on a Linux platform of choice.
Installing Ansible
Section titled “Installing Ansible”In this section, we’ll show you how to install Ansible on a control node. On Linux, we can install Ansible in a couple of ways:
- Using the platform-specific package manager (for example,
apton Ubuntu/Debian) - Using
pip, the Python package manager
The Ansible community recommends pip for installing Ansible since it provides the most recent stable version of Ansible. In this section, we’ll use Ubuntu as our distribution of choice. For a complete Ansible installation guide for all major OS platforms, please follow the online documentation at https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html.
On the control node, Ansible requires Python, so before installing Ansible, we need to make sure we have Python installed on our system.
Important note
Python 2 is no longer supported as of January 1, 2020. Please use Python 3.8 (or newer) instead.
Let’s start by installing Ansible on Ubuntu.
Installing Ansible on Ubuntu
Section titled “Installing Ansible on Ubuntu”With Ubuntu 22.04 LTS, we have Python 3 installed by default. We can proceed with installing Ansible by following these steps:
- Let’s first check the Python 3 version we have by using the following command:
On our Ubuntu 20.04 machine, the Python version is as follows:python3 --versionIf you don’t have Python 3 installed, you can install it with the following command:Python 3.10.12sudo apt install -y python3
- With Python 3 installed, we can proceed with installing Ansible. To get the most up-to-date Ansible packages using
apt, we need to add the Ansible Personal Package Archives (PPA) repository to our system. Let’s start by updating the currentaptrepository:sudo apt update - Next, we must add the
sudo apt install -y software-properties-commonsudo apt-add-repository --update ppa:ansible/ansible -y
- Now, we can install the Ansible package with the
sudo apt install ansible -y
- With Ansible installed, we can check its
In our case, the relevant excerpt in the output of the previous command is as follows:ansible --versionansible [core 2.15.4]
Next, we’ll look at how to install Ansible using pip.
Installing Ansible using pip
Section titled “Installing Ansible using pip”Before we install Ansible with pip, we need to make sure Python is installed on the system. We assume Python 3 is installed based on the steps presented in the previous section. When installing Ansible using pip, it is a safe practice to previously uninstall any version of Ansible that was installed using the local package manager (such as apt). This will ensure that pip will install the latest version of Ansible successfully. To proceed with the installation, follow these steps:
- We should remove any existing version of Ansible that’s been installed with the platform-specific package manager (for example,
aptoryum). To uninstall Ansible on Ubuntu, run thesudo apt remove -y ansible - Next, we must make sure
pipis installed. The following command should provide the current version ofpip:Ifpython3 -m pip --versionpipis not installed, the following output will show:We must then download the/usr/bin/python3: No module named pippipinstaller first:curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py - We’re now ready to install
pipand Ansible with thePlease note that, with the previous commands, we only installedpython3 get-pip.py --userpython3 -m pip install --user ansiblepipand Ansible for the current user (hence the--useroption we used). - If you wish to install Ansible globally on the system, the equivalent commands are
sudo python3 get-pip.pysudo python3 -m pip install ansible
- After the installation completes, you may have to log out and log back in to your Terminal again before using Ansible. You can check the Ansible version you have installed with the
In our case, the output shows the following:ansible --versionansible [core 2.15.4]
As you can see, you can get the most recent version (as of writing) of Ansible by using pip. Therefore, it is the recommended method of installing Ansible.
With Ansible installed on our control node, let’s look at some practical examples of using Ansible.
Working with Ansible
Section titled “Working with Ansible”In this section, we’ll use the Ansible CLI tools extensively to perform various configuration management tasks. To showcase our practical examples, we’ll work with a custom lab environment, and we highly encourage you to reproduce it for a complete configuration management experience.
Here’s a high-level outline of this section:
- Setting up the lab environment
- Configuring Ansible
- Using Ansible ad hoc commands
- Using Ansible playbooks
- Using templates with Jinja2
- Using Ansible roles
Let’s start with an overview of the lab environment.
Setting up the lab environment
Section titled “Setting up the lab environment”Our lab uses Kernel-based Virtual Machine (KVM) as a hypervisor for the virtual environment, but any other hypervisor will do. Chapter 11, Working with Virtual Machines, describes the process of creating Linux virtual machines (VMs) in detail. We deployed the following VMs using Ubuntu Server LTS to mimic a real-world configuration management infrastructure:
neptune: The Ansible control nodeans-web1: Web serverans-web2: Web serverans-db1: Database serverans-db2: Database server
All VMs have the default server components installed. On each host, we created a default admin user called packt with SSH access enabled. Each VM will have 2 vCPUs, 2 GB of RAM, and 20 GB minimum.
Now, let’s briefly describe the setup for these VMs, starting with managed hosts.
Setting up managed hosts
Section titled “Setting up managed hosts”There are a couple of key requirements for managed hosts to fully enable configuration management access from the Ansible control node:
- They must have an OpenSSH server installed and running
- They must have Python installed
As specified in the Technical requirements section, we assume you have OpenSSH enabled on your hosts. For installing Python, you may follow the related steps described in the Installing Ansible section.
Important note
Managed hosts don’t require Ansible to be installed on the system.
To set the hostname on each VM, you may run the following command (for example, for the ans-web1 hostname):
sudo hostnamectl set-hostname ans-web1We also want to disable the sudo login password on our managed hosts to facilitate unattended privilege escalation when running automated scripts. If we don’t make this change, remotely executing Ansible commands will require a password.
To disable the sudo login password, edit the sudo configuration with the following command:
sudo visudoAdd the following line and save the configuration file. Replace packt with your username if it’s different:
packt ALL=(ALL) NOPASSWD:ALLYou’ll have to make this change on all managed hosts.
Next, we’ll look at the initial setup for the Ansible control node.
Setting up the Ansible control node
Section titled “Setting up the Ansible control node”The Ansible control node (neptune) interacts with managed hosts (ans-web1, ans-web2, ans-db1, and ans-db2) using Ansible commands and playbooks. For convenience, our examples will reference the managed hosts by their hostnames instead of their IP addresses. To easily accomplish this, we added the following entries to the /etc/hosts file on the Ansible control node (neptune):
127.0.0.1 neptune localhost192.168.122.70 ans-web1192.168.122.147 ans-web2192.168.122.254 ans-db1192.168.122.25 ans-db2You’ll have to match the hostnames and IP addresses according to your VM environment.
Next, we must install Ansible on our managed hosts too. Use the related procedure described in the Installing Ansible section earlier in this chapter, when we showed you how to install Ansible on the control node. In our case, we followed the steps in the Installing Ansible using pip section to benefit from the latest Ansible release at the time of writing.
Finally, we’ll set up SSH key-based authentication between the Ansible control node and the managed hosts.
Setting up SSH key-based authentication
Section titled “Setting up SSH key-based authentication”Ansible uses SSH communication with managed hosts. The SSH key authentication mechanism enables remote SSH access without the need to enter user passwords. To enable SSH key-based authentication, run the following commands on the Ansible control host (neptune).
Use the following command to generate a secure key pair and follow the default prompts:
ssh-keygenWith the key pair generated, copy the related public key to each managed host. You’ll have to target one host at a time and authenticate with the remote packt user’s password. Accept the SSH key exchange when prompted:
ssh-copy-id -i ~/.ssh/id_rsa.pub packt@ans-web1ssh-copy-id -i ~/.ssh/id_rsa.pub packt@ans-web2ssh-copy-id -i ~/.ssh/id_rsa.pub packt@ans-db1ssh-copy-id -i ~/.ssh/id_rsa.pub packt@ans-db2Now, you should be able to SSH into any of the managed hosts from the Ansible control node (neptune) without being prompted for a password. For example, to access ans-web1, you can test it with the following command:
ssh packt@ans-web1The command will take you to the remote server’s (ans-web1) Terminal. Make sure you go back to the Ansible control node’s Terminal (on neptune) before following the next steps.
We’re now ready to configure Ansible on the control node.
Configuring Ansible
Section titled “Configuring Ansible”This section explores some of the basic configuration concepts of Ansible that are related to the Ansible configuration file and inventory. Using a configuration file and the parameters within, we can change the behavior of Ansible, such as privilege escalation, connection timeout, and default inventory file path. The inventory defines managed hosts, acting as the CMDB of Ansible.
Let’s look at the Ansible configuration file first.
Creating an Ansible configuration file
Section titled “Creating an Ansible configuration file”The following command provides some helpful information about our Ansible environment, including the current configuration file:
ansible --versionHere’s the complete output of the preceding command:

Figure 17.3 – The default Ansible configuration settings
A default Ansible installation will set the configuration file path to /etc/ansible/ansible.cfg. As you can probably guess, the default configuration file has a global scope, which means that it’s used by default when we run Ansible tasks.
Now, let’s look at some different scenarios and how they can be addressed:
- What if there are multiple users on the same control host running Ansible tasks? Our instinct suggests that each user may have their own set of configuration parameters. Ansible resolves this problem by looking into the user’s home directory for the
~/.ansible.cfgfile. Let’s verify this behavior by creating a dummy configuration file in our user’s (packt)A new invocation of thetouch ~/.ansible.cfgansible --versioncommand now yields the followingconfigfilepath:
Figure 17.4 – Changing the default configuration file
In other words, ~/.ansible.cfg takes precedence over the global /etc/ansible/ansible.cfg configuration file.
- Now, suppose our user (
packt) creates multiple Ansible projects, some managing on-premises hosts and others interacting with public cloud resources. Again, we may need a different set of Ansible configuration parameters (such as a connection timeout and inventory file). Ansible accommodates this scenario by looking for the./ansible.cfgfile in the current folder. Let’s create a dummyansible.cfgfile in a new~/ansible/directory:Switching to themkdir ~/ansibletouch ~/ansible/ansible.cfg~/ansibledirectory and invoking theansible --versioncommand shows the following config file:
Figure 17.5 – Changing the current directory and configuration file
We could have named our project directory anything, not necessarily /home/packt/ansible. Ansible prioritizes the ./ansible.cfg file over the ~/.ansible.cfg configuration file in the user’s home directory.
- Finally, we may want the ultimate flexibility of a configuration file that doesn’t depend on the directory or location originating from our Ansible commands. Such a feature could be helpful while testing ad hoc configurations without altering the main configuration file. For this purpose, Ansible reads the
ANSIBLE_CONFIGenvironment variable for the path of the configuration file. Assuming we are in the~/ansibleproject folder, where we already have our localansible.cfgfile defined, let’s create a dummy test configuration file namedtest.cfg:Now, let’s verify that Ansible will read the configuration fromcd ~/ansibletouch test.cfgtest.cfginstead ofansible.cfgwhen theANSIBLE_CONFIGenvironment variable is set:The output shows the following:ANSIBLE_CONFIG=test.cfg ansible --version
Figure 17.6 – Verifying reading of the new configuration file
We should note that the configuration file should always have the .cfg extension. Otherwise, Ansible will discard it.
Here’s a list summarizing the order of precedence in descending order for Ansible configuration files:
- The
ANSIBLE_CONFIGenvironment variable - The
./ansible.cfgfile in the local directory - The
~/.ansible.cfgfile in the user’s home directory /etc/ansible/ansible.cfg
In our examples, we’ll rely on the ansible.cfg configuration file in a local project directory (~/ansible). Let’s create this configuration file and leave it empty for now:
mkdir ~/ansiblecd ~/ansibletouch ansible.cfgFor the rest of this chapter, we’ll run our Ansible commands from the ~/ansible folder unless we specify otherwise.
Unless we specifically define (override) configuration parameters in our configuration file, Ansible will assume the system defaults. One of the attributes that we’ll add to the config file is the inventory file path. But first, we’ll need to create an inventory. The following section will show you how.
Creating an Ansible inventory
Section titled “Creating an Ansible inventory”An Ansible inventory is a regular INI or YAML file describing the managed hosts. In its simplest form, the inventory could be a flat list of hostnames or IP addresses, but Ansible can also organize the hosts into groups. Ansible inventory files are either static or dynamic, depending on whether they are created and updated manually or dynamically. For now, we’ll use a static inventory.
In our demo environment with two web servers (ans-web1, ans-web2) and two database servers (ans-db1, ans-db2), we can define the following inventory (in INI format) in a file named hosts (located inside ~/ansible) that we will create later on, as shown in Figure 17*.7*:
[webservers]ans-web1ans-web2[databases]ans-db1ans-db2We classified our hosts into a couple of groups, featured in bracketed names; that is, [webservers] and [databases]. As discussed earlier, groups are logical arrangements of hosts based on specific criteria. Hosts can be part of multiple groups. Group names are case-sensitive, should always start with a letter, and should not contain hyphens (-) or spaces.
Ansible has two default groups:
all: Every host in the inventoryungrouped: Every host inallthat is not a member of another group
We can also define groups based on specific patterns. For example, the following group includes a range of hostnames starting with ans-web and ending with a number in the range of 1 - 2:
[webservers]ans-web[1:2]Patterns are helpful when we’re managing a large number of hosts. For example, the following pattern includes all the hosts within a range of IP addresses:
[all_servers]172.16.191.[11:15]Ranges are defined as [START:END] and include all values from START to END. Examples of ranges are [1:10], [01:10], and [a-g].
Groups can also be nested. In other words, a group may contain other groups. This nesting is described with the :children suffix. For example, we can define a [platforms] group that includes the [ubuntu] and [debian] groups (all our VMs are running on Ubuntu, so this is only for explaining purposes):
[platforms:children]ubuntudebianLet’s name our inventory file hosts. Please note that we are in the ~/ansible directory. Using a Linux editor of your choice, add the following content to the hosts file:

Figure 17.7 – The inventory file in INI format
After saving the inventory file, we can validate it with the following command:
ansible-inventory -i ./hosts –-list --yamlHere’s a brief explanation of the command’s parameters:
-i (--inventory): Specifies the inventory file; that is,./hosts--list: Lists the current inventory, as read by Ansible--yaml: Specifies the output format as YAML
Upon successfully validating the inventory, the command will show the equivalent YAML output (the default output format of the ansible-inventory utility is JSON).
So far, we’ve expressed the Ansible inventory in INI format, but we may as well use a YAML file instead. The following screenshot shows the output of the preceding command in YAML format:

Figure 17.8 – The output in YAML inventory format
The YAML representation could be somewhat challenging, especially with large configurations, due to the strict indentation and formatting requirements. We’ll continue to use the INI inventory format throughout the rest of this chapter.
Next, we’ll point Ansible to our inventory. Edit the ./ansible.cfg configuration file and add the following lines:

Figure 17.9 – Pointing to our inventory file
After saving the file, we’re ready to run Ansible commands or tasks that target our managed hosts. There are two ways we can perform Ansible configuration management tasks: using one-off ad hoc commands and via Ansible playbooks. We’ll look at ad hoc commands next.
Using Ansible ad hoc commands
Section titled “Using Ansible ad hoc commands”Ad hoc commands execute a single Ansible task and provide a quick way to interact with our managed hosts. These simple operations are helpful when we’re making simple changes and performing testing.
The general syntax of an Ansible ad hoc command is as follows:
ansible [OPTIONS] -m MODULE -a ARGS PATTERNThe preceding command uses an Ansible MODULE to perform a particular task on select hosts based on a PATTERN. The task is described via arguments (ARGS). You may recall that modules encapsulate a specific functionality, such as managing users, packages, and services. To demonstrate the use of ad hoc commands, we’ll use some of the most common Ansible modules for our configuration management tasks. Let’s start with the Ansible ping module.
Working with the ping module
Section titled “Working with the ping module”One of the simplest ad hoc commands is the Ansible ping test:
ansible -m ping allThe command performs a quick test on all managed hosts to check their SSH connectivity and ensure the required Python modules are present. Here’s an excerpt from the output:

Figure 17.10 – A successful ping test with a managed host
The output suggests that the command was successful (| SUCCESS) and that the remote servers responded with "pong" to our ping request ("ping": "pong"). Please note that the Ansible ping module doesn’t use Internet Control Message Protocol (ICMP) to test the remote connection with managed hosts. The ping module inside Ansible is just a test module that requires Python; it does not rely on the ping command we use when troubleshooting network issues.
Next, we’ll look at ad hoc commands while using the Ansible user module.
Working with the user module
Section titled “Working with the user module”Here’s another example of an ad hoc command. This one is checking if a particular user (packt) exists on all the hosts:
ansible -m user -a "name=packt state=present" allThe following is an excerpt of the output yielded by a successful check:

Figure 17.11 – Checking if a user account exists
The preceding output also suggests that we could be even more specific when checking for a user account by also making sure they have a particular user and group ID:
ansible -m user -a "name=packt state=present uid=1000 group=1000" allWe can target ad hoc commands against a limited subset of our inventory. The following command, for example, would only ping the web1 host for Ansible connectivity:
ansible -m ping ans-web1Host patterns can also include wildcards or group names. Here are a few examples:
ansible -m ping ans-web*ansible -m ping webserversLet’s look at the available Ansible modules next. Before we do that, you may want to add the following line to ./ansible.cfg, under the [defaults] section, to keep the noise down about deprecated modules:
deprecation_warnings = FalseTo list all the modules available in Ansible, run the following command:
ansible-doc --listYou may search or grep the output for a particular module. For detailed information about a specific module (for example, user), you can run the following command:
ansible-doc userMake sure you check out the EXAMPLES section in the ansible-doc output for a specific module. You will find hands-on examples of using the module with ad hoc commands and playbook tasks.
Furthermore, we can create new users for different use cases on our Ansible hosts. Next, we will show you how to create a new user.
Creating a new user
Section titled “Creating a new user”If we want to create a new user (webuser) on all our web servers, we can perform the related operation with the following ad hoc command:
ansible -bK -m user -a "name=webuser state=present" webserversLet’s explain the command’s parameters:
-b(--become): Changes the execution context tosudo(root)-K(--ask-become-pass): Prompts for thesudopassword on the remote hosts; the same password is used on all managed hosts-m: Specifies the Ansible module (user-a: Specifies theusermodule arguments as key-value pairs;name=webuserrepresents the username, whilestate=presentchecks whether the user account exists before attempting to create itwebservers: The group of managed hosts targeted by the operation
Creating a user account requires administrative (sudo) privileges on the remote hosts. Using the -b (--become) option invokes the related privilege escalation for the Ansible command to act as a sudoer on the remote system.
Important note
By default, Ansible does not enable unattended privilege escalation. For tasks requiring sudo privileges, you must explicitly set the -b (--become) flag. You can override this behavior in the Ansible configuration file.
To enable unattended privilege escalation by default, add the following lines to the ansible.cfg file:

Figure 17.12 – Adding privilege escalation rules
Now, you don’t have to specify the --b (--become) flag anymore with your ad hoc commands.
If the sudoer account on the managed hosts has the sudo login password enabled, we’ll have to provide it to our ad hoc command. Here is where the -K (--ask-become-pass) option comes in handy. Consequently, we’re asked for a password with the following message:
BECOME password:This password is used across all managed hosts targeted by the command.
As you may recall, we disabled the sudo login password on our managed hosts (see the Setting up the lab environment section earlier in this chapter). Therefore, we can rewrite the previous ad hoc command without explicitly asking for privilege escalation and the related password:
ansible -m user -a "name=webuser state=present" webserversThere are some security concerns regarding privilege escalation, and Ansible has the mechanisms to mitigate the related risks. For more information on this topic, you may refer to https://docs.ansible.com/ansible/latest/user_guide/become.html.
The preceding command produces the following output:

Figure 17.13 – Creating a new user using an ad hoc command
You may have noticed that the output text here is highlighted, as it was with our previous ad hoc commands. Ansible highlights the output if it corresponds to a change in the desired state of the managed host. If you run the same command a second time, the output will not be highlighted, suggesting that there’s been no change since the user account has been already created. Here, we can see Ansible’s idempotent operation at work.
With the previous command, we created a user without a password for demo purposes only. What if we want to add or modify the password? Next, we will show you how to do that.
Adding or modifying a password
Section titled “Adding or modifying a password”Glossing through the user module’s documentation with ansible-doc user, we can use the password field inside the module arguments, but Ansible will only accept password hashes as input. For hashing passwords, we’ll use a helper Python module called passlib. Let’s install it on the Ansible control node with the following command:
pip install passlibYou’ll need the Python package manager (pip) to run the previous command. If you installed Ansible using pip, you should be fine. Otherwise, follow the instructions in the Installing Ansible using pip section to download and install pip.
With passlib installed, we can use the following ad hoc command to create or modify the user password:
ansible webservers -m user \ -e "password=changeit!" \ -a "name=webuser \ update_password=always \ password={{ password | password_hash('sha512') }}"Here are the additional parameters helping with the user password:
-e(--extra-vars): Specifies custom variables as key-value pairs; we set the value of a custom variable topassword=changeit!update_password=always: Updates the password if it’s different from the previous onepassword={{...}}: Sets the password to the value of the expression enclosed within double bracespassword | password_hash('sha512'): Pipes the value of thepasswordvariable (changeit!) to thepassword_hash()function, thus generating an SHA-512 hash;password_hash()is part of thepasslibmodule we installed earlier
The command sets the password of webuser to changeit!, and is an example of using variables (password) in ad hoc commands. Here’s the related output:

Figure 17.14 – Changing the user’s password using an ad hoc command
Ansible won’t show the actual password for obvious security reasons.
Now, you can try to SSH into any of the web servers (web1 or web2) using the webuser account, and you should be able to authenticate successfully with the changeit! password.
Deleting a user
Section titled “Deleting a user”To delete the webuser account on all web servers, we can run the following ad hoc command:
ansible -m user -a "name=webuser state=absent remove=yes force=yes" webserversThe state=absent module parameter invokes the deletion of the webuser account. The remove and force parameters are equivalent to the userdel -rf command, deleting the user’s home directory and any files within, even if they’re not owned by the user.
The related output is as follows:

Figure 17.15 – Deleting a user account using an ad hoc command
You may safely ignore stderr and stderr_lines, which were captured in the output. The message is benign since the user didn’t create a mail spool previously.
We’ll look at the package module next and run a few related ad hoc commands.
Working with the package module
Section titled “Working with the package module”The following command installs the Nginx web server on all hosts within the webserver group:
ansible -m package -a "name=nginx state=present" webserversHere’s an excerpt from the output:

Figure 17.16 – Installing the nginx package on the web servers
We use a similar ad hoc command to install the MySQL database server on all hosts within the databases group:
ansible -m package -a "name=mysql-server state=present" databasesHere’s an excerpt from the command’s output:

Figure 17.17 – Installing the mysql-server package on the database servers
If we wanted to remove a package, the ad hoc command would be similar but would feature state=absent instead.
Although the package module provides a good OS-level abstraction across various platforms, certain package management tasks are best handled with platform-specific package managers. We’ll show you how to use the apt module next.
Working with platform-specific package managers
Section titled “Working with platform-specific package managers”The following ad hoc command installs the latest updates on all Ubuntu machines in our managed environment. As all of our VMs are running Ubuntu, we will choose to run the commands only on the webservers group. The command will be the following:
ansible -m apt -a "upgrade=dist update_cache=yes" ubuntuIf we wanted, we could create one more group inside the hosts file, named [ubuntu] for example, and add all the VMs in there. This would be easier if we had different operating systems running, but that is not the case for us.
Thee platform-specific package management modules (apt, yum, and so on) match all the capabilities of the system-agnostic package module, featuring additional OS-exclusive functionality.
Let’s look at the service module next and a couple of related ad hoc commands.
Working with the service module
Section titled “Working with the service module”The following command restarts the nginx service on all hosts in the webservers group:
ansible -m service -a "name=nginx state=restarted" webserversHere’s a relevant excerpt from the output:

Figure 17.18 – Restarting the nginx service on the web servers
In the same way, we can restart the mysql service on all database servers, but there’s a trick to it! On Ubuntu, the MySQL service is named mysql. We could, of course, target each host with the appropriate service name, but if you had many database servers, it would be a laborious task. Alternatively, we can use the exclusion pattern (written as !) when targeting multiple hosts or groups.
The following command will restart the mysql service on all hosts in the databases group, except those that are members of the debian group (if we were to have a debian group):
ansible -m service -a "name=mysql state=restarted" 'databases:!debian'Similarly, we can restart the mysqld service on all hosts in the databases group, except for those that are members of the ubuntu group (if we were to have one), with the following ad hoc command:
ansible -m service -a "name=mysqld state=restarted" 'databases:!ubuntu'Always use single quotes ('') when you’re targeting multiple hosts or groups with an exclusion pattern; otherwise, the ansible command will fail.
Let’s look at one last Ansible module and the related ad hoc command, which is frequently used in upgrade scenarios.
Working with the reboot module
Section titled “Working with the reboot module”The following ad hoc command reboots all hosts in the webservers group:
ansible -m reboot -a "reboot_timeout=3600" webserversSlower hosts may take longer to reboot, especially during substantial upgrades, hence the increased reboot timeout of 3600 seconds. (The default timeout is 600 seconds.)
In our case, the reboot only took a few seconds. The output is as follows:

Figure 17.19 – Rebooting the webservers group
In this section, we showed a few examples of ad hoc commands using different modules. The next section will give you a brief overview of some of the most common Ansible modules and how to explore more.
Exploring Ansible modules
Section titled “Exploring Ansible modules”Ansible has a vast library of modules. As we noted previously, you may use the ansible-doc --list command to browse the available Ansible modules on the command-line Terminal. You can also access the same information online, on the Ansible modules index page, at https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html.
The online catalog provides module-by-category indexing to help you quickly locate a particular module you’re looking for. Here are some of the most typical modules used in everyday system administration and configuration management tasks with Ansible:
- Packaging modules:
apt: Performs APT package managementyum: Performs YUM package managementdnf: Performs DNF package management
- System modules:
users: Manages usersservices: Controls servicesreboot: Restarts machinesfirewalld: Performs firewall management
- File modules:
copy: Copies local files to the managed hostssynchronize: Synchronizes files and directories usingrsyncfile: Controls file permissions and attributeslineinfile: Manipulates lines in text files
- Net Tools modules:
nmcli: Controls network settingsget_url: Downloads files over HTTP, HTTPS, and FTPuri: Interacts with web services and API endpoints
- Commands modules (not idempotent):
raw: Simply runs a remote command via SSH (which is an unsafe practice); doesn’t need Python installed on the remote hostcommand: Runs commands securely using Python’s remote execution contextshell: Executes shell commands on managed hosts
We should note that ad hoc commands always execute a single operation using a single module. This feature is an advantage (for quick changes) but also a limitation. For more complex configuration management tasks, we use Ansible playbooks. The following section will take you through the process of authoring and running Ansible playbooks.
Using Ansible playbooks
Section titled “Using Ansible playbooks”An Ansible playbook is essentially a list of tasks that are executed automatically. Ansible configuration management workflows are primarily driven by playbooks. More precisely, a playbook is a YAML file containing one or more plays, each with a list of tasks executed in the order they are listed. Plays are execution units that run the associated tasks against a set of hosts, and they are selected via a group identifier or a pattern. Each task uses a single module that executes a specific action targeted at the remote host. You may think of a task as a simple Ansible ad hoc command. As the majority of Ansible modules comply with idempotent execution contexts, playbooks are also idempotent. Running a playbook multiple times always yields the same result.
Well-written playbooks can replace laborious administrative tasks and complex scripts with relatively simple and maintainable manifests, running easily repeatable and predictable routines.
We’ll create our first Ansible playbook next.
Creating a simple playbook
Section titled “Creating a simple playbook”We’ll build our playbook based on the ad hoc command we used for creating a user (webuser). As a quick refresher, the command was as follows:
ansible -m user -a "name=webuser state=present" webserversAs we write the equivalent playbook, you may notice some resemblance to the ad hoc command parameters.
While editing the playbook YAML file, please be aware of the YAML formatting rules:
- Use only space characters for indentation (no tabs)
- Keep the indentation length consistent (for example, two spaces)
- Items at the same level in the hierarchy (for example, list items) must have the same indentation
- A child item’s indentation is one indentation more than its parent
Now, using a Linux editor of your choice, add the following lines to a create-user.yml file. Make sure you create the playbook in the ~/ansible project directory, which is where we have our current inventory (hosts) and Ansible configuration file (ansible.cfg):

Figure 17.20 – A simple playbook for creating a user
Let’s look at each line in our create-user.yml playbook:
---: Marks the beginning of the playbook file- name: Describes the name of the play; we can have one or more plays in a playbookhosts: webservers: Targets the hosts in thewebserversgroupbecome: yes: Enables privilege escalation for the current task; you can leave this line out if you enabled unattended privilege escalation in your Ansible configuration file (withbecome = Truein the[``privileged_escalation]section)tasks: The list of tasks in the current play- name: The name of the current task; we can have multiple tasks in a playuser: The module being used by the current taskname: webuser: The name of the user account to createstate: present: The desired state upon creating the user – we want the user account to be present on the system
Let’s run our create-user.yml playbook:
ansible-playbook create-user.ymlHere’s the output we get after a successful playbook run:

Figure 17.21 – Running the create-user.yml playbook
Most of the ansible-playbook command-line options are similar to the ones for the ansible command. Let’s look at some of these parameters:
-i(--inventory): Specifies an inventory file path-b(--become): Enables privilege escalation tosudo(root)-C(--check): Produces a dry run without making any changes and anticipating the end results – a useful option for validating playbooks-l(--limit): Limits the action of the command or playbook to a subset of managed hosts--syntax-check: Validates the playbook’s syntax without making any changes; this option is only available for theansible-playbookcommand
Let’s experiment with a second playbook, this time for deleting a user. We’ll name the playbook delete-user.yml and add the following content:

Figure 17.22 – A simple playbook for deleting a user
Now, let’s run this playbook:
ansible-playbook delete-user.ymlThe output of the preceding command is as follows:

Figure 17.23 – Limiting the delete-user.yml playbook to the Ubuntu host group
Next, we’ll look at ways to further streamline our configuration management workflows, starting with the use of variables in playbooks.
Using variables in playbooks
Section titled “Using variables in playbooks”Ansible provides a flexible and versatile model for working with variables in both playbooks and ad hoc commands. Through variables, we are essentially parameterizing a playbook, making it reusable or dynamic.
Take our previous playbook, for example, to create a user. We hardcoded the username (webuser) in the playbook. We can’t really reuse the playbook to create another user (for example, webadmin) unless we add the related task to it. But then, if we had many users, our playbook would grow proportionally, making it harder to maintain. And what if we wanted to specify a password for each user as well? The complexity of the playbook would grow even more.
Here’s where variables come into play. Let’s first look at what variables are and how they are written.
Introducing variables
Section titled “Introducing variables”We can substitute the hardcoded values with variables, making the playbook dynamic. In terms of pseudocode, our example of using a playbook to create a user with specific username and password variables would look like this:
User = Playbook(username, password)Variables in Ansible are enclosed in double braces; for example, {{ username }}. Let’s see how we can leverage variables in our playbooks. Edit the create-user.yml playbook we worked on in the previous section and adjust it as follows:

Figure 17.24 – Using the “username” variable in a playbook
We use the {{ username }} variable substituting our previously hardcoded value (webuser). Then, we surrounded the double braces with quotes to avoid syntax interference with the YAML dictionary notation. Variable names in Ansible must begin with a letter and only contain alphanumerical characters and underscores.
Setting values for variables
Section titled “Setting values for variables”Next, we’ll explain how and where to set values for variables. Ansible implements a hierarchical model for assigning values to variables:
- Global variables: Values are set for all the hosts, either via the
–extra-vars ansible-playbookcommand-line parameter or the./group_vars/allfile. - Group variables: Values are set for the hosts in a specific group, either in the inventory file or the local
./group_varsdirectory in files named after each group. - Host variables: Values are set for a particular host, either in the inventory file or the local
./host_varsdirectory in files named after each host. Host-specific variables are also available from Ansible facts via thegather_factsdirective. You can learn more about Ansible facts at https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#ansible-facts. - Play variables: Values are set in the context of the current play for the hosts targeted by the play; examples are the
varsdirective in a play orinclude_varstasks.
In the preceding numbered list, the order of precedence for a variable’s value increases with each number. In other words, a variable value defined in a play will overwrite the same variable value specified at the host, group, or global level.
As an example, you may recall the peculiarity related to the MySQL service name on Ubuntu and RHEL/Fedora platforms. On Ubuntu, the service is mysql, while on Fedora, the service is mysqld. Suppose we want to restart the MySQL service on all hosts in our databases group. Assuming most of our database servers run Ubuntu, we can define a group-level service variable as service: mysql. We set this variable in the local project’s ./group_vars/databases file. Then, in the play where we control the service status, we can override the service variable value with mysqld when the remote host’s OS platform is Fedora.
Let’s look at a few examples to illustrate what we’ve learned so far about placing variables and setting their values. Back in our create-user.yml playbook, we can define the username variable at the play level with the following directive:
vars: username: webuserHere’s what it looks like in the overall playbook:

Figure 17.25 – Defining a variable at the play level
Let’s run our playbook with the following command:
ansible-playbook create-user.ymlA relevant excerpt from the output is shown in the next screenshot:

Figure 17.26 – Creating a user with a playbook using variables
Deleting user accounts
Section titled “Deleting user accounts”To delete user accounts, we can readjust our previous delete-user.yml file so that it looks as follows:

Figure 17.27 – Deleting a user with a playbook using variables
After saving the file, run the following command to delete the webuser account on all web servers:
ansible-playbook delete-user.ymlThe relevant output from the preceding command run is as follows:

Figure 17.28 – Deleting a user with a playbook using variables
Enhancing our playbooks
Section titled “Enhancing our playbooks”We can improve our create-user and delete-user playbooks even further. You can follow these steps:
- Since the play exclusively targets the
webserversgroup, we can define ausernamevariable in the./group_vars/webserversfile instead. This way, we can keep the playbooks more compact. Let’s remove the variable definition from both files. - Next, create a
./group_varsfolder in the local directory (~/ansible) and add the following lines to a file namedwebservers.yml:We could also just call the fileusername: webuserwebserversso that it matches the group we’re targeting. However, we should prefer to use the.ymlextension so that we’re consistent with the file’s YAML format. Ansible accepts both naming conventions. Here’s the current tree structure of our project directory:
Figure 17.29 – The directory tree, including the group_vars folder
If we run our playbooks, the results should be identical to our previous runs:
ansible-playbook create-user.ymlansible-playbook delete-user.yml- Now, let’s add one more variable to our
create-userplaybook: the user’spasswordvariable. You may recall the ad hoc command we created for the same purpose. See the Using Ansible ad hoc commands section earlier in this chapter for more information. Add the following lines to thecreate-user.ymlfile of theusertask, at the same level asname:You may notice how these changes are similar to the related ad hoc command. The updated playbook contains the following content:password: "{{ password | password_hash('sha512') }}"update_password: always
Figure 17.30 – The playbook with username and password variables
- Next, edit the
./group_vars/webservers.ymlfile and add thepasswordvariable with thechangeit!value. Your updated file should have the following content:
Figure 17.31 – Adding the new variable value inside the webservers.yml file
- Let’s run
The command’s output is identical to our similar previous commands.ansible-playbook create-user.yml
- You may test the new username (
webuser) and password (changeit!) by trying to SSH into one of the web servers (for example,ans-web1):The SSH authentication should succeed. Make sure to exit the remote Terminal before proceeding with the next steps.ssh webuser@ans-web1 - Let’s remove the
webuseraccount on the web servers with the following command, to get back to ouransible-playbook delete-user.yml - Suppose we want to reuse the
create-userplaybook to create a different user with a different password. Let’s name this userwebadmin; we’ll set the password tochangeme!. One way to accomplish this task is to use the-e(--extra-vars) option parameter withansible-playbook:The preceding command will create a new user (ansible-playbook -e '{"username": "webadmin", "password": "changeme!"}' create-user.ymlwebadmin) with the related password. You can test the credentials with the following command:The SSH authentication should succeed. Make sure you exit the remote Terminal before continuing. As you can see, thessh webadmin@ans-web1-e(--extra-vars) option parameter takes a JSON string featuring theusernameandpasswordfields, along with the corresponding values. These values will override the values of the same variables defined at the group level in the./group_vars/webservers.ymlfile. - Let’s remove the
webuserandwebadminaccounts before we proceed with the next steps. Let’s run thedelete-userplaybook, first without any parameters:The preceding command removes theansible-playbook delete-user.ymlwebuseraccount. - Next, we’ll use the
-e(--extra-vars) option parameter to delete thewebadminansible-playbook -e '{"username": "webadmin"}' delete-user.yml
Using –extra-vars with our create-user and delete-user playbooks, we can act on multiple user accounts by running the playbooks manually or in a loop and feeding the JSON blob with the required variables. While this method could easily be scripted, Ansible provides even more ways to improve our playbooks by using task iteration with loops. We’ll look at loops later in this chapter, but first, let’s handle our passwords more securely with Ansible’s encryption and decryption facilities for managing secrets.
Working with secrets
Section titled “Working with secrets”Ansible has a dedicated module for managing secrets called Ansible Vault. With Ansible Vault, we can encrypt and store sensitive data such as variables and files that are referenced in playbooks. Ansible Vault is essentially a password-protected secure key-value data store.
To manage our secrets, we can use the ansible-vault command-line utility. Regarding our playbook, where we’re creating a user with a password, we want to avoid storing the password in clear text. It is currently in the ./group_vars/webservers.yml file. As a reminder, our webservers.yml file has the following content:

Figure 17.32 – Sensitive data stored in the password variable
The last line contains sensitive data; the password is shown in plain text. We have a few options here to protect our data:
- Encrypt the
webservers.ymlfile. If we choose to encrypt thewebservers.ymlfile, we could possibly incur the overhead of encrypting non-sensitive data, such as the username or other general-purpose information. If we have many users, encrypting and decrypting non-sensitive data would be highly redundant. - Encrypt the
passwordvariable only. This would work fine for a single user. But with a growing number of users, we’ll have multiple password variables to deal with, each with its own encryption and decryption. Performance will once again be an issue if we have a large number of users. - Store the password in a separate protected file. Ideally, we should have a separate file for storing all sensitive data. This file would be decrypted only once during the playbook run, even with multiple passwords stored.
We will pursue the third option and create a separate file to keep our user passwords in.
Protecting our data
Section titled “Protecting our data”Let’s look at the steps that need to be followed to ensure that our data is secure:
- We’ll name the file
passwords.yml(we create it inside the~/ansible/directory) and add the following content to it:
Figure 17.33 – The passwords.yml file storing sensitive data
- We added a YAML dictionary (or hash) item matching the
webuserusername related to the password. This item contains another dictionary as a key-value pair:password: changeit!. The equivalent YAML representation is as follows:This approach will allow us to add passwords that correspond to different users, like so:webuser: { password: changeit! }We’ll explain the concept behind this data structure and its use when we consume thewebuser: { password: changeit! }webadmin: { password: changeme! }passwordvariable in the playbook, later in this section. - Now, since we keep our password in a different file, we’ll remove the corresponding entry from
webusers.yml. Let’s add some other user-related information using thecommentvariable. Here’s what ourwebusers.ymlfile looks like:
Figure 17.34 – The webusers.yml file storing non-sensitive user data
- Next, let’s protect our secrets by encrypting the
passwords.ymlfile usingYou’ll be prompted to create a vault password to protect the file. Remember the password, as we’ll be using it throughout this section.ansible-vault encrypt passwords.yml - Once you’re done, check the
passwords.ymlfile with theThe output for the preceding command shows the following:cat passwords.yml
Figure 17.35 – The encrypted passwords.yml file
- We can view the content of the
passwords.ymlfile with theansible-vault view passwords.yml - You’ll be prompted for the vault password we created previously. The output shows the streamlined YAML content corresponding to our protected file:

Figure 17.36 – Viewing the content of the protected file
- If you need to make changes, you can edit the encrypted file with the
After authenticating with the vault password, the command will open a local editor (ansible-vault edit passwords.yml
vi) to edit your changes. If you want to re-encrypt your protected file with a different password, you can run the following command:ansible-vault rekey passwords.yml - You’ll be prompted for the current vault password, followed by the new password.
Now, let’s learn how to reference secrets in our playbook.
Referencing secrets in playbooks
Section titled “Referencing secrets in playbooks”To reference secrets, follow these steps:
- First, let’s make sure we can read our password from the vault. Let’s make a new file with the following lines in it. We will call it
create-user-new.yml:
Figure 17.37 – Debugging vault access with new create-user-new.yml file
We’ve added a couple of tasks:
include_vars(lines 6 - 8): Reading variables from thepasswords.ymlfiledebug(lines 10 - 12): Debugging the playbook and logging the password that was read from the vault
None of these tasks are aware that the passwords.yml file is protected. Line 12 is where the magic happens:
msg: "{{ vars[username]['password'] }}"- We use the
vars[]dictionary to query a specific variable in the playbook.vars[]is a reserved data structure for storing all the variables that were created viavarsandinclude_varsin an Ansible playbook. We can query the dictionary based on a key appointed byusername:Our playbook gets{{ vars[username] }}usernamefrom the./group_vars/webservers.ymlfile, and its value iswebuser. Consequently, thevars[webuser]dictionary item reads the corresponding entry from thepasswords.ymlfile:webuser: { password: changeit! } - To get the password value from the corresponding key-value pair, we specify the
'password'key in thevars[username]{{ vars[username]['password'] }} - Let’s run this playbook with the
We invoked theansible-playbook --ask-vault-pass create-user-new.yml
--ask-vault-passoption to let Ansible know that our playbook needs vault access. Without this option, we’ll get an error when running the playbook. Here’s the relevant output for ourdebugtask:
Figure 17.38 – The playbook successfully reading secrets from the vault
Here, we can see that the playbook successfully retrieves the password from the vault.
- Let’s wrap up our
create-user-new.ymlplaybook by adding the following code:
Figure 17.39 – The playbook creating a user with a password retrieved from the vault
Here are a few highlights of the current implementation:
- We’ve added a
varsblock (1 in Figure 17.39) to define a localpasswordvariable (at the play scope) for reading the password from the vault; we are reusing thepasswordvariable in multiple tasks. - The
include_varstask (2 in the preceding screenshot) adds an external reference to the variables defined in the protectedpasswords.ymlfile. - The
debugtask (3 in the preceding screenshot) helped with the initial debugging effort to make sure we could read the password from the vault. You may choose to remove this task or leave it in place for future use. If you keep the task, make sure you haveno_log: trueenabled (line 15) to avoid logging sensitive information in the output. When debugging, you can temporarily setno_log: false. - The
usertask (4 in the preceding screenshot) reads thepasswordvariable and hashes the corresponding value. This hashing is required by the Ansibleusermodule for security reasons. We also added acommentfield with additional user information. This field maps to the Linux General Electric Comprehensive Operating System (GECOS) record of the user. See the Managing users section of Chapter 4, Managing Users and Groups, for related information.
- Let’s run the playbook with the
After the command completes successfully, you can verify the new user account in a couple of ways:ansible-playbook --ask-vault-pass create-user-new.yml
- Use SSH to connect to any of the web servers using the related username and password,
ssh webuser@ans-web1
- Look for the
webuserrecord in/etc/passwdon theans-web1
tail -n 10 /etc/passwd- You should see the following line in the output (you’ll notice the GECOS
webuser:x:1001:1001:Regular web user:/home/webuser:/bin/sh - Look for the
- Use SSH to connect to any of the web servers using the related username and password,
You may want to run the ansible-playbook command without supplying a vault password, as required by --ask-vault-pass. Such functionality is essential in scripted or automated workflows when using Ansible Vault. To make your vault password automatically available when you’re running a playbook using sensitive data, start by creating a regular text file, preferably in your home directory; for example, ~/vault.pass. Add the vault password to this file in a single line. Then, you can choose either of the following options to use the vault password file:
- Create the following
export ANSIBLE_VAULT_PASSWORD_FILE=~/vault.pass
- Add the following line to the
ansible.cfgfile’s[``defaults]vault_password_file = ~/vault.pass
Now, you can run the create-user-new playbook without the -- ask-vault-pass option:
ansible-playbook create-user.ymlSometimes, protecting multiple secrets with a single vault password raises security concerns. Ansible supports multiple vault passwords through vault IDs.
Using vault IDs
Section titled “Using vault IDs”A vault ID is an identifier, or a label, associated with one or more vault secrets. Each vault ID has a unique password to unlock the encryption and decryption of the corresponding secrets. To illustrate the use of vault IDs, let’s look at our passwords.yml file. Suppose we want to secure this file using a vault ID. The following command creates a vault ID labeled passwords and prompts us to create a password:
ansible-vault create --vault-id passwords@prompt passwords.ymlThe passwords vault ID protects the passwords.yml file. Now, let’s assume we also want to secure some API keys associated with users. If we stored these secrets in the apikeys.yml file, the following command would create a corresponding vault ID called apikeys:
ansible-vault create --vault-id apikeys@prompt apikeys.ymlHere, we created two vault IDs, each with its own password and protecting different resources.
The benefits of vault IDs are as follows:
- They provide an improved security context when managing secrets. If one of the vault ID passwords becomes compromised, resources that have been secured by the other vault IDs are still protected.
- With vault IDs, we can also leverage different access levels to vault secrets. For example, we can define
admin,dev, andtestvault IDs for related groups of users. Alternatively, we can have multiple configuration management projects, each with its own dedicated vault IDs and secrets; for example,user-config,web-config, anddb-config. - You can associate a vault ID with multiple secrets. For example, the following command creates a
user-configvault ID that secures thepasswords.ymlandapi-keys.ymlansible-vault create --vault-id user-config@prompt passwords.yml apikeys.yml - When using vault IDs, we can also specify a password file to supply the related vault password. The following command encrypts the
apikeys.ymlfile, which reads the corresponding vault ID password from theapikeys.passYou can name your vault password files anything you want, but keeping a consistent naming convention, possibly one that matches the related vault ID, will make your life easier when you’re managing multiple vault secrets.ansible-vault encrypt --vault-id [email protected] apikeys.yml - Similarly, you can pass a vault ID (
passwords) to a playbook (create-users-new.yml) with theansible-playbook --vault-id [email protected] create-users-new.yml
For more information about Ansible Vault, you may refer to the related online documentation at https://docs.ansible.com/ansible/latest/user_guide/vault.html.
So far, we have created a single user account with a password. What if we want to onboard multiple users, each with their own password? As we noted previously, we could call the create-user playbook and override the username and password variables using the --extra-vars option parameter. But this method is not a very efficient one, not to mention the difficulty of maintaining it. In the next section, we’ll show you how to use task iteration in Ansible playbooks.
Working with loops
Section titled “Working with loops”Loops provide an efficient way of running a task repeatedly in Ansible playbooks. There are several loop implementations in Ansible, and we can classify them into the following categories based on their keyword or syntax:
loop: The recommended way of iterating through a collectionwith_<lookup>: Collection-specific implementations of loops; examples includewith_list,with_items, andwith_dict, to name a few
In this section, we’ll keep our focus on the loop iteration (equivalent to with_list), which is best suited for simple loops. Let’s expand our previous use case and adapt it to create multiple users. We’ll start by making a quick comparison between running repeated tasks with and without loops:
- As a preparatory step, make sure
~/ansibleis your current working directory. Also, you can delete the./group_varsfolder, as we’re not using it anymore. Now, let’s create a couple of playbooks,create-users1.ymlandcreate-users2.yml, as shown in the following screenshot:
Figure 17.40 – Playbooks with multiple versus iterative tasks
Both playbooks create three users: webuser, webadmin, and webdev. The create-users1 playbook has three distinct tasks, one for creating each user. On the other hand, create-users2 implements a single task iteration using the loop directive (in line 15):
loop: "{{ users }}"The loop iterates through the items of the users list, defined as a play variable in lines 6-9. The user task uses the {{ item }} variable, referencing each user while iterating through the list.
- Before running any of these playbooks, let’s also create one for deleting the users. We’ll name this playbook
delete-users2.yml,and it will have a similar implementation tocreate-users2.yml:
Figure 17.41 – A playbook using a loop for deleting users
- Now, let’s run the
create-users1playbook while targeting only theans-web1In the output, we can see that three tasks have been executed, one for each user:ansible-playbook create-users1.yml --limit ans-web1
Figure 17.42 – The output of the create-users1 playbook, with multiple tasks
- Let’s delete the users by running the
delete-users2.ymlThe output is as shown in the following screenshot:ansible-playbook delete-users2.yml --limit ans-web1
Figure 17.43 – Deleting users using the playbook
- Now, let’s run the
create-users2playbook, again targeting only theweb1This time, the output shows a single task iterating through all the users:ansible-playbook create-users2.yml --limit ans-web1
Figure 17.44 – The output of the create-users2 playbook, with a single task iteration
The difference between the two playbook runs is significant:
- The first playbook executes a task for each user. While forking a task is not an expensive operation, you can imagine that creating hundreds of users would incur a significant load on the Ansible runtime.
- On the other hand, the second playbook runs a single task, loading the
usermodule three times, to create each user. Loading a module takes significantly fewer resources than running a task.
For more information about loops, you may refer to the related online documentation at https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html.
Now that we know how to implement a simple loop, we’ll make our playbook more compact and maintainable.
Configuring our playbooks
Section titled “Configuring our playbooks”Apart from enhancing our playbooks, we’ll also try to come closer to a real-world scenario by storing the users and their related passwords in a reusable and secure fashion.
We will keep the web users’ information in the users.yml file. The related passwords are in the users_passwords.yml file. Here are the two files, along with some example user data:

Figure 17.45 – The users.yml and users_passwords.yml files
Let’s take a closer look at these files:
- The
users.ymlfile contains a dictionary with a single key-value pair:- Key:
webusers- Value: A list of
usernameand
- Value: A list of
- Key: