Online courses

Free courses, labs and MOOCs, with your progress saved.

Terraform & Ansible — The course

Guide 09 / 3

Ansible configuration and business cases

Understand the project's files, the modules and seven ready-to-use automation scenarios.

Expected outcome :

Adapt an Ansible project for Linux servers, Nginx, SSH, Docker Compose and Kubernetes.

Reading
0%

01 · Reading the structure of an Ansible project

A maintainable project separates targets, general configuration, variables, scripts and templates.

Recommended folder layout

Separate inventory, playbooks, templates, files, roles and requirements.yml to tell targeting apart from operations.

ansible.cfg
inventory.ini
site.yml
group_vars/web.yml
templates/site.conf.j2
roles/

ansible.cfg

The project's local run configuration. The inventory field avoids repeating -i; the other settings must be adapted.

[defaults]
inventory = inventory.ini
host_key_checking = True
Remember :

Do not disable SSH verification or warnings for convenience.

inventory.ini

Describes the real or virtual servers to be managed and splits them into groups.

[web]
web1 ansible_host=192.0.2.11
web2 ansible_host=192.0.2.12
[web:vars]
ansible_user=deployer

group_vars/web.yml

Values shared by the web servers of a group.

site_hostname: demo.example.test
http_port: 80

requirements.yml

Declares the external collections needed to reproduce the project on another machine.

collections:
  - name: community.docker
  - name: kubernetes.core

02 · YAML keys and execution

Playbook files follow a hierarchy: play → tasks → module and arguments.

hosts

Selects the hosts targeted by the play according to the inventory.

- hosts: web
Remember :

This key defines the scope: check the targets before any run.

name

Gives a task or play a readable title and makes logs and diagnostics easier.

- name: Configurer nginx

become / become_user

Lets you run tasks with another account's permissions, often root via sudo.

become: true
become_user: root

tasks / handlers

tasks holds the operations to perform; handlers the operations triggered only after a change.

notify: Recharger nginx

vars / vars_files

Defines variables directly in the play or loads a variables file.

vars:
  http_port: 8080

when

An execution condition evaluated for each host.

when: ansible_facts["os_family"] == "Debian"

loop

Iterates over a list and exposes each element in item.

loop:
  - curl
  - git

register

Records a module's response and lets you test changed, failed or stdout.

register: resultat

notify

Requests the deferred execution of a handler if the notifying task changed something.

notify: Recharger nginx

serial

Limits the number of hosts processed simultaneously within a play.

serial: 1

check_mode / changed_when

Adjusts the behaviour of check mode or the detection of change in specific cases.

changed_when: false pour une commande d’observation
Remember :

Avoid arbitrarily masking changes or failures.

no_log

Prevents the usual display of a task's sensitive parameters and results.

no_log: true
Remember :

Do not confuse hiding logs with encrypting secrets.

03 · Essential modules for business cases

Each module meets a specific business need and has documented parameters. The examples assume Debian/Ubuntu Linux unless stated otherwise.

ansible.builtin.apt

Manages Debian/Ubuntu packages according to the desired state.

ansible.builtin.apt:
  name: nginx
  state: present
  update_cache: true

ansible.builtin.package

A generic package-management interface; delegates to an underlying manager.

ansible.builtin.package:
  name: curl
  state: present

ansible.builtin.file

Manages folders, permissions, links and path deletions.

ansible.builtin.file:
  path: /opt/monapp
  state: directory
  mode: "0755"

ansible.builtin.copy

Transfers a static file or creates a file via content.

ansible.builtin.copy:
  src: files/index.html
  dest: /var/www/html/index.html

ansible.builtin.template

Renders a Jinja2 template on the target, with variables and possibly a validation command.

ansible.builtin.template:
  src: templates/site.conf.j2
  dest: /etc/nginx/sites-available/site
  backup: true
Remember :

After rendering, run nginx -t before reloading the service; backup: true keeps the previous version.

ansible.builtin.service

Ensures a service is started, stopped or enabled at boot.

ansible.builtin.service:
  name: nginx
  state: started
  enabled: true

ansible.builtin.user

Creates and configures Unix accounts according to the defined parameters.

ansible.builtin.user:
  name: deploiement
  state: present

ansible.posix.authorized_key

Manages an authorised SSH public key for a remote account.

ansible.posix.authorized_key:
  user: deploiement
  key: "{{ lookup('file', 'files/deploiement.pub') }}"
Remember :

This module belongs to ansible.posix: install the matching collection.

community.docker.docker_compose_v2

Drives the services of a Compose folder via the Docker Compose V2 plugin available on the host.

community.docker.docker_compose_v2:
  project_src: /opt/portail
  state: present
Remember :

Requires the community.docker collection, Docker and the Compose plugin on the targeted machine.

kubernetes.core.k8s

Creates, updates or deletes Kubernetes resources via the API.

kubernetes.core.k8s:
  state: present
  definition: "{{ lookup('file', 'manifests/web.yaml') | from_yaml }}"
Remember :

Requires the collection, the Python dependencies and an authorised kubeconfig.

04 · Going-live method

An Ansible business case comes with a method for checking, rolling back and verifying the service.

Before the change

Take stock of the inventory, check the rights, version the playbook and back up the important files.

ansible-playbook -i inventory.ini site.yml --list-hosts

Syntax check

Validate the YAML structure and the module references.

ansible-playbook -i inventory.ini site.yml --syntax-check

Simulation

Estimate the changes and check the differences on a lab host.

ansible-playbook -i inventory.ini site.yml --limit web1 --check --diff
Remember :

A module may not announce all its actions in check mode.

Gradual deployment

Do a first deployment on a pilot host before extending to the others.

ansible-playbook -i inventory.ini site.yml --limit web1

Business check

Test the functional result in addition to Ansible's recap.

curl -I http://192.0.2.11/
Remember :

An “ok” task does not prove the application is available.

Rollback

Plan for a return to a known configuration, to a previous image version and to backups.

git checkout <revision> puis relance contrôlée du playbook
Remember :

Rolling back code and restoring data are two different operations.

05 · Business case A — Preparing a fleet of Linux servers

NEED: A SysOps administrator wants to prepare several Ubuntu VMs with the same tools, rights and a base folder structure.
PREREQUISITES: You need SSH access, an account able to use sudo and reachable APT repositories.

Implementation · playbook 01-preparer-serveurs.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Preparations communes des serveurs Ubuntu
  hosts: web
  become: true
  gather_facts: true
  tasks:
    - name: Verifier le systeme d'exploitation
      ansible.builtin.assert:
        that:
          - ansible_facts['os_family'] == 'Debian'
        fail_msg: "Ce cas vise Debian et Ubuntu."
    - name: Mettre a jour le cache des paquets
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 3600
    - name: Installer les outils d'exploitation
      ansible.builtin.apt:
        name: [curl, git, htop, ca-certificates]
        state: present
    - name: Creer un dossier applicatif
      ansible.builtin.file:
        path: /opt/portail
        state: directory
        mode: '0755'
Remember :

To check: Validation: apt list --installed, presence of /opt/portail. Limit: does not work as is on RHEL.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 01-preparer-serveurs.yml --syntax-check
ansible-playbook -i inventory.ini 01-preparer-serveurs.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 01-preparer-serveurs.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

06 · Business case B — Publishing a reproducible Nginx website

NEED: An operations manager must install Nginx, publish an HTML page and create a virtual host from variables.
PREREQUISITES: Install the apt module, provide files/index.html and templates/site.conf.j2, have suitable DNS or /etc/hosts.

Implementation · playbook 02-deployer-nginx.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Installer et configurer le serveur web
  hosts: web
  become: true
  vars:
    site_hostname: demo.example.test
  tasks:
    - name: Installer nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
    - name: Deployer la page d'accueil
      ansible.builtin.copy:
        src: files/index.html
        dest: /var/www/html/index.html
        owner: root
        group: root
        mode: '0644'
    - name: Generer le virtual host
      ansible.builtin.template:
        src: templates/site.conf.j2
        dest: /etc/nginx/sites-available/demo
        owner: root
        group: root
        mode: '0644'
      notify: Recharger nginx
    - name: Activer le site
      ansible.builtin.file:
        src: /etc/nginx/sites-available/demo
        dest: /etc/nginx/sites-enabled/demo
        state: link
      notify: Recharger nginx
    - name: Valider la configuration nginx
      ansible.builtin.command: nginx -t
      changed_when: false
    - name: Demarrer nginx au boot
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
  handlers:
    - name: Recharger nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
Remember :

To check: Validation: nginx -t then curl -H "Host: demo.example.test" http://SERVER_IP/ ; plan for config validation before reloading in production.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 02-deployer-nginx.yml --syntax-check
ansible-playbook -i inventory.ini 02-deployer-nginx.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 02-deployer-nginx.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

Associated file: 02-site.conf.j2

A complementary resource used by the playbook. Keep the expected name and path, then adapt the values to the lab.

server {
    listen 80;
    server_name {{ site_hostname }};
    root /var/www/html;
    index index.html;
    location / { try_files $uri $uri/ =404; }
}
Remember :

These files are also part of the examples ZIP.

Associated file: 02-index.html

A complementary resource used by the playbook. Keep the expected name and path, then adapt the values to the lab.

<!doctype html>
<html lang="fr"><meta charset="utf-8">
<title>Atelier Ansible</title><h1>Deploiement Ansible OK</h1>
Remember :

These files are also part of the examples ZIP.

07 · Business case C — Managing SSH accounts and access

NEED: An operations team creates a single deployment account and associates an approved public key with it.
PREREQUISITES: Prepare files/deploiement.pub; install ansible.posix from requirements.yml.

Implementation · playbook 03-acces-ssh.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Creer un compte de deploiement
  hosts: web
  become: true
  tasks:
    - name: Creer le compte applicatif
      ansible.builtin.user:
        name: deploiement
        shell: /bin/bash
        create_home: true
        state: present
    - name: Installer sa cle publique
      ansible.posix.authorized_key:
        user: deploiement
        key: "{{ lookup('file', 'files/deploiement.pub') }}"
        state: present
Remember :

To check: Validation: ssh -i KEY_PATH deploiement@IP ; never remove existing access before verifying the new one.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 03-acces-ssh.yml --syntax-check
ansible-playbook -i inventory.ini 03-acces-ssh.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 03-acces-ssh.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

08 · Business case D — Scheduling updates in batches

NEED: An administrator must apply patches to the web servers without interrupting them all at once.
PREREQUISITES: Plan a maintenance window, a backup and at least some remaining application capacity during serial: 1.

Implementation · playbook 04-maintenance.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Maintenir les serveurs successivement
  hosts: web
  become: true
  serial: 1
  tasks:
    - name: Installer les correctifs disponibles
      ansible.builtin.apt:
        update_cache: true
        upgrade: safe
    - name: Detecter un redemarrage demande par Ubuntu
      ansible.builtin.stat:
        path: /var/run/reboot-required
      register: reboot_requis
    - name: Redemarrer uniquement si necessaire
      ansible.builtin.reboot:
        reboot_timeout: 600
      when: reboot_requis.stat.exists
Remember :

To check: Validation: package versions and application availability; the reboot strategy must be adapted to operations.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 04-maintenance.yml --syntax-check
ansible-playbook -i inventory.ini 04-maintenance.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 04-maintenance.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

09 · Business case E — Deploying a Docker Compose application

NEED: A DevOps team reuses its Docker knowledge: Ansible copies the Compose file and ensures the service starts.
PREREQUISITES: Docker Engine, the Compose V2 plugin and community.docker installed on their respective machines.

Implementation · playbook 05-docker-compose.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Deployer une application Docker Compose
  hosts: web
  become: true
  tasks:
    - name: Creer le dossier du projet
      ansible.builtin.file:
        path: /opt/portail
        state: directory
        mode: '0755'
    - name: Publier compose.yaml
      ansible.builtin.copy:
        src: files/compose.yaml
        dest: /opt/portail/compose.yaml
        mode: '0644'
    - name: Lancer la stack Compose
      community.docker.docker_compose_v2:
        project_src: /opt/portail
        state: present
Remember :

To check: Validation: docker compose -f /opt/portail/compose.yaml ps ; HTTP on port 8080 if the network allows it.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 05-docker-compose.yml --syntax-check
ansible-playbook -i inventory.ini 05-docker-compose.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 05-docker-compose.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

Associated file: 05-compose.yaml

A complementary resource used by the playbook. Keep the expected name and path, then adapt the values to the lab.

services:
  web:
    image: nginx:stable-alpine
    ports:
      - "8080:80"
    restart: unless-stopped
Remember :

These files are also part of the examples ZIP.

10 · Business case F — Deploying Kubernetes objects

NEED: A Platform Engineering team uses Ansible to apply a manifest via the Kubernetes API, without a shell kubectl command.
PREREQUISITES: A cluster reachable from the control node, an authorised kubeconfig, the kubernetes.core collection and its Python dependencies.

Implementation · playbook 06-kubernetes.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Publier une ressource sur Kubernetes
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Appliquer le manifeste YAML via l'API
      kubernetes.core.k8s:
        state: present
        definition: "{{ lookup('file', 'manifests/web.yaml') | from_yaml }}"
Remember :

To check: Validation: kubectl get configmap demo-ansible ; never publish secrets in clear text.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 06-kubernetes.yml --syntax-check
ansible-playbook -i inventory.ini 06-kubernetes.yml --check
ansible-playbook -i inventory.ini 06-kubernetes.yml
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.

Associated file: 06-web.yaml

A complementary resource used by the playbook. Keep the expected name and path, then adapt the values to the lab.

apiVersion: v1
kind: ConfigMap
metadata:
  name: demo-ansible
  namespace: default
data:
  MESSAGE: "Configuration geree par Ansible"
Remember :

These files are also part of the examples ZIP.

11 · Business case G — Auditing server compliance

NEED: An IT manager wants to prove that the Nginx service is present and active on a set of nodes.
PREREQUISITES: Nginx installed across the fleet and the rights needed to read the services' state.

Implementation · playbook 07-audit.yml

The playbook below can be copied straight into a YAML file. Identify hosts, the modules called and the expected effects before running.

---
- name: Observer la conformite des serveurs
  hosts: web
  become: true
  tasks:
    - name: Collecter les services
      ansible.builtin.service_facts:
    - name: Verifier que nginx est actif
      ansible.builtin.assert:
        that:
          - "'nginx.service' in ansible_facts.services"
          - "ansible_facts.services['nginx.service'].state == 'running'"
        fail_msg: "Nginx ne fonctionne pas sur cet hote."
    - name: Donner le bilan
      ansible.builtin.debug:
        msg: "Nginx actif sur {{ inventory_hostname }}"
Remember :

To check: Validation: output per host; an audit is a snapshot of the state, not a complete monitoring system.

Command to run

Check the targeting and the syntax, then run only on the machines or the training cluster.

ansible-playbook -i inventory.ini 07-audit.yml --syntax-check
ansible-playbook -i inventory.ini 07-audit.yml --limit web1 --check --diff
ansible-playbook -i inventory.ini 07-audit.yml --limit web1
Remember :

For cases that use localhost or modules that do not simulate everything: adjust the options and confirm the prerequisites. Example D can cause a real reboot.