Imagine you are managing ten Linux servers.
You need to install Java on all ten servers, configure Nginx on five servers, create application directories, deploy your application, and update configuration files.
How would you do it?
One option is to connect to each server using SSH and execute the commands manually.
But what happens when you have 100 servers? Or 500?
You would be repeating the same commands again and again. And there is always a chance that you forget something or configure one server differently from the others.
Wouldn't it be easier to write the instructions once and let a tool execute them across all your servers?
This is where Ansible comes into the picture.
Ansible is an open-source automation tool used for configuration management, application deployment, infrastructure automation, and orchestration.
Instead of manually configuring every server, you describe what you want in simple YAML files, and Ansible takes care of applying that configuration.
In this article, we'll understand why Ansible exists, how its architecture works, how to organize servers using inventory groups, and how to automate tasks using ad hoc commands and YAML playbooks.
We'll also explore variables, privilege escalation, Ansible Vault, and tags using practical examples.
Versions used in this article:
- Ansible Community Package: 15.0.0.
- ansible-core: 2.22.0.
- Python: 3.13 or later for the control node.
- YAML: 1.2-compatible syntax.
These versions were checked on November 26, 2026. The examples focus on Linux managed nodes using SSH.
Table of contents
- What is Ansible?
- How Ansible works
- Install Ansible
- Host inventory
- Ad hoc commands
- Ansible playbooks
- Ansible Vault
- Ansible tags
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
What is Ansible?
Ansible is an open-source IT automation tool used to automate infrastructure management, configuration management, application deployment, and repetitive administrative tasks.
In simple words, Ansible helps you manage multiple machines from one central machine.
Suppose you have five Linux servers.
Without Ansible, you might connect to every server and execute commands manually.
With Ansible, you write the instructions once and execute them against all five servers.
For example, you can tell Ansible:
- Install Java on all application servers.
- Install Nginx on all web servers.
- Create a particular user on every server.
- Copy a configuration file to multiple machines.
- Start or stop services.
- Deploy an application.
Instead of repeating commands manually, Ansible automates the work.
Why configuration management?
Before understanding Ansible, let's understand configuration management.
Configuration management is the process of maintaining systems in a consistent and desired state.
Let's take an example.
A company has three web servers:
Server 1 Server 2 Server 3
Ubuntu Ubuntu Ubuntu
Java 17 Java 17 Java 11
Nginx Nginx Nginx
Running Running Stopped
Notice the problem?
Server 3 has Java 11 instead of Java 17, and Nginx is not running.
The servers are supposed to have the same configuration, but they are not consistent.
This can cause application failures.
We want all three servers to have:
Server 1 Server 2 Server 3
Ubuntu Ubuntu Ubuntu
Java 17 Java 17 Java 17
Nginx Nginx Nginx
Running Running Running
Ansible helps us achieve and maintain this desired state.
We can write instructions such as:
- name: Ensure Java is installed
ansible.builtin.package:
name: java-17-openjdk
state: present
- name: Ensure Nginx is running
ansible.builtin.service:
name: nginx
state: started
Ansible executes these tasks on the selected servers.
An important concept here is Idempotency.
Idempotency means that performing the same operation multiple times produces the same desired final state.
For example:
state: present
means that the package should be installed.
If it is already installed, Ansible does not need to install it again.
Similarly:
state: started
means that the service should be running.
If it is already running, Ansible normally leaves it running.
This makes configuration management much easier.
Infrastructure as Code (IaC)
Ansible also follows the Infrastructure as Code approach.
Infrastructure as Code means managing infrastructure and its configuration using files instead of performing every operation manually.
For example:
ansible-project/
|
+-- inventory.ini
|
+-- install-java.yml
|
+-- configure-nginx.yml
|
+-- deploy-application.yml
|
+-- group_vars/
|
+-- webservers.yml
|
+-- dbservers.yml
These files can be stored in Git just like application source code.
This gives us several advantages:
- We can track configuration changes.
- We can review infrastructure changes.
- We can reuse configurations.
- We can maintain consistent environments.
- We can recreate configurations when required.
That's the basic idea behind Infrastructure as Code.
Ansible and Red Hat
You might have noticed that Ansible is closely associated with Red Hat.
So, who owns Ansible?
Let's understand its history.
Ansible was originally developed as an open-source automation project by Michael DeHaan.
Ansible, Inc. was the company behind the project.
On October 16, 2015, Red Hat announced that it would acquire Ansible, Inc.
Red Hat later expanded its automation portfolio around Ansible.
Today, we have two important things to understand:
1. Ansible Open Source Project
Ansible is an open-source automation project with community contributions.
Developers and system administrators can use it to automate their infrastructure without purchasing an enterprise product.
2. Red Hat Ansible Automation Platform
Red Hat also provides Ansible Automation Platform, an enterprise automation solution built around Ansible.
It provides additional enterprise capabilities for managing and scaling automation across organizations.
So, remember:
- Red Hat acquired Ansible, Inc. in 2015.
- Ansible continues as an open-source automation project.
- Red Hat provides an enterprise automation platform based on Ansible.
How Ansible works
Now let's understand how Ansible actually communicates with multiple servers.
Ansible follows a simple architecture with two important components:
- Control Node.
- Managed Node.
Control node and managed nodes
Control Node
A control node is the machine where Ansible is installed and executed.
It is responsible for:
- Storing inventory files.
- Storing YAML playbooks.
- Executing Ansible commands.
- Connecting to managed machines.
- Controlling automation tasks.
For example, your laptop can act as a control node.
Managed Nodes
Managed nodes are the remote machines that Ansible manages.
For example:
- Web servers.
- Database servers.
- Application servers.
- Cloud virtual machines.
Ansible connects to these machines and performs the required operations.
Let's understand this with a diagram.
CONTROL NODE
(Your Linux Machine)
+-------------------+
| |
| Ansible |
| |
| Inventory File |
| |
| Playbook (YAML) |
| |
+-------------------+
|
|
SSH Connection
|
+------------+------------+
| | |
v v v
+---------+ +---------+ +---------+
| WEB 1 | | WEB 2 | | DB 1 |
| | | | | |
| Managed | | Managed | | Managed |
| Node | | Node | | Node |
+---------+ +---------+ +---------+
The control node sends instructions to managed nodes.
For Linux servers, SSH is commonly used for communication.
For example:
Control Node
|
| SSH
v
192.168.1.10
|
| Execute Task
v
Install Nginx
This is how Ansible manages remote machines.
Agentless architecture
One important feature of Ansible is that it is agentless.
What does agentless mean?
Some configuration management tools require additional agent software to be installed on every managed server.
Ansible generally does not require this.
For Linux managed nodes, Ansible uses SSH to connect to the machines and execute its modules.
CONTROL NODE
+-----------+
| Ansible |
+-----------+
|
| SSH
|
+---------+---------+
| |
v v
+----------+ +----------+
| Server 1 | | Server 2 |
| | | |
| No | | No |
| Ansible | | Ansible |
| Agent | | Agent |
+----------+ +----------+
The managed Linux nodes normally need:
- SSH connectivity.
- A user account that can connect to the server.
- Python for most Ansible modules.
Ansible itself does not need to be installed on those managed nodes.
Behind the scenes
When you run an Ansible command:
- Ansible reads the inventory.
- It identifies the target machines.
- It establishes a connection to the selected machines.
- It executes the required module.
- It collects the result.
- It displays the result on the control node.
This is why we can manage multiple machines from one place.
Install Ansible
Before using Ansible commands, we need to install Ansible on our control node.
The official Ansible documentation recommends using pipx for installing the Python-based Ansible package in an isolated environment.
Install the Ansible package:
pipx install --include-deps "ansible==15.0.0"
Check the installation:
ansible --version
To check the community package version:
ansible-community --version
If you are using a Python environment that does not support pipx, refer to the official installation guide for other supported installation methods.
Ansible and ansible-core
You might encounter two different package names:
ansibleansible-core
Are they the same?
No.
ansible-core
ansible-core contains the core Ansible runtime and a set of built-in modules, plugins, and command-line tools.
It provides the main functionality required to execute Ansible automation.
ansible
The ansible community package includes ansible-core along with a curated collection of additional community Ansible collections.
Think of it like this:
ANSIBLE PACKAGE
+-------------------+
| |
| ansible-core |
| |
+-------------------+
| |
| Community |
| Collections |
| |
+-------------------+
For learning Ansible and using a broad collection of community modules, installing the full ansible package is convenient.
Host inventory
Now we have Ansible installed.
But there is a problem.
How does Ansible know which servers it should manage?
Imagine you have 50 servers.
Should you manually provide all 50 IP addresses every time you execute a command?
That would be difficult to maintain.
This is where the Host Inventory comes into the picture.
What is an inventory file?
An inventory file is a file that contains information about the machines Ansible manages.
It tells Ansible:
- Which machines are available.
- Their hostnames or IP addresses.
- Which group they belong to.
- Additional connection information.
- Host-specific variables.
The default inventory file location is:
/etc/ansible/hosts
You can also create your own inventory file inside your project.
For example:
ansible-project/
|
+-- inventory.ini
|
+-- playbook.yml
Let's create an inventory file.
inventory.ini
[webservers]
192.168.1.10
192.168.1.11
192.168.1.12
[dbservers]
192.168.1.20
192.168.1.21
Here:
-
webserversis a group. -
dbserversis another group. - The IP addresses represent managed machines.
These are example addresses. Replace them with the actual IP addresses or DNS names of your servers.
Now Ansible knows which machines belong to our infrastructure.
Grouping hosts
Why do we need groups?
Imagine you have 20 servers:
- 10 web servers.
- 5 database servers.
- 5 application servers.
Sometimes you want to execute a command on all servers.
Sometimes you want to execute it only on web servers.
Grouping helps us do this.
Let's understand:
INVENTORY
|
+------------+------------+
| | |
v v v
WEBSERVERS DBSERVERS APP-SERVERS
| | |
+---+---+ +---+---+ +---+---+
| | | | | | | | |
W1 W2 W3 DB1 DB2 DB3 A1 A2 A3
We can define these groups inside our inventory file.
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
db2.example.com
[appservers]
app1.example.com
app2.example.com
Now we can target specific groups.
For example:
ansible webservers -m ansible.builtin.ping -i inventory.ini
This command targets only machines belonging to the webservers group.
We can also target every machine:
ansible all -m ansible.builtin.ping -i inventory.ini
Here, all is a special inventory group that matches all hosts in the inventory.
Why is grouping useful?
Because different servers have different responsibilities.
For example:
- Install Nginx only on web servers.
- Install database software only on database servers.
- Deploy application files only on application servers.
Inventory groups make this much easier.
Ad hoc commands
Now that we understand inventory, let's execute some commands on remote machines.
Ansible provides two main ways to execute automation:
- Ad hoc commands.
- Playbooks.
Let's first understand ad hoc commands.
An ad hoc command is a one-time Ansible command used to perform a specific task on one or more managed nodes.
For example:
- Check connectivity.
- Display the current date.
- Check server uptime.
- Copy a file.
- Start a service.
Ad hoc commands are useful for quick operations that you don't need to store as a reusable playbook.
The general syntax is:
ansible <host-pattern> -m <module> -a "<arguments>"
Let's understand:
ansible all -m ping -a ""
| | |
| | +-- Module arguments
| |
| +-------- Module
|
+------------- Target hosts
-
ansible: Command-line tool. -
all: Target machines. -
-m: Specify the module. -
-a: Pass arguments to the module.
Test connectivity with ping
Suppose we have multiple servers in our inventory.
We want to check whether Ansible can communicate with them.
We can use the Ansible ping module.
1. Ping all servers
ansible all -m ansible.builtin.ping -i inventory.ini
Example output:
192.168.1.10 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.1.11 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.1.12 | SUCCESS => {
"changed": false,
"ping": "pong"
}
This means Ansible successfully communicated with these servers.
2. Ping only web servers
ansible webservers -m ansible.builtin.ping -i inventory.ini
Now only web servers are targeted.
Important:
Ansible's ping module is not the same as the Linux ping command.
Linux ping checks network reachability using ICMP.
Ansible's ping module checks Ansible connectivity and whether it can execute the required module on the managed node.
Run commands on managed nodes
Apart from checking connectivity, we can execute commands on remote servers.
Let's explore some examples.
1. Display the current date on all servers
ansible all -m ansible.builtin.shell -a "date" -i inventory.ini
Example output:
192.168.1.10 | CHANGED | rc=0 >>
Thu Nov 26 10:00:00 UTC 2026
The actual date, time, and timezone will differ.
2. Check server uptime
ansible all -m ansible.builtin.shell -a "uptime" -i inventory.ini
Example output:
192.168.1.10 | CHANGED | rc=0 >>
10:00:00 up 5 days, 3:20, 2 users, load average: 0.10, 0.20, 0.15
The output depends on the server.
3. Execute a command only on web servers
ansible webservers -m ansible.builtin.shell -a "whoami" -i inventory.ini
This displays the remote user executing the command.
4. Copy a file to all web servers
ansible webservers -m ansible.builtin.copy -a "src=app.conf dest=/tmp/app.conf" -i inventory.ini
This copies app.conf from the control node to /tmp/app.conf on each selected machine.
One important thing:
For commands that do not require shell features such as pipes, redirects, or shell expansion, prefer ansible.builtin.command.
Use ansible.builtin.shell when you actually need shell functionality.
These commands are called ad hoc commands because they perform individual tasks without requiring a YAML playbook.
Ansible playbooks
Ad hoc commands are useful for quick operations.
But imagine configuring 100 servers.
You need to:
- Install Java.
- Create application directories.
- Copy configuration files.
- Deploy the application.
- Start the application service.
- Verify the deployment.
Writing a separate command every time becomes difficult.
We need a reusable way to describe these operations.
This is where Ansible Playbooks come into the picture.
An Ansible playbook is a YAML file containing instructions that Ansible executes on selected managed nodes.
Playbooks are used for:
- Deploying applications.
- Configuring systems.
- Managing services and users.
- Orchestrating build processes.
- Running tests and verification tasks.
Ansible can orchestrate build tools such as Maven or Gradle, but it does not replace those tools themselves.
Why YAML?
YAML is a human-readable data serialization format.
Ansible uses YAML because it makes automation instructions easy to read and maintain.
For example:
name: Install Java
hosts: webservers
This is easier to understand than writing a large number of shell commands.
Play, hosts, variables and tasks
A playbook contains one or more plays.
A play defines which machines should receive a set of tasks.
Each task describes an operation Ansible should execute.
For beginners, it's useful to understand three important parts of a play:
- Hosts.
- Variables.
- Tasks.
These are common playbook sections, not the only fields a play can contain.
Let's understand each one.
1. Hosts
The hosts keyword defines the target machines.
Example:
hosts: webservers
This tells Ansible to execute the play against all machines belonging to the webservers inventory group.
We could also write:
hosts: dbservers
Now the play targets database servers.
2. Variables
Variables allow us to store values that can be reused in multiple tasks.
For example:
vars:
package_name: httpd
service_name: httpd
Instead of writing the package name repeatedly, we can refer to the variable.
Ansible uses Jinja2 syntax to reference variables:
"{{ package_name }}"
3. Tasks
Tasks define the operations Ansible should execute.
For example:
tasks:
- name: Install HTTP server
ansible.builtin.package:
name: httpd
state: present
- name: Start HTTP server
ansible.builtin.service:
name: httpd
state: started
Each task uses an Ansible module.
A module is a reusable unit of functionality that performs a specific operation.
Some commonly used modules are:
-
ansible.builtin.ping: Test Ansible connectivity. -
ansible.builtin.copy: Copy files. -
ansible.builtin.file: Manage files and directories. -
ansible.builtin.package: Manage packages. -
ansible.builtin.service: Manage services. -
ansible.builtin.command: Execute commands. -
ansible.builtin.shell: Execute commands through a shell.
Let's visualize the structure.
PLAYBOOK (YAML)
|
v
+---------------+
| PLAY |
+---------------+
|
+-----------+-----------+
| | |
v v v
HOSTS VARS TASKS
| | |
| | |
Target Variables Operations
Machines and Values to Execute
|
+---------+---------+
| | |
v v v
COPY PACKAGE SERVICE
FILE INSTALL START
Now let's create an actual playbook.
A practical playbook
Let's say we want to configure two web servers.
Our goal is:
- Install Apache HTTP Server.
- Start the Apache service.
- Deploy a simple HTML page.
We'll create a file named:
configure-webservers.yml
configure-webservers.yml
---
- name: Configure Web Servers
hosts: webservers
become: true
vars:
web_package: httpd
web_service: httpd
page_title: "Welcome to Ansible"
tasks:
- name: Install Apache HTTP Server
ansible.builtin.package:
name: "{{ web_package }}"
state: present
tags:
- install
- name: Start Apache Service
ansible.builtin.service:
name: "{{ web_service }}"
state: started
enabled: true
tags:
- service
- name: Deploy HTML Page
ansible.builtin.copy:
dest: /var/www/html/index.html
content: "<h1>{{ page_title }}</h1>\n"
mode: "0644"
tags:
- deploy
This example targets Linux systems that provide the httpd package and service, such as suitable RHEL-based systems.
Let's understand what happens.
Step 1: Define the play name
- name: Configure Web Servers
This is the name of our play.
It makes the playbook output easier to understand.
Step 2: Select target hosts
hosts: webservers
Ansible executes this play on all hosts belonging to the webservers group.
Step 3: Define variables
vars:
web_package: httpd
web_service: httpd
page_title: "Welcome to Ansible"
These values can be accessed inside tasks.
For example:
name: "{{ web_package }}"
Ansible replaces the variable with its actual value.
Step 4: Execute tasks
The first task installs Apache.
The second task ensures that Apache is running and enabled to start automatically when the system boots.
The third task copies an HTML page to the web server's document root.
Notice that we're not manually running commands such as dnf install httpd or systemctl start httpd.
We're describing the desired state using Ansible modules.
Run the playbook
ansible-playbook -i inventory.ini configure-webservers.yml
Example output (trimmed):
PLAY [Configure Web Servers] **************************
TASK [Gathering Facts] *********************************
ok: [192.168.1.10]
ok: [192.168.1.11]
TASK [Install Apache HTTP Server] **********************
changed: [192.168.1.10]
changed: [192.168.1.11]
TASK [Start Apache Service] ****************************
changed: [192.168.1.10]
changed: [192.168.1.11]
TASK [Deploy HTML Page] ********************************
changed: [192.168.1.10]
changed: [192.168.1.11]
PLAY RECAP *********************************************
192.168.1.10 : ok=4 changed=3 failed=0
192.168.1.11 : ok=4 changed=3 failed=0
The actual output and number of changed tasks depend on the initial configuration of your servers.
Now imagine running the same playbook again.
If everything is already configured correctly, Ansible should report that most tasks are ok instead of changed.
This is the benefit of idempotent configuration management.
What does become true do?
You might have noticed this line in our playbook:
become: true
Why do we need it?
Imagine connecting to a Linux server using a normal user account.
You can execute normal commands, but installing packages or modifying system-level directories usually requires administrator privileges.
For example:
dnf install httpd
This generally requires root privileges.
One solution is to use sudo.
In Ansible, we use Privilege Escalation.
The become keyword tells Ansible to execute tasks using elevated privileges.
Example:
- name: Install Apache
hosts: webservers
become: true
tasks:
- name: Install HTTP Server
ansible.builtin.package:
name: httpd
state: present
Here:
become: true
means Ansible should escalate privileges for the tasks in this play.
By default, the become user is generally root and the default method is sudo, depending on configuration.
We can also use it for a specific task instead of the entire play.
tasks:
- name: Display current user
ansible.builtin.command: whoami
- name: Install Apache
ansible.builtin.package:
name: httpd
state: present
become: true
In this example, only the installation task uses elevated privileges.
What if sudo requires a password?
Run:
ansible-playbook -i inventory.ini configure-webservers.yml --ask-become-pass
Or use the shorter option:
ansible-playbook -i inventory.ini configure-webservers.yml -K
Ansible will prompt for the privilege escalation password.
Remember:
-
become: trueenables privilege escalation. -
become_userspecifies the user to become. -
become_methodspecifies the escalation method. -
-Kasks for the privilege escalation password.
Playbook variables and extra vars
Variables help us avoid hardcoding values inside every task.
Imagine we have three environments:
- Development.
- Testing.
- Production.
We may want to deploy different application versions in each environment.
Instead of maintaining three completely different playbooks, we can pass variables.
For example:
---
- name: Deploy Application
hosts: webservers
vars:
app_version: "1.0.0"
tasks:
- name: Display application version
ansible.builtin.debug:
msg: "Deploying version {{ app_version }}"
Here:
app_version: "1.0.0"
is a playbook variable.
Ansible uses double curly braces to reference variables:
"{{ app_version }}"
Now, what if we want to override the application version without editing the playbook?
We can use Extra Variables.
The --extra-vars option allows us to pass variables directly through the command line.
Example:
ansible-playbook -i inventory.ini deploy.yml --extra-vars "app_version=2.0.0"
We can also use its shorthand:
ansible-playbook -i inventory.ini deploy.yml -e "app_version=2.0.0"
Now the output will be:
TASK [Display application version] ************************
ok: [192.168.1.10] => {
"msg": "Deploying version 2.0.0"
}
Notice that the original value was:
app_version: "1.0.0"
But we passed:
app_version=2.0.0
The extra variable overrides the playbook variable.
We can also pass multiple variables.
ansible-playbook -i inventory.ini deploy.yml \
-e "app_version=2.0.0 environment=production"
For values containing spaces or more complex data, JSON is useful:
ansible-playbook -i inventory.ini deploy.yml \
-e '{"app_version":"2.0.0","environment":"production"}'
Important: Extra variables have very high precedence among Ansible variable sources. Use them carefully because they can override values defined in inventory and playbooks.
Ansible Vault
Now let's discuss an important problem.
Suppose you're writing Ansible playbooks for a production environment.
Your application needs:
- Database password.
- API keys.
- SSH credentials.
- Cloud access credentials.
Where should you store these values?
Storing passwords directly inside a normal YAML file is dangerous.
For example:
db_username: admin
db_password: mysecretpassword
If you push this file to GitHub, anyone with access to that repository may be able to read the password.
This is where Ansible Vault helps.
Ansible Vault is a feature provided by Ansible to encrypt sensitive data.
It supports encrypting:
- Entire files.
- Individual variables and values.
Encrypt, view, decrypt and edit
Let's create a file named:
database.yml
Add some sensitive information:
db_username: admin
db_password: mysecretpassword
db_host: 192.168.1.20
Now let's explore the Vault commands.
1. Encrypt
To encrypt an existing file:
ansible-vault encrypt database.yml
Ansible will prompt you for a vault password.
After encryption, the file contents become unreadable ciphertext.
The beginning of an encrypted file looks similar to:
$ANSIBLE_VAULT;1.1;AES256
663864653362633034...
The exact encrypted data will be different.
2. View
What if you want to inspect an encrypted file without permanently decrypting it?
Use:
ansible-vault view database.yml
Ansible asks for the vault password and displays the decrypted contents.
3. Edit
What if you want to modify an encrypted file?
Use:
ansible-vault edit database.yml
Ansible temporarily decrypts the file, opens it in your configured editor, and encrypts it again after you save and close it.
4. Decrypt
What if you want to permanently decrypt the file?
Use:
ansible-vault decrypt database.yml
After this command, the file is stored as normal readable YAML again.
Be careful: the decrypted file is no longer protected by Vault encryption.
Quick recap:
ansible-vault encrypt file.yml
|
v
Encrypt File
ansible-vault view file.yml
|
v
View Contents
ansible-vault edit file.yml
|
v
Edit Contents
ansible-vault decrypt file.yml
|
v
Decrypt File
Using Vault with a playbook
Suppose our playbook loads an encrypted variables file.
We can execute it with:
ansible-playbook -i inventory.ini deploy.yml --ask-vault-pass
Ansible prompts for the vault password and uses it to decrypt the required data.
Important: Never store the Vault password alongside the encrypted file in the same Git repository without a proper secret-management strategy.
Ansible tags
Imagine your playbook contains 20 tasks.
For example:
- Install packages.
- Create directories.
- Copy configuration files.
- Start services.
- Deploy applications.
- Verify deployment.
Suppose you only want to execute the deployment task.
Should you execute all 20 tasks again?
Not necessarily.
This is where Ansible Tags become useful.
Tags allow us to select which plays or tasks should execute when running a playbook.
We can also skip tasks using specific tags.
Add tags to tasks
Let's revisit our web server playbook.
We can assign different tags to different tasks.
Example:
---
- name: Configure Web Servers
hosts: webservers
become: true
tasks:
- name: Install Apache
ansible.builtin.package:
name: httpd
state: present
tags:
- install
- name: Start Apache Service
ansible.builtin.service:
name: httpd
state: started
tags:
- service
- name: Deploy HTML Page
ansible.builtin.copy:
dest: /var/www/html/index.html
content: "<h1>Hello Ansible</h1>"
tags:
- deploy
Here, we've assigned three tags:
install
service
deploy
We can also use inline YAML list syntax:
tags: [install]
A task can have multiple tags:
tags: [install, setup]
Now each task can be selected using its tag.
Run or skip tagged tasks
First, let's see all the tags available in our playbook.
ansible-playbook -i inventory.ini configure-webservers.yml --list-tags
This displays the available tags without executing the tasks.
1. Execute only specific tags
Suppose we want to execute only installation and deployment tasks.
Run:
ansible-playbook -i inventory.ini configure-webservers.yml --tags "install,deploy"
Ansible executes tasks matching either install or deploy.
2. Skip specific tags
Suppose we want to execute every task except deployment.
Run:
ansible-playbook -i inventory.ini configure-webservers.yml --skip-tags "deploy"
Now the deployment task is skipped.
3. Preview selected tasks
You can also see which tasks would execute without actually running them:
ansible-playbook -i inventory.ini configure-webservers.yml --tags "install,deploy" --list-tasks
This is useful when working with large playbooks.
Remember:
--list-tags
|
v
Display available tags
--tags "install,deploy"
|
v
Execute tasks with either selected tag
--skip-tags "deploy"
|
v
Execute tasks except selected tag
Tags are particularly useful when a playbook contains many independent operations and you need to execute only a specific part.
Which one should I use?
We've covered different ways of working with Ansible.
Let's understand when to use each one.
1. Ad hoc commands vs Playbooks
Use ad hoc commands when:
- You need to execute a quick one-time operation.
- You want to check connectivity.
- You want to inspect server information.
- You need to copy a file quickly.
Use playbooks when:
- You want reusable automation.
- You need multiple tasks executed in order.
- You want to maintain configuration as code.
- You need repeatable deployments.
- You want to store automation in Git.
My default: Use playbooks for repeatable infrastructure and deployment operations. Use ad hoc commands for quick administrative tasks.
2. Ansible vs Shell Scripts
Shell scripts are useful when you need to execute a sequence of commands on a particular machine.
Ansible provides additional features such as:
- Inventory management.
- Remote execution across multiple hosts.
- Reusable modules.
- Variables.
- Privilege escalation.
- Tags.
- Configuration management.
For a simple local task, a shell script may be enough.
For managing multiple machines and keeping their configurations consistent, Ansible provides a more structured approach.
Common mistakes
Here are six mistakes beginners commonly make while learning Ansible.
Confusing control nodes and managed nodes: Ansible is installed on the control node, not normally on every managed Linux server. Understand which machine executes Ansible and which machines receive its tasks.
Using the wrong inventory group: If your playbook specifies
hosts: webservers, but your inventory contains only[dbservers], the expected hosts won't be selected. Always verify group names usingansible-inventory.Confusing the Ansible ping module with Linux ping:
ansible.builtin.pingverifies Ansible connectivity and module execution. It does not test ICMP network reachability.Ignoring YAML indentation: YAML uses indentation to represent structure. Use consistent spaces and avoid tabs. Incorrect indentation can prevent a playbook from being parsed.
Storing passwords in plain YAML files: Use Ansible Vault for sensitive information. Never commit unencrypted production credentials to Git.
Using extra variables without understanding precedence: Values passed using
-ecan override variables defined elsewhere. Check the variable values before running a production deployment.
Quick recap
Let's quickly revise everything we learned.
Ansible
- An open-source automation tool.
- Used for configuration management, deployment, and orchestration.
- Acquired through Red Hat's acquisition of Ansible, Inc. in 2015.
- Supports Infrastructure as Code.
Architecture
- Control Node: Machine where Ansible is installed and executed.
- Managed Node: Machine managed by Ansible.
- Agentless: No Ansible agent is normally required on Linux managed nodes.
- SSH: Common transport used to manage Linux servers.
Inventory
- Inventory contains managed host information.
-
/etc/ansible/hostsis the default inventory location. - Groups organize hosts based on their purpose.
- Examples:
webservers,dbservers,appservers.
Ad hoc commands
- Used for one-time operations.
ansible all -m ansible.builtin.pingansible webservers -m ansible.builtin.pingansible all -m ansible.builtin.shell -a "date"ansible all -m ansible.builtin.shell -a "uptime"
Playbooks
- Written in YAML.
- Contain one or more plays.
- Common play sections:
hosts,vars, andtasks. - Used for deployment, configuration, and system management.
- Modules perform operations such as copying files, installing packages, and starting services.
Privilege escalation and variables
-
become: true: Enable privilege escalation. -
vars: Define playbook variables. -
--extra-varsor-e: Pass variables from the command line.
Security and selective execution
- Ansible Vault: Encrypt sensitive data.
-
ansible-vault encrypt: Encrypt a file. -
ansible-vault view: View encrypted contents. -
ansible-vault edit: Edit an encrypted file. -
ansible-vault decrypt: Decrypt a file. -
tags: Select specific tasks. -
--list-tags: Display available tags. -
--tags: Execute selected tags. -
--skip-tags: Skip selected tags.
Try it yourself
Practice idea:
Create an Ansible project that manages two groups of servers:
ANSIBLE PROJECT
|
+---------+---------+
| |
v v
WEBSERVERS DBSERVERS
| |
v v
Install Apache Install MariaDB
Start Apache Start MariaDB
Deploy HTML Configure DB
Create an inventory file with webservers and dbservers groups.
Then create two playbooks:
-
webserver.yml: Install Apache, start the service, and deploy an HTML page. -
database.yml: Install MariaDB and start the database service.
Use variables to store package and service names. Use become: true for administrative tasks.
Bonus experiment:
Take your web server playbook and add these tags:
installservicedeploy
Now try executing only the installation task, skipping the deployment task, and listing all available tags.
Finally, encrypt your database variables using Ansible Vault.
The goal is to understand how a few YAML files can automate tasks that would otherwise require manually configuring multiple servers.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)