Skip to content
devops/architect
06 ansible 01 01 ansible
0/8 read · lab 0/1
STARTUP TO ENTERPRISE
06 / 14 • CONFIGURATION MANAGEMENT

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.

1 Server Rolling 10 hosts AWX + Compliance

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.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

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.

graph LR Control[Control Node] -->|SSH| Inventory[Static/Dynamic Inventory] Inventory --> Target1[Host 1] Inventory --> TargetN[Host N] Control --> Playbook[YAML Playbook] Playbook --> Tasks[Tasks + Modules] Tasks --> Handlers[Handlers on change]

Core Components 06.2

ComponentDescriptionKey File / Command
InventoryList of hosts and groupsinventory.ini or dynamic plugin
PlaybookOrdered list of plays and taskssite.yml
RoleStandardized reusable unitroles/nginx/tasks/main.yml
VariablesPrecedence hierarchygroup_vars/all.yml
VaultEncrypted variablesansible-vault encrypt
HandlersTriggered on changenotify: restart service

WSL Hands-On Lab 06.3

Install • Inventory • Playbook • Role • Vault • Idempotency Test

install ansible
$ sudo apt update && sudo apt install -y ansible-core python3-pip
$ ansible --version
inventory.yml (modern YAML inventory)
all:
  children:
    webservers:
      hosts:
        localhost:
          ansible_connection: local
    dbservers:
      hosts:
        db01:
          ansible_host: 127.0.0.1
playbook.yml
---
- 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
run & vault
$ 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.

roles/webserver/defaults/main.yml
---
# 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
roles/webserver/tasks/main.yml
---
- 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
roles/webserver/handlers/main.yml
---
- name: restart webserver
  ansible.builtin.systemd:
    name: webserver
    state: restarted
    daemon_reload: true
rolling-deploy.yml
---
- 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: absent

Troubleshooting 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.

secure-token.yml
---
- 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.
ansible.cfg
[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
local-recovery-drill.sh
#!/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.conf

30-Day Roadmap 06.6

WEEK 1
Inventory & Playbooks
  • YAML inventory formats
  • Ad-hoc vs playbook
  • Core modules (apt, copy, service)
WEEK 2
Roles & Variables
  • Role directory layout
  • Jinja2 templates
  • Precedence & scope
WEEK 3
Vault, Security, Idempotency
  • ansible-vault workflow
  • become & privilege
  • Writing idempotent tasks
WEEK 4
AWX / Tower + CI
  • 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
---
# 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'"
dynamic-inventory-cli.sh
# 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_webserver

Predict 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.

site.yml
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: app directory exists
      ansible.builtin.file:
        path: /srv/app
        state: directory
        mode: "0755"
shell.yml
- 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
recorded run
# 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.

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ ansible-playbook -i localhost, site.yml | grep 'ok='
Show the lesson's result

The lesson shows:

localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

What result does the lesson show for this command?

$ ansible-playbook -i localhost, site.yml | grep 'ok='
Show the lesson's result

The lesson shows:

localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

What result does the lesson show for this command?

$ ansible-playbook -i localhost, shell.yml | grep 'ok='
Show the lesson's result

The lesson shows:

localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

A playbook that breaks the server on its second run

Output recorded from a real run on ansible-core 2.19.14 installed with pip in a python:3.12-slim Docker container, run from Git Bash on Windows. The playbook targets localhost inside the container (connection: local), so there is no SSH; check_config.py stands in for the app reading its INI file with Python's configparser. Nothing runs on your machine.

Builds on Troubleshooting.

A tuning playbook raised the app's connection limit last night and the app restarted fine. Tonight the same playbook ran again from the nightly schedule, reported failed=0, and this morning the app will not start: it exits while reading /etc/app/app.ini. Nobody changed the playbook or the server in between.

  1. Step 1 of 3: Same playbook, same server, failed=0 both nights, yet the app now refuses its config. What do you look at first?

Design decision

Pushing a config change to 200 web servers: how much at once?

Builds on Real-World Project.

A playbook changes the nginx worker and keepalive settings on 200 web servers behind a load balancer, then reloads nginx. Last quarter a typo in a similar change was pushed to every server at once and took the site down for 20 minutes. The team wants the next change to stop on its own if something is wrong.

Constraints

  • The change must finish within one 2-hour maintenance window
  • The load balancer health check marks a server down after 3 failed checks, 10 seconds apart
  • At least 80 percent of servers must stay in service at all times
  • The playbook runs from AWX, which keeps the job logs
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Run the first command shown in the section “WSL Hands-On Lab”
Run the first command shown in the section “WSL Hands-On Lab”

Ready. Type the command for the current goal.

Check yourself

A team wants to manage hosts over SSH without installing an agent on each host. Which Ansible execution model fits?

Explanation

In 'Architecture & How It Works', the control node connects over SSH, copies and executes modules, then removes temporary files: 'No agents required.' Inventory selects hosts; handlers and encrypted variables do not replace that execution path.

Several changed tasks notify the same handler during a play. With default timing, how many times does it run and when?

Explanation

In 'Troubleshooting', 'Handler never runs' says handlers run once at the end of a play, even if notified multiple times. Notifications do not schedule a separate run after each task.

A fleet rollout must update one host at a time and stop a bad release from spreading after a failed health check. Which pattern does the lesson recommend?

Explanation

In 'Production Role Layout & Rolling-Deploy Recovery', the lesson pairs serial: 1 and max_fail_percentage: 0 with ansible.builtin.uri health checks and a fail-fast rescue rollback. Handlers, defaults, or inventory grouping alone do not implement that recovery pattern.

A task's parameters and return values must be suppressed from terminal logs. Which setting does the lesson use?

Explanation

In 'Run Reporting, Secret Redaction & Local Idempotency Recovery', 'no_log: true' suppresses task arguments and return values from terminal logs. Timing callbacks and dry-run/diff options serve other purposes.

Why is idempotency useful when rerunning a configuration task?

An idempotent task can run again without changing an already-correct target state; the lesson says most modules guarantee idempotency.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 3 sections Not covered Not covered Not covered
Operate Not covered Missing · 2 sections Not covered Not covered
Troubleshoot Not covered Not covered Missing · 1 section Not covered
Automate Not covered Missing · 2 sections Missing · 1 section Not covered
Secure Not covered Not covered Not covered Not covered
Observe Not covered Not covered Not covered Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Not covered Not covered

How this lesson fits each role