Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🔍 Introduction
Now that you have installed Ansible and configured your
environment, it’s time to start writing Playbooks — the real power of
Ansible!
In this chapter, you’ll learn:
By the end, you’ll be able to create production-ready
automation scripts with Ansible!
🛠️ Part 1: What is a
Playbook?
An Ansible Playbook is a YAML file that
describes:
Instead of running ad-hoc commands manually, Playbooks
automate complex, multi-step operations in a reliable, repeatable way.
A Playbook is your automation recipe!
📋 Basic Structure of a
Playbook
yaml
CopyEdit
---
-
name: Configure web servers
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache service
service:
name: apache2
state: started
✅ Human-readable and easily
extendable!
🔹 Key Components of a
Playbook
Component |
Purpose |
name |
Description of the
play or task |
hosts |
Target group
of hosts |
become |
Privilege escalation
(sudo) |
tasks |
List of actions
to perform |
vars |
Variables for reuse |
handlers |
Special tasks
triggered on changes |
roles |
Reusable, organized
sets of Playbooks and tasks |
🏗️ Part 2: Writing Your
First Playbook
Let’s build a simple Playbook to install and start Apache
web server.
📋 Example: Install Apache
install_apache.yml
yaml
CopyEdit
---
-
name: Install and start Apache webserver
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
update_cache: yes
- name: Ensure Apache is running
service:
name: apache2
state: started
✅ Save the file and run:
bash
CopyEdit
ansible-playbook
-i inventory.ini install_apache.yml
📚 Part 3: Advanced Task
Features
Tasks can become powerful with variables, conditionals,
loops, and handlers.
🔹 Using Variables
Variables make Playbooks flexible and DRY (Don't Repeat
Yourself).
Example:
yaml
CopyEdit
vars:
http_port: 80
tasks:
- name: Open firewall for HTTP
ufw:
rule: allow
port: "{{ http_port }}"
proto: tcp
✅ Easy to update across the
Playbook.
🔹 Using Conditionals
(when)
Execute tasks only if certain conditions are met.
yaml
CopyEdit
tasks:
- name: Install Nginx only on Ubuntu
apt:
name: nginx
state: present
when: ansible_distribution ==
"Ubuntu"
🔹 Using Loops
Repeat actions easily without repeating code.
yaml
CopyEdit
tasks:
- name: Install multiple packages
apt:
name: "{{ item }}"
state: present
loop:
- git
- curl
- vim
✅ Loops make tasks compact!
🔹 Using Handlers
Handlers are triggered only when notified by tasks.
yaml
CopyEdit
tasks:
- name: Update web content
copy:
src: index.html
dest: /var/www/html/index.html
notify: Restart Apache
handlers:
- name: Restart Apache
service:
name: apache2
state: restarted
⚙️ Part 4: Templates with Jinja2
Templates allow dynamic file generation based on variables.
📋 Example: Using a
Template
templates/index.html.j2
html
CopyEdit
<html>
<head><title>{{ site_name
}}</title></head>
<body>Welcome to {{ site_name
}}!</body>
</html>
Task to deploy:
yaml
CopyEdit
tasks:
- name: Deploy customized index page
template:
src: templates/index.html.j2
dest: /var/www/html/index.html
Variables (site_name) can be defined in the Playbook!
🧩 Part 5: Organizing
Playbooks with Roles
As Playbooks grow, you must modularize using roles.
Roles structure:
bash
CopyEdit
roles/
webserver/
tasks/
main.yml
templates/
files/
vars/
handlers/
✅ Roles make projects scalable,
reusable, and cleaner.
📋 Example: Assigning a
Role
yaml
CopyEdit
-
hosts: webservers
roles:
- webserver
📦 Part 6: Running and
Debugging Playbooks
Run Playbooks:
bash
CopyEdit
ansible-playbook
-i inventory.ini playbook.yml
🔹 Useful Playbook Run
Options
Option |
Purpose |
--check |
Dry-run (no changes
made) |
--diff |
Show
differences |
-v, -vv, -vvv |
Increase verbosity |
--limit "host_group" |
Target
specific hosts |
--start-at-task
"task name" |
Resume from a failed
task |
📋 Example: Dry Run
Playbook
bash
CopyEdit
ansible-playbook
-i inventory.ini install_apache.yml --check
✅ See what would change without
making changes.
📈 Best Practices for
Writing Playbooks
Best Practice |
Why Important |
Use clear names for
tasks |
Easier to debug |
Reuse code with roles and templates |
Scalable |
Group related tasks
into plays |
Logical structure |
Keep tasks idempotent |
Reliable
re-runs |
Use variables for
configuration |
Flexible and clean |
Separate sensitive data |
Use Ansible
Vault |
🌍 Real-World Playbook Use
Cases
🚀 Summary: What You
Learned in Chapter 3
Playbooks are the heart of Ansible — master them and you can automate almost anything!
BackAnswer:
Ansible is an open-source automation tool used for configuration management,
application deployment, and orchestration. It helps automate the process of
setting up and maintaining systems in a desired state without manual
intervention, using simple YAML-based playbooks over SSH connections.
Answer:
Unlike Puppet or Chef, Ansible is agentless (no software needed on
managed nodes), uses SSH for communication, and adopts a human-readable
YAML syntax instead of custom DSLs (domain-specific languages). This makes
it easier to install, learn, and operate, especially for small to mid-sized
teams.
Answer:
You only need to install Ansible on a control node (your local machine,
a management server, etc.). It then connects to managed nodes (servers,
devices) via SSH (Linux/macOS) or WinRM (Windows) to execute tasks. No software
needs to be installed on the managed nodes.
Answer:
A playbook is a YAML file that defines a set of tasks for Ansible to perform on
target hosts. Playbooks describe what the system should look like, not
how to achieve that state, making it easier to manage system configurations
declaratively.
Answer:
Idempotence in Ansible means that applying the same playbook multiple times
produces the same result — no unintended changes. Modules are designed
to detect the current system state and only perform actions if changes are
needed.
Answer:
Ansible Inventory is a file (typically hosts.ini or dynamic inventory scripts)
listing all the machines you want to manage. It organizes hosts into groups
(like [webservers], [dbservers]) and defines connection details for efficient
targeting and task execution.
Answer:
Yes. Ansible has built-in modules for managing cloud resources across AWS,
Azure, GCP, OpenStack, and more. You can provision VMs, configure networks,
manage storage, and deploy apps using the same Ansible playbooks.
Answer:
Ansible Vault is a feature that allows you to encrypt sensitive data
(like passwords, API keys) within your Ansible files. This ensures that secrets
remain protected even if your playbooks are stored in public or shared
repositories.
Answer:
Ansible can scale from managing a few servers to thousands by using
features like dynamic inventory, parallel task execution, and tools like Ansible
AWX/Tower for centralized control, scheduling, and reporting across large
environments.
Answer:
No. While Ansible is best known for managing Linux and Unix systems, it also
supports Windows systems through WinRM connections and provides specific
modules for Windows tasks like configuring IIS, managing services, and
installing applications.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)