Top 15 Ansible Playbooks Used in Production

15 Ansible playbooks used in production with YAML: patching, hardening, secrets, Kubernetes drains, Helm, zero-downtime deploys, backups, ACME TLS and EDA.

Dec 6, 2025 - 11:50
Nov 7, 2026 - 05:15
 0  526
Top 15 Ansible Playbooks Used in Production

The Ansible playbooks most teams run in production cover server bootstrap, OS patching with rolling reboots, security hardening, secrets, container hosts, Kubernetes node maintenance, Helm releases, zero-downtime and blue-green deploys, monitoring and logging agents, database backups, TLS certificates, Windows updates and event-driven remediation. Each one relies on idempotent modules and controlled batches.

This guide gives you the 15 playbooks with working YAML skeletons, the modules each one uses (by fully qualified collection name), and the safety patterns that make them fit for production. It belongs to our infrastructure as code series. Module names and options were checked against docs.ansible.com in November 2026. For where Ansible fits in day-to-day DevOps, read 10 real-world use cases of Ansible first; this page is about the playbooks themselves.

Key takeaways

  • Production playbooks use serial and max_fail_percentage so a bad change stops after one batch instead of reaching every host.
  • Always write module names in full (ansible.builtin.dnf, ansible.posix.firewalld). Several popular modules live in collections, not in ansible-core.
  • Prefer modules over shell and command. When you must run a command, set changed_when and failed_when yourself.
  • Keep secrets out of Git: use Ansible Vault for static values and a secrets manager lookup (for example HashiCorp Vault) for dynamic ones, with no_log: true.
  • Run every change with --check --diff first, lint with ansible-lint, and test roles with Molecule before they touch production.
  • On RHEL, the supported RHEL system roles (redhat.rhel_system_roles) already cover firewall, SELinux, crypto policies, logging, Podman and more.

The 15 playbooks at a glance

#PlaybookMain modules or rolesRun pattern
1Server bootstrapansible.builtin.user, ansible.posix.authorized_key, ansible.builtin.copyOnce per new host, then on drift
2OS patching with rolling rebootansible.builtin.dnf, ansible.builtin.rebootScheduled, serial batches
3Security hardeningredhat.rhel_system_roles (selinux, firewall, crypto_policies), ansible.posix.sysctlScheduled, check mode for audits
4Secrets distributioncommunity.hashi_vault.vault_kv2_get, ansible.builtin.templateOn deploy and rotation
5Container host setupansible.builtin.dnf, containers.podman.podman_containerPer host
6Kubernetes node maintenancekubernetes.core.k8s_drainserial: 1
7Helm release deploykubernetes.core.helmFrom CI, localhost
8Zero-downtime rolling deploycommunity.general.haproxy, ansible.builtin.uriserial: 1 or small batches
9Blue-green switchansible.builtin.template with validate, handlersrun_once on load balancers
10Monitoring agent rolloutansible.builtin.unarchive, ansible.builtin.systemd_serviceFleet-wide
11Central log forwardingredhat.rhel_system_roles.loggingFleet-wide
12Database backup and restore testcommunity.postgresql.postgresql_dbNightly, restore test weekly
13TLS certificates with ACMEcommunity.crypto.acme_certificate, openssl_privatekey, openssl_csrDaily, renews when due
14Windows Server updatesansible.windows.win_updatesMaintenance window, batches
15Event-driven self-healingansible-rulebook, eda.builtin.webhook, run_playbookTriggered by alerts

Patterns every production playbook shares

The playbooks below differ in purpose, but the same handful of controls separate a lab script from something you can run against hundreds of servers.

  • Batches. serial accepts a number, a percentage or a list such as [1, 5, "25%"], so the first batch acts as a canary. Ansible finishes the whole play on one batch before it starts the next.
  • Failure limits. max_fail_percentage stops the run when too many hosts in a batch fail; any_errors_fatal: true stops on the first failure.
  • Rollback paths. block, rescue and always let you undo a half-applied change and still put a node back into the load balancer.
  • Dry runs. ansible-playbook site.yml --check --diff shows what would change. Modules that cannot predict their result should be marked with check_mode: false or skipped in check mode.
  • Handlers. Restart a service only when its configuration changed, and use validate on templates so a broken config never replaces a working one.
  • Concurrency control. throttle limits a single heavy task, and run_once with delegate_to runs a step on one host for the whole batch.
  • Testing. ansible-lint catches style and risky patterns; Molecule runs roles against throwaway containers or VMs in CI.

More of these habits are collected in 12 Ansible playbook tips for error-free execution.

The 15 playbooks

1. Server bootstrap

Every new VM or bare-metal host gets the same baseline: an operations user with SSH keys, sudo rules, basic packages and time sync. Running it again later fixes drift, because every task is idempotent.

- name: Bootstrap new servers
  hosts: new_servers
  become: true
  tasks:
    - name: Create ops user
      ansible.builtin.user:
        name: ops
        groups: wheel
        append: true
        shell: /bin/bash

    - name: Install SSH public key
      ansible.posix.authorized_key:
        user: ops
        key: "{{ lookup('ansible.builtin.file', 'files/ops.pub') }}"

    - name: Passwordless sudo for ops, checked before it is written
      ansible.builtin.copy:
        dest: /etc/sudoers.d/ops
        content: "ops ALL=(ALL) NOPASSWD: ALL\n"
        mode: "0440"
        validate: visudo -cf %s

    - name: Baseline packages
      ansible.builtin.dnf:
        name: [chrony, vim-enhanced, tar, rsync]
        state: present

    - name: Time sync running
      ansible.builtin.systemd_service:
        name: chronyd
        state: started
        enabled: true

Note that authorized_key is in the ansible.posix collection. On cloud images, cloud-init often creates the first user; Ansible then takes over the rest of the baseline.

2. OS patching with rolling reboots

Patching is the playbook most teams run most often. It updates a quarter of the fleet at a time, reboots only hosts that need it, and stops if more than 10% of a batch fails.

- name: Monthly security patching
  hosts: rhel_servers
  become: true
  serial: "25%"
  max_fail_percentage: 10
  tasks:
    - name: Apply security updates only
      ansible.builtin.dnf:
        name: "*"
        state: latest
        security: true

    - name: Check whether a reboot is needed
      ansible.builtin.command: dnf needs-restarting -r
      register: reboot_check
      changed_when: false
      failed_when: reboot_check.rc not in [0, 1]

    - name: Reboot when required
      ansible.builtin.reboot:
        reboot_timeout: 900
      when: reboot_check.rc == 1

dnf needs-restarting -r returns 1 when a reboot is recommended, so the playbook treats 0 and 1 as success. For clusters, patch replicas before primaries by putting them in separate plays.

3. Security hardening

Hardening playbooks apply a baseline such as CIS or DISA STIG and are rerun to correct drift. On RHEL, start with the RHEL system roles that Red Hat supports, then add your own tasks for anything they do not cover.

- name: Harden RHEL hosts
  hosts: rhel_servers
  become: true
  vars:
    selinux_state: enforcing
    selinux_policy: targeted
    crypto_policies_policy: DEFAULT
    firewall:
      - service: ssh
        state: enabled
      - service: cockpit
        state: disabled
  roles:
    - redhat.rhel_system_roles.selinux
    - redhat.rhel_system_roles.crypto_policies
    - redhat.rhel_system_roles.firewall
  tasks:
    - name: Ignore ICMP redirects
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.accept_redirects
        value: "0"
        sysctl_set: true

    - name: Disable SSH password logins with a drop-in file
      ansible.builtin.copy:
        dest: /etc/ssh/sshd_config.d/50-hardening.conf
        content: |
          PasswordAuthentication no
          PermitRootLogin no
        mode: "0600"
        validate: /usr/sbin/sshd -t -f %s
      notify: Reload sshd
  handlers:
    - name: Reload sshd
      ansible.builtin.systemd_service:
        name: sshd
        state: reloaded

Run it with --check --diff as a compliance report, and use OpenSCAP scans to measure the result against a published profile. Our RHEL 10 hardening guide explains the settings behind each task.

4. Secrets distribution and rotation

Never commit plain secrets. Static values can sit in files encrypted with ansible-vault. Credentials that rotate belong in a secrets manager, read at run time:

- name: Render app config with secrets from HashiCorp Vault
  hosts: app_servers
  become: true
  vars:
    db_secret: "{{ lookup('community.hashi_vault.vault_kv2_get', 'myapp/db', engine_mount_point='secret') }}"
  tasks:
    - name: Write config file
      ansible.builtin.template:
        src: app.env.j2
        dest: /etc/myapp/app.env
        owner: myapp
        mode: "0600"
      no_log: true
      notify: Restart myapp
  handlers:
    - name: Restart myapp
      ansible.builtin.systemd_service:
        name: myapp
        state: restarted

Inside the template, use {{ db_secret.secret.password }}. The Vault address and auth method come from lookup options or the environment variables documented for the collection. no_log: true keeps the rendered values out of logs and CI output. Compare approaches in storing secrets in Ansible and Terraform projects.

5. Container host setup

This playbook prepares a host to run containers and starts a service container. On RHEL the default engine is Podman.

- name: Prepare container hosts
  hosts: container_hosts
  become: true
  tasks:
    - name: Install Podman
      ansible.builtin.dnf:
        name: podman
        state: present

    - name: Run the API container
      containers.podman.podman_container:
        name: api
        image: registry.example.com/team/api:1.4.2
        state: started
        ports:
          - "8080:8080"
        restart_policy: always

Pin image tags (or digests) instead of latest so every host runs the same build. The containers.podman collection also has podman_quadlet for systemd-managed containers, and redhat.rhel_system_roles.podman wraps the same idea in a supported role. For Docker hosts, the community.docker collection plays the same part.

6. Kubernetes node maintenance

Kernel patches and kubelet upgrades need each node drained first. With serial: 1 only one node is out of service at a time.

- name: Patch Kubernetes worker nodes one by one
  hosts: k8s_workers
  become: true
  serial: 1
  tasks:
    - name: Drain node
      kubernetes.core.k8s_drain:
        name: "{{ inventory_hostname }}"
        state: drain
        delete_options:
          ignore_daemonsets: true
          delete_emptydir_data: true
      delegate_to: localhost
      become: false

    - name: Update packages
      ansible.builtin.dnf:
        name: "*"
        state: latest

    - name: Reboot
      ansible.builtin.reboot:

    - name: Return node to service
      kubernetes.core.k8s_drain:
        name: "{{ inventory_hostname }}"
        state: uncordon
      delegate_to: localhost
      become: false

Drain respects PodDisruptionBudgets, so a service with too few replicas will block the drain instead of going down. That is the behaviour you want; fix the replica count rather than forcing the drain.

7. Helm release deploy

Many teams use Ansible as the glue that deploys Helm charts with values per environment, often from a CI job:

- name: Deploy monitoring stack with Helm
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Install or upgrade the release
      kubernetes.core.helm:
        name: monitoring
        chart_ref: prometheus-community/kube-prometheus-stack
        chart_version: "{{ chart_version }}"
        release_namespace: monitoring
        create_namespace: true
        wait: true
        values: "{{ lookup('ansible.builtin.file', 'values/' + env + '.yml') | from_yaml }}"

Add the chart repository first with kubernetes.core.helm_repository, and pin chart_version. If you already run a GitOps tool such as Argo CD, let it own the release and use Ansible only for the cluster plumbing around it.

8. Zero-downtime rolling deploy

The classic web deploy takes one server out of the load balancer, upgrades it, checks it, and puts it back before moving on.

- name: Rolling deploy behind HAProxy
  hosts: web
  become: true
  serial: 1
  max_fail_percentage: 0
  tasks:
    - name: Drain this server on every load balancer
      community.general.haproxy:
        state: disabled
        backend: app
        host: "{{ inventory_hostname }}"
        socket: /var/lib/haproxy/stats
        drain: true
        wait: true
      delegate_to: "{{ item }}"
      loop: "{{ groups['lb'] }}"

    - block:
        - name: Deploy new release
          ansible.builtin.unarchive:
            src: "releases/app-{{ app_version }}.tar.gz"
            dest: /opt/app
          notify: Restart app

        - name: Restart now so the health check tests the new code
          ansible.builtin.meta: flush_handlers

        - name: Wait for health endpoint
          ansible.builtin.uri:
            url: "http://{{ inventory_hostname }}:8080/healthz"
            status_code: 200
          register: health
          retries: 20
          delay: 3
          until: health.status == 200
      always:
        - name: Put server back in rotation
          community.general.haproxy:
            state: enabled
            backend: app
            host: "{{ inventory_hostname }}"
            socket: /var/lib/haproxy/stats
            wait: true
          delegate_to: "{{ item }}"
          loop: "{{ groups['lb'] }}"
          when: health is succeeded
  handlers:
    - name: Restart app
      ansible.builtin.systemd_service:
        name: app
        state: restarted

If the health check fails, the server stays out of rotation and max_fail_percentage: 0 stops the run, so only one node is affected. The socket path must match the stats socket line in your HAProxy configuration.

9. Blue-green switch

With two full environments, the switch is a small, reversible change on the load balancer. Rendering the config from a variable makes rollback a one-word change.

- name: Switch traffic to the green environment
  hosts: lb
  become: true
  vars:
    active_color: green
  tasks:
    - name: Render HAProxy config pointing at the active pool
      ansible.builtin.template:
        src: haproxy.cfg.j2
        dest: /etc/haproxy/haproxy.cfg
        validate: haproxy -c -f %s
      notify: Reload haproxy
  handlers:
    - name: Reload haproxy
      ansible.builtin.systemd_service:
        name: haproxy
        state: reloaded

Run the smoke tests against green before the switch, and keep blue running until you are confident. Rolling back means rerunning with -e active_color=blue.

10. Monitoring agent rollout

Installing an exporter or agent across the fleet is a good first production playbook because it is low risk and easy to verify. This example installs Prometheus node_exporter from the upstream release archive:

- name: Install node_exporter
  hosts: all
  become: true
  vars:
    ne_version: "{{ node_exporter_version }}"
  tasks:
    - name: Create service user
      ansible.builtin.user:
        name: node_exporter
        system: true
        shell: /sbin/nologin

    - name: Download and unpack release
      ansible.builtin.unarchive:
        src: "https://github.com/prometheus/node_exporter/releases/download/v{{ ne_version }}/node_exporter-{{ ne_version }}.linux-amd64.tar.gz"
        dest: /opt
        remote_src: true
        creates: "/opt/node_exporter-{{ ne_version }}.linux-amd64/node_exporter"

    - name: Install systemd unit
      ansible.builtin.template:
        src: node_exporter.service.j2
        dest: /etc/systemd/system/node_exporter.service
      notify: Restart node_exporter

    - name: Open port 9100 to the monitoring network only
      ansible.posix.firewalld:
        rich_rule: 'rule family="ipv4" source address="10.10.0.0/24" port port="9100" protocol="tcp" accept'
        permanent: true
        immediate: true
        state: enabled
  handlers:
    - name: Restart node_exporter
      ansible.builtin.systemd_service:
        name: node_exporter
        state: restarted
        enabled: true
        daemon_reload: true

Check the release checksum in production, either with the checksum option of ansible.builtin.get_url or by mirroring the archive internally.

11. Central log forwarding

Shipping system logs to a central collector is another fleet-wide baseline. On RHEL, the logging system role configures rsyslog from a short set of variables:

- name: Forward system logs to the central collector
  hosts: rhel_servers
  become: true
  vars:
    logging_inputs:
      - name: system_input
        type: basics
    logging_outputs:
      - name: central
        type: forwards
        target: logs.example.com
        tcp_port: 601
    logging_flows:
      - name: to_central
        inputs: [system_input]
        outputs: [central]
  roles:
    - redhat.rhel_system_roles.logging

If you ship to Elasticsearch, Loki or a cloud service through an agent such as Fluent Bit, the same structure works with a package task, a template for the agent config and a handler.

12. Database backup and restore test

Backups only count if they restore. This playbook dumps PostgreSQL databases nightly and a second play restores the latest dump into a scratch database to prove it works.

- name: Nightly PostgreSQL dumps
  hosts: db_primary
  become: true
  become_user: postgres
  tasks:
    - name: Dump each database (compression chosen by the file extension)
      community.postgresql.postgresql_db:
        name: "{{ item }}"
        state: dump
        target: "/backup/{{ item }}-{{ ansible_facts['date_time']['date'] }}.sql.gz"
      loop: "{{ databases }}"

- name: Weekly restore test
  hosts: db_restore_test
  become: true
  become_user: postgres
  tasks:
    - name: Create scratch database
      community.postgresql.postgresql_db:
        name: restore_check
        state: present

    - name: Restore latest dump
      community.postgresql.postgresql_db:
        name: restore_check
        state: restore
        target: "{{ latest_dump }}"

Copy dumps off the database host (to object storage or a backup server) in a separate task, and alert when the restore test fails. Choosing between .gz and .xz dumps is a trade-off between dump speed and storage size.

13. TLS certificates with ACME (Let's Encrypt)

The community.crypto collection can request and renew certificates from any ACME CA. acme_certificate runs twice: once to get the challenge, and again after you publish it.

- name: Issue or renew certificate
  hosts: web
  become: true
  vars:
    domain: www.example.com
  tasks:
    - name: Private key
      community.crypto.openssl_privatekey:
        path: "/etc/pki/tls/private/{{ domain }}.key"

    - name: CSR
      community.crypto.openssl_csr:
        path: "/etc/pki/tls/{{ domain }}.csr"
        privatekey_path: "/etc/pki/tls/private/{{ domain }}.key"
        common_name: "{{ domain }}"

    - name: Request challenge
      community.crypto.acme_certificate:
        acme_directory: https://acme-v02.api.letsencrypt.org/directory
        acme_version: 2
        account_key_src: /etc/pki/acme/account.key
        csr: "/etc/pki/tls/{{ domain }}.csr"
        fullchain_dest: "/etc/pki/tls/certs/{{ domain }}.crt"
        challenge: http-01
        remaining_days: 30
      register: acme

    - name: Publish http-01 challenge file
      ansible.builtin.copy:
        dest: "/var/www/html/{{ acme.challenge_data[domain]['http-01'].resource }}"
        content: "{{ acme.challenge_data[domain]['http-01'].resource_value }}"
      when: acme is changed

    - name: Complete challenge and fetch certificate
      community.crypto.acme_certificate:
        acme_directory: https://acme-v02.api.letsencrypt.org/directory
        acme_version: 2
        account_key_src: /etc/pki/acme/account.key
        csr: "/etc/pki/tls/{{ domain }}.csr"
        fullchain_dest: "/etc/pki/tls/certs/{{ domain }}.crt"
        challenge: http-01
        remaining_days: 30
        data: "{{ acme }}"
      when: acme is changed
      notify: Reload web server

The module's default acme_directory is the Let's Encrypt staging server, so test there and set the production URL only when the flow works. Define the Reload web server handler for nginx or httpd.

14. Windows Server updates

Ansible manages Windows over WinRM or SSH with the ansible.windows collection. Patching follows the same batch pattern as Linux:

- name: Patch Windows servers
  hosts: windows
  serial: 2
  max_fail_percentage: 0
  tasks:
    - name: Install security and critical updates, reboot if needed
      ansible.windows.win_updates:
        category_names:
          - SecurityUpdates
          - CriticalUpdates
        reboot: true
      register: wu

    - name: Show what was installed
      ansible.builtin.debug:
        var: wu.installed_update_count

Other common Windows tasks use win_feature for roles such as IIS, win_service, and win_reboot when a separate reboot step is clearer.

15. Event-driven self-healing

Event-Driven Ansible runs a playbook when an event arrives, for example an alert that a service is down. ansible-rulebook listens on a source and matches conditions:

# rulebook.yml
- name: Restart failed services
  hosts: all
  sources:
    - eda.builtin.webhook:
        host: 0.0.0.0
        port: 5000
  rules:
    - name: Service down alert
      condition: event.payload.alertname == "ServiceDown"
      action:
        run_playbook:
          name: playbooks/restart_service.yml

Your monitoring system (for example Prometheus Alertmanager) posts alerts to the webhook, and the playbook restarts the service on the affected host and records what it did. The ansible.eda collection adds more sources, including ansible.eda.alertmanager and Kafka. Keep automated fixes narrow and safe to repeat, cap how often they can fire, and page a human when the same alert returns.

How to organise these playbooks in a repository

Keep each playbook thin and put the logic in roles, so the same role can be tested alone and reused across playbooks.

ansible/
  ansible.cfg
  collections/requirements.yml     # pinned collection versions
  inventories/
    production/hosts.yml
    production/group_vars/
    staging/hosts.yml
  roles/
    baseline/
    patching/
    app_deploy/
  playbooks/
    bootstrap.yml
    patch.yml
    deploy.yml
  rulebooks/
    self_heal.yml

Install collections with ansible-galaxy collection install -r collections/requirements.yml so every engineer and every CI runner uses the same versions. Run playbooks from CI or from an automation controller rather than from laptops, so every run is logged. For a step-by-step introduction to playbook structure, see automating server configuration with Ansible playbooks.

Common mistakes that break production runs

MistakeWhat happensFix
No serial on disruptive playsEvery host restarts at onceUse percentages or a canary list
shell without changed_whenAlways reports changed; handlers fire every runUse a module, or define changed_when
Short module namesWrong module picked or collection missingUse FQCNs and pin collections
Secrets in vars files or logsCredentials leak through Git or CI outputAnsible Vault, a secrets lookup, no_log: true
Templates without validateA typo takes down sshd, sudo or HAProxyValidate with sshd -t, visudo -c, haproxy -c
Unpinned images, charts or packagesHosts drift to different versionsPin versions and change them through review

Frequently asked questions

What makes an Ansible playbook production ready?

It is idempotent, uses modules instead of raw commands, runs in controlled batches with failure limits, validates config files before replacing them, keeps secrets out of logs, and has been tested with check mode, ansible-lint and Molecule before it reaches production.

How do I do a zero-downtime deployment with Ansible?

Use serial: 1 or small batches, remove each host from the load balancer (for example with community.general.haproxy), deploy, wait for a health check with ansible.builtin.uri, then add the host back. Set max_fail_percentage: 0 so a failed host stops the rollout.

Why should I use fully qualified collection names?

Many modules moved out of ansible-core into collections. FQCNs such as ansible.posix.authorized_key make it clear which collection a task needs, avoid name clashes, and are what ansible-lint expects.

How do I keep secrets safe in Ansible playbooks?

Encrypt static secrets with ansible-vault, read dynamic ones from a secrets manager such as HashiCorp Vault with community.hashi_vault.vault_kv2_get, and add no_log: true to tasks that handle them.

Can Ansible patch servers without downtime?

It can patch without a full outage. Batch the hosts with serial, drain each one from load balancers or Kubernetes first, reboot only when dnf needs-restarting -r says so, and check health before moving to the next batch.

Should I use Ansible or Terraform for these tasks?

Use Terraform or another provisioning tool to create cloud resources, and Ansible to configure what runs on them. Most of the playbooks here, such as patching, hardening and deploys, are configuration work where Ansible fits best.

What is Event-Driven Ansible?

It is the part of Ansible that reacts to events. ansible-rulebook listens to sources such as webhooks, Kafka or Alertmanager and runs a playbook or job template when a rule's condition matches.

Do I need RHEL system roles to use these playbooks?

No. They are a convenient, supported option on RHEL for areas such as firewall, SELinux and logging. On other distributions you can write the same tasks with core modules or use community roles.

Practise these playbooks

Our Ansible training builds several of these playbooks in hands-on labs, in Kharadi, Pune or live online. Ansible is also the subject of the RHCE exam; see RHCE on RHEL 10: syllabus and preparation tips. When you are ready for interviews, work through 80+ Ansible interview questions and answers.

References

What's Your Reaction?

Like Like 1
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.