Ansible
Push-based, agentless automation over SSH. Write idempotent playbooks and roles. Encrypt secrets. Manage fleets from 1 server to hundreds with Tower or AWX.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Advanced Ansible Patterns · Predict the Result: Idempotency in PLAY RECAP
- Why it matters
- A required lesson for Cloud Engineer. Recommended for DevOps Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 6 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 06.1
Ansible control node connects to managed nodes over SSH, copies modules, executes them, then removes temporary files. No agents required. Idempotency is guaranteed by most modules.
Core Components 06.2
| Component | Description | Key File / Command |
|---|---|---|
| Inventory | List of hosts and groups | inventory.ini or dynamic plugin |
| Playbook | Ordered list of plays and tasks | site.yml |
| Role | Standardized reusable unit | roles/nginx/tasks/main.yml |
| Variables | Precedence hierarchy | group_vars/all.yml |
| Vault | Encrypted variables | ansible-vault encrypt |
| Handlers | Triggered on change | notify: restart service |
WSL Hands-On Lab 06.3
Install • Inventory • Playbook • Role • Vault • Idempotency Test
$ sudo apt update && sudo apt install -y ansible-core python3-pip $ ansible --version
all:
children:
webservers:
hosts:
localhost:
ansible_connection: local
dbservers:
hosts:
db01:
ansible_host: 127.0.0.1---
- name: Configure web tier
hosts: webservers
become: true
vars_files:
- group_vars/all/vault.yml
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
- name: Deploy site config
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: reload nginx
handlers:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded$ ansible-playbook -i inventory.yml playbook.yml --check $ mkdir -p group_vars/all $ ansible-vault create group_vars/all/vault.yml $ ansible-playbook -i inventory.yml playbook.yml --ask-vault-pass
- Install ansible-core
- Create YAML inventory with localhost + docker targets
- Write and run idempotent nginx playbook
- Create proper role directory structure
- Encrypt sensitive data with ansible-vault
- Test idempotency twice and verify no changes on second run
Real-World Project 06.4
Single server hardening playbook
users, sshd_config, ufw, fail2ban, unattended upgrades.
3-tier rolling deployment across fleet of 10 servers
serial: 1, pre/post tasks, rolling service restarts, blue/green strategy.
AWX + scheduled patching + Lynis compliance + Windows support
Maintenance windows, credential isolation, job templates, surveys, compliance reporting.
Production Role Layout & Rolling-Deploy Recovery
Simulated multi-node deployment pattern. Assumptions: Ansible Core >= 2.16 / 2.17+, systemd targets with an HTTP health probe. See official Ansible Roles Guide, Ansible Playbook Strategies (serial), and Playbook Error Handling (block, rescue, always). No credentials, paid resources, or live cloud runs required.
Production roles separate configuration defaults (easily overridden in inventory or extra vars), idempotent tasks, and change-triggered handlers. When deploying across server pools, pair serial: 1 with max_fail_percentage: 0, health checks via ansible.builtin.uri, and an automated rescue rollback block that fails fast to prevent bad releases from propagating across the fleet.
---
# Default variables for webserver role (lowest precedence, easily overridden)
webserver_port: 8080
webserver_version: "2.4.1"
webserver_app_dir: "/opt/app"
webserver_releases_dir: "{{ webserver_app_dir }}/releases/{{ webserver_version }}"
webserver_current_symlink: "{{ webserver_app_dir }}/current"
webserver_health_url: "http://127.0.0.1:{{ webserver_port }}/healthz"
webserver_health_status_code: 200
webserver_health_retries: 5
webserver_health_delay: 2---
- name: Ensure target release directory exists
ansible.builtin.file:
path: "{{ webserver_releases_dir }}"
state: directory
mode: "0755"
owner: www-data
group: www-data
- name: Deploy application release archive
ansible.builtin.copy:
src: "app-{{ webserver_version }}.tar.gz"
dest: "{{ webserver_releases_dir }}/app.tar.gz"
mode: "0644"
- name: Update current symlink to new release
ansible.builtin.file:
src: "{{ webserver_releases_dir }}"
dest: "{{ webserver_current_symlink }}"
state: link
notify: restart webserver---
- name: restart webserver
ansible.builtin.systemd:
name: webserver
state: restarted
daemon_reload: true---
- name: Zero-downtime rolling deployment with health check and rescue rollback
hosts: webservers
serial: 1
max_fail_percentage: 0
tasks:
- name: Deploy release batch inside protected block
block:
- name: Drain node from traffic routing
ansible.builtin.file:
path: /etc/nginx/maintenance.flag
state: touch
mode: "0644"
- name: Apply webserver role update
ansible.builtin.include_role:
name: webserver
- name: Flush handlers immediately before running health probe
ansible.builtin.meta: flush_handlers
- name: Verify application endpoint responds with HTTP 200
ansible.builtin.uri:
url: "{{ webserver_health_url }}"
status_code: "{{ webserver_health_status_code }}"
return_content: false
register: health_result
until: health_result.status == webserver_health_status_code
retries: "{{ webserver_health_retries }}"
delay: "{{ webserver_health_delay }}"
rescue:
- name: Health check failed - notify operator
ansible.builtin.debug:
msg: "CRITICAL: Health check failed on {{ inventory_hostname }}. Reverting release symlink."
- name: Roll back symlink to previous release
ansible.builtin.file:
src: "{{ webserver_app_dir }}/releases/previous"
dest: "{{ webserver_current_symlink }}"
state: link
notify: restart webserver
- name: Flush handlers to immediately activate rollback
ansible.builtin.meta: flush_handlers
- name: Fail fast to abort deployment across remaining hosts
ansible.builtin.fail:
msg: "Deployment aborted: {{ inventory_hostname }} failed post-deployment health check."
always:
- name: Restore node into active service pool
ansible.builtin.file:
path: /etc/nginx/maintenance.flag
state: absentTroubleshooting 06.5
SSH authentication or permission issues
Verify ssh keys 600, ansible_user, become_method: sudo, ssh-agent forwarding if using jump hosts.
Handler never runs
Handler name must match notify exactly. Handlers run once at end of play, even if notified multiple times.
Variable precedence surprises
Extra vars > host_vars > group_vars > role defaults. Use -vvv to debug.
Run Reporting, Secret Redaction & Local Idempotency Recovery
Local self-contained exercise. Assumptions: Ansible Core >= 2.16 / 2.17+, ansible.posix collection, local Ubuntu/Debian/WSL environment. See official Ansible Protecting Sensitive Data with no_log and ansible.cfg Configuration Settings. No credentials, external APIs, or destructive host actions.
Automation observability requires tracking execution timing and auditing playbook outcomes without leaking sensitive credentials into logs. no_log: true suppresses task arguments and return values from terminal logs. In ansible.cfg, callbacks like profile_tasks and structured output formatters measure task latencies while routing records to persistent log paths.
---
- name: Secure secret deployment with output redaction
hosts: localhost
connection: local
gather_facts: false
vars_files:
- vault-secrets.yml
tasks:
- name: Write sensitive API token configuration
ansible.builtin.copy:
dest: /tmp/api-token.conf
content: "API_TOKEN={{ vault_secret_token }}\n"
mode: "0600"
no_log: true
# no_log: true suppresses task parameters, diffs, and return values from stdout/stderr.
# If this task fails, Ansible redacts the error payload to prevent credential leakage.
# Caveat: debugging errors requires verifying syntax and vars separately in check mode.[defaults]
# Structured callbacks for execution timing, profiling, and log persistence
callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer, community.general.yaml
stdout_callback = community.general.yaml
bin_ansible_callbacks = true
log_path = /var/log/ansible/ansible.log
retry_files_enabled = false
host_key_checking = true
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false#!/usr/bin/env bash
# Local self-contained idempotency & recovery drill
set -euo pipefail
WORK_DIR=$(mktemp -d /tmp/ansible-drill-XXXXXX)
trap 'rm -rf "${WORK_DIR}"' EXIT
cd "${WORK_DIR}"
cat << 'EOF' > playbook.yml
- name: Idempotent configuration management drill
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Ensure target configuration directory exists
ansible.builtin.file:
path: ./config
state: directory
mode: "0755"
- name: Ensure idempotently managed parameter line is set
ansible.builtin.lineinfile:
path: ./config/app.conf
line: "max_connections=250"
create: true
mode: "0644"
EOF
echo "--- Run 1: Initial configuration ---"
ansible-playbook -i localhost, playbook.yml | grep -E "changed=[0-9]+"
echo "--- Run 2: Verifying idempotency (must report changed=0) ---"
ansible-playbook -i localhost, playbook.yml | grep -E "changed=[0-9]+"
echo "--- Line count verification (must equal 1) ---"
wc -l < ./config/app.conf30-Day Roadmap 06.6
- YAML inventory formats
- Ad-hoc vs playbook
- Core modules (apt, copy, service)
- Role directory layout
- Jinja2 templates
- Precedence & scope
- ansible-vault workflow
- become & privilege
- Writing idempotent tasks
- AWX installation
- Job templates & surveys
- Git integration + schedules
Deep Dive: Advanced Ansible Patterns 06.7
Dynamic Inventory
Use aws_ec2, azure_rm, gcp_compute inventory plugins. Cache results. Tag instances properly so Ansible can select hosts without static lists.
Testing & CI for Playbooks
Use molecule + testinfra or ansible-lint in pipelines. Run ansible-playbook --check --diff in PRs. Never merge untested roles into production playbooks.
Dynamic Cloud Inventory: amazon.aws.aws_ec2 Plugin
Offline specification and validation drill. Assumptions: Ansible Core >= 2.16 / 2.17+, collection amazon.aws >= 7.0.0, Python boto3 >= 1.28.0. See official amazon.aws.aws_ec2 plugin docs and Ansible Dynamic Inventory Guide. No cloud credentials or billing incurred.
Static inventory files fail in dynamic cloud environments. The modern amazon.aws.aws_ec2 plugin dynamically discovers compute instances across specified regions, filters targets by instance state and tags, groups nodes into dynamic groups via keyed_groups, and composes target variables like ansible_host from AWS metadata.
---
# inventory.aws_ec2.yml - Dynamic inventory plugin configuration
# Offline specification; requires collection amazon.aws >= 7.0.0 and boto3.
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
- eu-west-1
# Filter EC2 instances strictly by tags and lifecycle state
filters:
tag:Environment:
- staging
- production
instance-state-name:
- running
# Dynamically construct Ansible groups from EC2 tags
keyed_groups:
# Creates groups such as tag_Environment_production
- prefix: tag_Environment
key: tags.Environment
# Creates groups such as role_webserver
- prefix: role
key: tags.Role
# Set target connection host dynamically
compose:
ansible_host: private_ip_address
ansible_user: "'ubuntu'"# 1. Install required AWS collection offline or from Ansible Galaxy
ansible-galaxy collection install amazon.aws:>=7.0.0
# 2. Offline schema validation: parse and graph discovered hosts (simulated mock)
ansible-inventory -i inventory.aws_ec2.yml --graph
# 3. Export complete inventory in JSON format to inspect constructed hostvars
ansible-inventory -i inventory.aws_ec2.yml --list
# 4. Filter target hosts by keyed group without static host lists
ansible-playbook -i inventory.aws_ec2.yml site.yml --limit role_webserverPredict the Result: Idempotency in PLAY RECAP 06.8
Recorded from a real run of scripts/recordings/ansible.sh; every output below is pasted from scripts/recordings/ansible.out. Cover the output, predict it, then compare.
Environment: python:3.12-slim container with ansible-core 2.17.7, running against localhost with connection: local. ANSIBLE_PYTHON_INTERPRETER=auto_silent hides the interpreter-discovery warning.
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: app directory exists
ansible.builtin.file:
path: /srv/app
state: directory
mode: "0755"- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: append a line with shell
ansible.builtin.shell: echo "max_conn=100" >> /srv/app/app.conf# First run of a playbook that ensures /srv/app exists (ansible.builtin.file) $ ansible-playbook -i localhost, site.yml | grep 'ok=' localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # Second run, nothing changed on the host $ ansible-playbook -i localhost, site.yml | grep 'ok=' localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # First run of a playbook that appends a line with ansible.builtin.shell $ ansible-playbook -i localhost, shell.yml | grep 'ok=' localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # Second run of the shell playbook, then count lines in the file $ ansible-playbook -i localhost, shell.yml | grep 'ok=' && wc -l < /srv/app/app.conf localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 2
The file module compares desired and actual state, so the second run reports changed=0. shell runs every time and appends again: two runs, two lines. Use lineinfile or a template for config, or give shell a creates: or changed_when: condition.