The order in which Ansible applies roles is not a matter of taste. It determines what manages to break before you notice: an application started before the ports get closed listens on an extra port for a minute; a database left without a firewall meets the next deploy step exposed to the world.

The product's basic playbook

Three roles, and in this order — always:

- hosts: prod
  become: true
  roles:
    - role: hardening      # close the excess first
    - role: docker         # then the runtime
    - role: app            # and only then the application
  any_errors_fatal: true

Three rules of ordering

  • Hardening always goes first. The application must not start listening on extra ports before the firewall closes them. The reverse order is a window of several minutes when the service already runs but the protection doesn't yet.
  • The same order in every environment. If roles run differently in dev, you'll debug the production incident twice: first in prod, then in dev, where it reproduces differently.
  • any_errors_fatal in production. A halted deploy is easier to fix than a half-updated cluster: half the nodes on the new version means two configurations at once and one long evening.

Rolling out: not all nodes at once

serial splits the deploy into batches: if something breaks, one batch breaks, not all of production:

- hosts: prod
  serial:
    - 1          # the first node - the canary
    - "25%"      # then - in batches
  max_fail_percentage: 0   # any error stops the rollout
  roles:
    - { role: app, tags: [deploy] }

The first batch of one node is a canary deploy without extra infrastructure: the node pool's metrics will tell you whether to continue or roll back.

Checks before production

  • --check — a dry run. The order of roles shows up in a dry run as clearly as its mistakes do:
ansible-playbook site.yml --check --diff --limit prod-spb-1
  • --diff shows what exactly will change: an empty diff on a "big" changeset is as much a reason to worry as a huge one.
  • Molecule — tests for roles. A role that changes the firewall must verify that afterwards the right ports are closed and the needed ones are open. Molecule runs the role in a container and checks the final asserts — CI level for infrastructure:
# molecule/default/verify.yml
- name: Closed ports are unreachable
  ansible.builtin.wait_for:
    host: "{{ ansible_host }}"
    port: 22
    state: started
    timeout: 3
  failed_when: false
  register: r
- assert:
    that: r is failed

Secrets: not in plaintext

# encrypting the secrets file
ansible-vault encrypt group_vars/prod/vault.yml

# using it in a pipeline
ansible-playbook site.yml --vault-password-file ~/.vault-pass

The vault password lives in CI secrets or a secret manager, not in the repository next to the encrypted file — otherwise encryption turns into a ritual.

Role hygiene

PracticeWhy
A role does one thing"database + firewall + monitoring" in one role = impossible to reuse in parts
Idempotency is mandatorya re-run changes nothing; verified by a second run in CI
handlers for restartsa service restarts only if the config actually changed
tags for targeted runs--tags deploy must not touch hardening

Ansible forgives almost everything except one thing: you must know the state of all nodes after a run. Role order, serial and any_errors_fatal are not paranoia but the way to guarantee "known".

Rollout strategies: when serial, when free

For playbooks with services that can't all be stopped at once:

- hosts: app-pool
  strategy: free          # nodes don't wait for each other - faster on large pools
  serial: "20%"           # but in batches - the blast radius is limited
  max_fail_percentage: 20 # one node in a batch may die - we stay honest
ParameterWhat it givesWhen it doesn't fit
serial: 1a strict canarya large fleet — the rollout takes hours
max_fail_percentage > 0resilience to "one weird node"production databases — any hit there is critical
strategy: freeevery node moves at its own pacetasks with shared constraints (API rate limits)

A good production default: serial: 1 → 25% + max_fail_percentage: 0 — soften only after the pipeline has proven the role's stability.

pre_tasks and post_tasks: the frame around roles

- hosts: prod
  roles:
    - role: app
  pre_tasks:
    - name: snapshot the state before changes
      ansible.builtin.command: "/usr/local/bin/config-snapshot pre-{{ lookup('pipe','date +%s') }}"
  post_tasks:
    - name: health-check after the deploy
      ansible.builtin.uri:
        url: "http://{{ inventory_hostname }}/health"
        status_code: 200
      retries: 5
      delay: 10
      delegate_to: "{{ inventory_hostname }}"

The point of the frame: if a post task fails, the run doesn't count as "successful", even if all roles completed. That's the difference between "we deployed" and "we deployed and the service works".

How to maintain 30+ roles without pain

  • requirements.yml for external ones, your own roles — one per repository or a monorepo with stable tags: a versioned requirements.yml is the infrastructure's lock file.
  • CI for every role: lint + molecule in the MR pipeline — a role without green CI doesn't get into requirements.
  • Semver for roles: a breaking change in the role's interface (required variables, default behavior) is a major, which consumers upgrade to deliberately.
  • A role's README is its contract: the variable list, examples, and what the role does NOT do. Half of "the role broke production" incidents are the role being used against its contract.