- Server configuration
- Application deployment
- Infrastructure provisioning
- Patch management
- Security hardening
- Cloud automation
- Kubernetes automation
- SSH (Linux)
- WinRM (Windows)
1. Core Ansible Architecture
Before learning commands, understand the overall architecture.
| Control Node |
| (Ansible Server) |
+--------+---------+
|
SSH / WinRM
|
------------------------------------------------
| | |
+-------------+ +-------------+ +-------------+
| Managed Node| | Managed Node| | Managed Node|
| Server1 | | Server2 | | Server3 |
+-------------+ +-------------+ +-------------+
Components
| Component | Purpose |
|---|---|
| Control Node | Machine where Ansible runs |
| Managed Node | Target machine |
| Inventory | List of managed nodes |
| Playbook | Automation instructions |
| Module | Unit of work |
| Role | Reusable collection of tasks |
| Variables | Dynamic values |
| Facts | Information collected from hosts |
2. Installation and Verification
Ubuntu
sudo apt update sudo apt install ansible
RHEL
sudo dnf install ansible
Verify Installation
ansible --version
ansible [core 2.18]
3. Inventory (Most Important Concept)
Which machines should be managed?
Static Inventory
[web] web1.example.com web2.example.com [db] db1.example.com db2.example.com
Host Groups
[web] web1 web2 [db] db1 db2 [production:children] web db
├── web
│ ├── web1
│ └── web2
└── db
├── db1
└── db2
4. Checking Inventory
List All Hosts
ansible all --list-hosts
List Specific Group
ansible web --list-hosts
Display Inventory
ansible-inventory -i inventory.ini --list
Visual Tree
ansible-inventory -i inventory.ini --graph
5. First Ad-Hoc Command
Ping All Servers
ansible all -m ping
web1 | SUCCESS web2 | SUCCESS db1 | SUCCESS db2 | SUCCESS
Check Uptime
ansible all -m command -a "uptime"
Check Memory Usage
ansible all -m shell -a "free -h"
6. Modules
Modules are the fundamental building blocks of Ansible automation.
↓
Tasks
↓
Modules
Common Modules
| Module | Purpose |
|---|---|
| ping | Connectivity test |
| command | Execute command |
| shell | Execute shell command |
| copy | Copy files |
| file | Manage files/directories |
| package | Install packages |
| apt | Ubuntu package management |
| yum | RHEL package management |
| service | Manage services |
| user | User management |
| cron | Cron job management |
| git | Git repository operations |
| reboot | Reboot machines |
| uri | HTTP requests |
Example Module Usage
- name: Install nginx
apt:
name: nginx
state: present
7. Playbooks
Playbooks are YAML files that describe automation workflows.
Simple Playbook Example
---
- name: Install nginx
hosts: web
tasks:
- name: Install package
apt:
name: nginx
state: present
Run Playbook
ansible-playbook nginx.yml
8. Anatomy of a Playbook
---
- name: Web setup
hosts: web
become: true
vars:
package_name: nginx
tasks:
- name: Install package
apt:
name: "{{ package_name }}"
state: present
Main Sections
| Section | Purpose |
|---|---|
| hosts | Target machines |
| become | Privilege escalation (sudo) |
| vars | Variables |
| tasks | Work to perform |
| handlers | Triggered tasks |
| roles | Reusable components |
9. Variables
Variables make playbooks flexible and reusable.
Define Variables
vars: app_port: 8080
Use Variables
{{ app_port }}
Command Line Variables
ansible-playbook deploy.yml -e app_port=9090
Inventory Variables
web1 ansible_host=10.0.0.1 app_port=8080
15. Limiting Execution
Very important in production environments. Limiting execution allows you to target only specific hosts or groups instead of running against the entire inventory.
Run on One Host
ansible-playbook site.yml --limit web1
Run on a Group
ansible-playbook site.yml --limit web
Run on Multiple Hosts
ansible-playbook site.yml --limit web1,web2
Exclude a Host
ansible-playbook site.yml --limit 'web:!web2'
16. Privilege Escalation
Used when tasks require root or administrator privileges.
Enable Privilege Escalation
become: true
Equivalent to:
sudo
17. Parallelism
Ansible executes tasks in parallel across hosts. The number of parallel workers is controlled by the forks setting.
Check Current Forks Value
ansible-config dump | grep forks
Default:
5
Override Fork Count
ansible-playbook site.yml -f 20
Increasing forks can significantly speed up operations on large inventories.
18. Success and Failure Checking
Typical Playbook Result
ok=10
changed=2
unreachable=0
failed=0
| Field | Meaning |
|---|---|
| ok | Already compliant |
| changed | Configuration was modified |
| unreachable | SSH / connectivity issue |
| failed | Task execution failed |
Detailed Output
ansible-playbook site.yml -vvv
Dry Run
ansible-playbook site.yml --check
Show Differences
ansible-playbook site.yml --check --diff
19. Roles
As Ansible projects grow, playbooks can become large and difficult to maintain. Roles provide a standardized way to organize automation into reusable components.
Why Use Roles?
- Improves project structure
- Encourages reuse across environments
- Separates configuration, templates, variables, and tasks
- Makes large automation projects manageable
Typical Role Structure
roles/
└── nginx/
├── tasks/
│ └── main.yml
├── handlers/
│ └── main.yml
├── templates/
├── files/
├── vars/
│ └── main.yml
├── defaults/
│ └── main.yml
└── meta/
└── main.yml
Using a Role
---
- hosts: web
roles:
- nginx
Create a Role Skeleton
ansible-galaxy role init nginx
This automatically creates the complete directory structure.
20. Templates (Jinja2)
Templates allow configuration files to be generated dynamically using variables.
Example Template
nginx.conf.j2
server {
listen 80;
server_name {{ domain_name }};
}
Deploy Template
- name: Deploy nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
Variable Example
domain_name: example.com
Generated output:
server {
listen 80;
server_name example.com;
}
Templates are one of the most heavily used features in real-world Ansible deployments.
21. Ansible Vault
Production environments frequently contain sensitive information such as:
- Passwords
- API Keys
- Cloud Credentials
- Database Secrets
- Certificates
Ansible Vault encrypts these values so they can safely reside in source control repositories.
Create an Encrypted File
ansible-vault create secrets.yml
Edit an Existing Vault
ansible-vault edit secrets.yml
Encrypt an Existing File
ansible-vault encrypt secrets.yml
Run a Playbook Using Vault
ansible-playbook site.yml --ask-vault-pass
Using a Vault Password File
ansible-playbook site.yml \
--vault-password-file vault.pass
This is the preferred method for CI/CD pipelines.
22. Rebooting All Machines
A common operational task is rebooting a fleet of servers after:
- Kernel upgrades
- Operating system patches
- Security updates
- Infrastructure maintenance
Using the Reboot Module
---
- hosts: all
become: true
tasks:
- name: Reboot servers
reboot:
Specify Reboot Timeout
---
- hosts: all
become: true
tasks:
- name: Reboot servers
reboot:
reboot_timeout: 600
The playbook waits until the host becomes reachable again before proceeding.
Run Against a Specific Group
---
- hosts: web
tasks:
- reboot:
Run Against the Entire Inventory
ansible-playbook reboot.yml
Run Against a Subset
ansible-playbook reboot.yml --limit web
For large environments, combine reboots with serial execution to avoid restarting every server simultaneously.
---
- hosts: web
serial: 2
tasks:
- reboot:
Use serial when rebooting clusters, application servers, or databases to prevent full-service outages during maintenance windows.
23. Serial Execution (Rolling Updates)
Serial execution allows Ansible to update servers in batches rather than all at once. This is commonly used for rolling updates in production environments to minimize downtime.
Example
---
- hosts: web
serial: 1
tasks:
- name: Update package
apt:
name: nginx
state: latest
Execution Flow
web1 → complete
web2 → complete
web3 → complete
Ideal for application deployments, operating system patching, and service upgrades where availability must be maintained during updates.
24. Dynamic Inventory
Instead of manually maintaining inventory files, Ansible can dynamically discover infrastructure by querying cloud providers and virtualization platforms.
Supported Platforms
- AWS EC2
- Azure Virtual Machines
- Google Cloud Platform (GCP) Instances
- VMware Environments
How It Works
Cloud API
↓
Dynamic Inventory
↓
Ansible
Whenever infrastructure changes, Ansible automatically retrieves the latest host information from the provider, eliminating manual inventory updates.
25. Ansible Galaxy
Ansible Galaxy is the official public repository for reusable Ansible roles and collections.
Install a Role
ansible-galaxy role install geerlingguy.nginx
You can get the installation command from the ansible galaxy documentation. For example, the above command is taken from https://galaxy.ansible.com/ui/standalone/roles/geerlingguy/nginx/
Benefits
- Reuse community-maintained automation
- Reduce development effort
- Adopt proven best practices
- Accelerate infrastructure provisioning
26. Error Handling
Ansible provides structured error handling using the block, rescue, and always keywords.
Example
- block:
- name: risky task
command: something
rescue:
- name: recovery
debug:
msg: failed
always:
- name: cleanup
debug:
msg: cleanup
Programming Equivalent
| Ansible | Programming Equivalent |
|---|---|
| block | try |
| rescue | catch |
| always | finally |
This structure allows playbooks to recover gracefully from failures while ensuring cleanup operations always execute.
27. Project Structure (Recommended)
For maintainable enterprise-grade automation, organize your Ansible projects using a consistent directory structure.
ansible-project/
│
├── inventory/
│ ├── dev
│ ├── test
│ └── prod
│
├── playbooks/
│ ├── deploy.yml
│ ├── reboot.yml
│ └── patch.yml
│
├── roles/
│ ├── nginx
│ ├── mysql
│ └── common
│
├── group_vars/
├── host_vars/
│
├── templates/
├── files/
│
└── ansible.cfg
Benefits
- Improved maintainability
- Clear separation of responsibilities
- Environment-specific configuration management
- Scalability for large infrastructure projects
28. Most Important Commands Cheat Sheet
| Purpose | Command |
|---|---|
| Check version | ansible --version |
| Ping all hosts | ansible all -m ping |
| List inventory | ansible-inventory --list |
| Inventory graph | ansible-inventory --graph |
| Gather facts | ansible all -m setup |
| Run command | ansible all -m command -a "uptime" |
| Execute playbook | ansible-playbook site.yml |
| Dry run | ansible-playbook site.yml --check |
| Limit hosts | ansible-playbook site.yml --limit web |
| Run tags | ansible-playbook site.yml --tags install |
| Verbose mode | ansible-playbook site.yml -vvv |
| Create role | ansible-galaxy role init nginx |
| Reboot hosts | ansible all -m reboot |
| Encrypt secrets | ansible-vault create secrets.yml |
The combination of inventories, playbooks, roles, templates, vaults, and dynamic inventories forms the foundation of real-world Ansible automation at enterprise scale.
No comments:
Post a Comment