DevOpsCloud

Ansible Automation: Complete Configuration Management Guide

· Pavan Y N · devops, linux, cloud, aws

Ansible is an agentless automation tool for configuration management, application deployment, and orchestration. A control node runs playbooks written in YAML, connects to managed nodes over SSH (or WinRM for Windows), and runs modules that bring each node to the state the playbook describes. EduGeek explains how Ansible is packaged today, how to structure inventory, playbooks, and roles, how to work with collections and secrets, and which older habits to drop. Every playbook in this guide was syntax-checked and linted against ansible-core 2.21 with the production profile of ansible-lint, and the nginx template was rendered and tested with nginx -t.

# What is Ansible?

Ansible pushes changes from a control node to managed nodes. There is no agent or daemon to install on the managed side: a Linux node needs an SSH login and a Python interpreter, while some modules, such as network modules, do not need Python on the device.

## Key features

  • →Agentless: nothing to install on managed nodes beyond Python for most modules.
  • →Readable: playbooks are YAML, so the automation doubles as documentation.
  • →Idempotent: modules compare current state with desired state and change only what differs, so a playbook can run repeatedly. Tasks that run raw commands need help to behave this way, as the troubleshooting section shows.
  • →Extensible: modules, plugins, and roles ship in collections, which are versioned bundles you install separately from Ansible itself.

## Architecture

code
┌──────────────────┐
│  Control node    │  (where Ansible runs)
│  - ansible CLI   │
│  - Playbooks     │
│  - Inventory     │
└────────┬─────────┘
         │ SSH / WinRM
    ┌────┴────┬─────────┬─────────┐
    │         │         │         │
┌───▼───┐ ┌───▼───┐ ┌───▼───┐ ┌───▼───┐
│ Node 1│ │ Node 2│ │ Node 3│ │ Node N│
│(Linux)│ │(Linux)│ │(Win)  │ │ ...   │
└───────┘ └───────┘ └───────┘ └───────┘

The control node must be a UNIX-like machine (Linux, macOS, a BSD) or Windows through the Windows Subsystem for Linux (WSL). Windows without WSL is not supported as a control node.

# Installation and setup

## Choosing and installing a package

The Ansible project publishes two community packages:

  • →ansible-core is the minimal runtime: the language, the CLI tools, and the ansible.builtin collection of core modules and plugins.
  • →ansible is the "batteries included" package: ansible-core plus a community-curated set of collections for clouds, operating systems, and devices.

Install with pipx (or pip in a virtual environment) rather than a distribution package, which is often several releases behind. The Ansible installation guide documents both routes.

code
# Full community package
pipx install --include-deps ansible

# Or the minimal runtime plus only the collections you need
pipx install ansible-core
ansible-galaxy collection install -r requirements.yml

ansible --version

As of October 2026 the current releases are ansible-core 2.21 (generally available in May 2026) and the ansible 14 community package. ansible-core 2.21 supports Python 3.12 through 3.14 on the control node and Python 3.9 through 3.14 on managed nodes. The project maintains the latest three ansible-core releases, so check the support matrix in the release documentation before pinning a version.

Pin the collections your playbooks depend on in requirements.yml:

code
---
collections:
  - name: ansible.posix
  - name: community.general
  - name: amazon.aws
  - name: community.docker

Commit it with the playbooks so every control node and CI runner resolves the same collections. A role or playbook then refers to a module by its fully qualified collection name (FQCN), such as ansible.posix.firewalld or amazon.aws.ec2_instance.

## Initial configuration

ansible.cfg:

code
[defaults]
inventory = ./inventory
remote_user = ansible
private_key_file = ~/.ssh/ansible_key
gathering = smart
fact_caching = jsonfile
fact_caching_connection = ~/.ansible/fact_cache

[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false

[ssh_connection]
pipelining = true

Three settings from older versions of this guide are deliberately absent:

  • →host_key_checking = False is not set. The default is True, and turning it off removes protection against man-in-the-middle attacks. Populate known_hosts instead (see the troubleshooting section).
  • →retry_files_enabled = False is not needed because the default is already False.
  • →ssh_args and control_path are not set. The default ssh_args already enables ControlMaster and ControlPersist=60s.

Pipelining, which cuts the number of SSH operations per task, is off by default. Turn it on as above, but note that it conflicts with sudo configurations that set requiretty, so disable requiretty in /etc/sudoers on managed hosts first. The fact cache lives in the user's home directory rather than the world-writable /tmp.

## Inventory

Static inventory (inventory/hosts.ini):

code
[webservers]
web1.example.com ansible_host=192.168.1.10
web2.example.com ansible_host=192.168.1.11
web3.example.com ansible_host=192.168.1.12

[databases]
db1.example.com ansible_host=192.168.1.20
db2.example.com ansible_host=192.168.1.21

[loadbalancers]
lb1.example.com ansible_host=192.168.1.30

[production:children]
webservers
databases
loadbalancers

[production:vars]
ansible_user=ubuntu
deploy_env=production

The variable is named deploy_env on purpose. Earlier examples used environment, but environment is a playbook keyword, and the Ansible documentation states that Python keywords and playbook keywords are not valid variable names. The same applies to tags, name, hosts, and other keywords.

Dynamic inventory (AWS) with the amazon.aws.aws_ec2 inventory plugin:

code
---
plugin: amazon.aws.aws_ec2
use_deprecated_tags: false
regions:
  - us-east-1
  - us-west-2
filters:
  tag:Environment: production
  instance-state-name: running
keyed_groups:
  - key: ec2_tags.Role
    prefix: role
  - key: ec2_tags.Environment
    prefix: env
  - key: placement.availability_zone
    prefix: az
hostnames:
  - tag:Name
  - private-ip-address
compose:
  ansible_host: private_ip_address
code
# Test dynamic inventory
ansible-inventory -i aws_ec2.yml --list
ansible-inventory -i aws_ec2.yml --graph

The plugin needs boto3 and botocore on the control node, and the file name must end with aws_ec2.yml or aws_ec2.yaml. Without explicit credentials it uses the standard AWS credential chain, including an IAM instance profile on the control node. Two details matter in 2026:

  • →Instance tags are exposed as ec2_tags (added in amazon.aws 11.2.0). The older tags host variable is deprecated and scheduled for removal in a release after December 1, 2026, because it collides with an Ansible reserved name. Setting use_deprecated_tags: false silences the deprecation warning and confirms nothing in the inventory depends on it.
  • →Pick ansible_host deliberately. private_ip_address suits a control node inside the VPC or on a VPN; use public_ip_address only when instances are meant to be reachable from the internet.

# Ansible playbooks

## Basic playbook structure

code
---
- name: Configure web servers
  hosts: webservers
  become: true
  vars:
    app_name: myapp
    app_port: 8080
    server_name: example.com
    ssl_enabled: false

  tasks:
    - name: Install required packages
      ansible.builtin.apt:
        name:
          - nginx
          - python3-pip
          - git
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create application directory
      ansible.builtin.file:
        path: "/opt/{{ app_name }}"
        state: directory
        owner: www-data
        group: www-data
        mode: "0755"

    - name: Copy application files
      ansible.builtin.copy:
        src: files/app/
        dest: "/opt/{{ app_name }}/"
        owner: www-data
        group: www-data
        mode: "0644"
        directory_mode: "0755"
      notify: Reload nginx

    - name: Configure nginx
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: "/etc/nginx/sites-available/{{ app_name }}"
        owner: root
        group: root
        mode: "0644"
      notify: Reload nginx

    - name: Enable nginx site
      ansible.builtin.file:
        src: "/etc/nginx/sites-available/{{ app_name }}"
        dest: "/etc/nginx/sites-enabled/{{ app_name }}"
        state: link
      notify: Reload nginx

    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

Notes on this playbook:

  • →Every task uses an FQCN (ansible.builtin.apt). Short names still resolve for some legacy modules, but not for all: with amazon.aws installed, a task that says ec2_instance fails with "couldn't resolve module/action". ansible-lint's fqcn rule flags every short name.
  • →Booleans are written true and false. YAML 1.1 also accepts yes and no, but ansible-lint's truthy rule reports them.
  • →File modes are quoted strings ("0644") so YAML does not parse them as numbers. directory_mode is set separately because mode alone also applies to the directories created while copying a tree.
  • →The handler reloads nginx instead of restarting it, so configuration changes do not drop connections. Handlers run once, at the end of the play, no matter how many tasks notify them.

## Advanced playbook patterns

### 1. Roles

A role packages tasks, handlers, templates, and defaults in a fixed layout. ansible-galaxy role init webserver creates the skeleton (README.md, defaults, handlers, meta, tasks, tests, vars), and you add templates and files as needed.

code
roles/
└── webserver/
    ├── tasks/
    │   ├── main.yml
    │   ├── install.yml
    │   └── configure.yml
    ├── handlers/
    │   └── main.yml
    ├── templates/
    │   └── nginx.conf.j2
    ├── files/
    ├── vars/
    │   ├── Debian.yml
    │   └── RedHat.yml
    ├── defaults/
    │   └── main.yml
    ├── meta/
    │   └── main.yml
    └── README.md

roles/webserver/tasks/main.yml:

code
---
- name: Include OS-specific variables
  ansible.builtin.include_vars: "{{ ansible_facts['os_family'] }}.yml"

- name: Install packages
  ansible.builtin.include_tasks: install.yml

- name: Configure web server
  ansible.builtin.include_tasks: configure.yml

- name: Ensure web server is running
  ansible.builtin.service:
    name: "{{ webserver_service }}"
    state: started
    enabled: true

roles/webserver/vars/Debian.yml:

code
---
webserver_package: nginx
webserver_service: nginx
webserver_config_path: /etc/nginx/conf.d/app.conf

Role variables carry the role name as a prefix (webserver_package) so they cannot collide with variables from other roles; ansible-lint enforces this with var-naming[no-role-prefix]. include_tasks is evaluated at run time, which lets it use variables loaded earlier in the role; import_tasks is processed when the playbook is parsed.

Using roles:

code
---
- name: Deploy web application
  hosts: webservers
  roles:
    - role: webserver
      tags: webserver

### 2. Conditionals

code
---
- name: Install packages based on OS
  hosts: all
  become: true
  tasks:
    - name: Install Apache on Debian
      ansible.builtin.apt:
        name: apache2
        state: present
      when: ansible_facts['os_family'] == "Debian"

    - name: Install Apache on RedHat
      ansible.builtin.dnf:
        name: httpd
        state: present
      when: ansible_facts['os_family'] == "RedHat"

    - name: Allow HTTP through firewalld in production
      ansible.posix.firewalld:
        service: http
        permanent: true
        immediate: true
        state: enabled
      when:
        - ansible_facts['os_family'] == "RedHat"
        - deploy_env == "production"

    - name: Install development tools outside production
      ansible.builtin.apt:
        name:
          - build-essential
          - gdb
        state: present
      when:
        - ansible_facts['os_family'] == "Debian"
        - deploy_env != "production"

Facts are read from ansible_facts['os_family']. The injected short form ansible_os_family still works, but ansible-core 2.20 deprecated the INJECT_FACTS_AS_VARS setting that provides it: the default will change to False in ansible-core 2.24, and you are warned whenever a playbook accesses an injected fact.

### 3. Loops

code
---
- name: Create multiple users
  hosts: all
  become: true
  vars:
    users:
      - name: alice
        uid: 1001
        groups: ["developers", "docker"]
      - name: bob
        uid: 1002
        groups: ["developers"]
      - name: charlie
        uid: 1003
        groups: ["ops", "docker"]

  tasks:
    - name: Create user groups
      ansible.builtin.group:
        name: "{{ item }}"
        state: present
      loop:
        - developers
        - ops
        - docker

    - name: Create users
      ansible.builtin.user:
        name: "{{ item.name }}"
        uid: "{{ item.uid }}"
        groups: "{{ item.groups }}"
        append: true
        shell: /bin/bash
        create_home: true
      loop: "{{ users }}"
      loop_control:
        label: "{{ item.name }}"

    - name: Add SSH keys
      ansible.posix.authorized_key:
        user: "{{ item.name }}"
        key: "{{ lookup('ansible.builtin.file', 'ssh_keys/' ~ item.name ~ '.pub') }}"
      loop: "{{ users }}"
      loop_control:
        label: "{{ item.name }}"

append: true keeps users' existing supplementary groups; without it the groups list replaces them. loop_control.label keeps task output readable for lists of dictionaries.

### 4. Blocks and error handling

code
---
- name: Deploy application with error handling
  hosts: webservers
  become: true
  vars:
    backup_file: "/backup/myapp-{{ ansible_facts['date_time']['iso8601_basic_short'] }}.tar.gz"

  tasks:
    - name: Deploy with rollback
      block:
        - name: Stop application
          ansible.builtin.service:
            name: myapp
            state: stopped

        - name: Back up the current version
          community.general.archive:
            path: /opt/myapp
            dest: "{{ backup_file }}"
            format: gz
            mode: "0600"

        - name: Deploy the new version
          ansible.builtin.unarchive:
            src: files/myapp-v2.0.tar.gz
            dest: /opt/myapp

        - name: Run database migrations
          ansible.builtin.command: /opt/myapp/migrate.sh
          changed_when: true

        - name: Start application
          ansible.builtin.service:
            name: myapp
            state: started

      rescue:
        - name: Restore from the backup
          ansible.builtin.unarchive:
            src: "{{ backup_file }}"
            dest: /opt/myapp
            remote_src: true

        - name: Start the restored application
          ansible.builtin.service:
            name: myapp
            state: started

        - name: Send failure notification
          community.general.mail:
            host: smtp.example.com
            to: ops@example.com
            subject: "Deployment failed on {{ inventory_hostname }}"
            body: "Deployment failed and was rolled back"
          delegate_to: localhost

      always:
        - name: Clean up temporary files
          ansible.builtin.file:
            path: /tmp/deployment
            state: absent

The rescue section runs if any task in the block fails, and always runs either way. Two details differ from many published examples: the restore step uses remote_src: true because the backup is on the managed node (unarchive otherwise looks for src on the control node), and backup_file is defined once so the backup and restore steps agree on the path.

### 5. Templates (Jinja2)

templates/nginx.conf.j2:

code
upstream {{ app_name }}_backend {
{% for host in groups['webservers'] %}
    server {{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }}:{{ app_port }};
{% endfor %}
}

server {
    listen 80;
    server_name {{ server_name }};

{% if ssl_enabled %}
    listen 443 ssl;
{% if nginx_http2 | default(false) %}
    http2 on;
{% endif %}
    ssl_certificate {{ ssl_cert_path }};
    ssl_certificate_key {{ ssl_key_path }};
    ssl_protocols TLSv1.2 TLSv1.3;
{% endif %}

    location / {
        proxy_pass http://{{ app_name }}_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /health {
        access_log off;
        default_type text/plain;
        return 200 "healthy\n";
    }

{% if deploy_env == 'production' %}
    # Production-specific configuration
    client_max_body_size 100M;
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
{% endif %}
}

The upstream block reads each host's default_ipv4 fact, so facts must have been gathered for every host in webservers, and on minimal images the ip command (the iproute2 package) must exist for network facts to be collected. HTTP/2 is opt-in: nginx 1.25.1 introduced the http2 on; directive and deprecated the http2 parameter of listen, but older distribution packages do not understand the new directive, so the template emits it only when nginx_http2 is true.

# Ansible modules

## Common modules

1. System, package, and file modules:

code
---
- name: Common modules
  hosts: all
  become: true
  tasks:
    - name: Create a deploy user
      ansible.builtin.user:
        name: deploy
        shell: /bin/bash
        groups: sudo
        append: true

    - name: Manage a service
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

    - name: Add a cron job
      ansible.builtin.cron:
        name: "Backup database"
        minute: "0"
        hour: "2"
        job: "/usr/local/bin/backup.sh"

    - name: Install packages on Debian and Ubuntu
      ansible.builtin.apt:
        name:
          - nginx
          - postgresql
        state: present
        update_cache: true

    - name: Install packages on RHEL-family systems
      ansible.builtin.dnf:
        name:
          - httpd
          - mariadb-server
        state: present

    - name: Install Python packages into a virtualenv
      ansible.builtin.pip:
        name:
          - django
          - celery
        virtualenv: /opt/myapp/venv

    - name: Copy a configuration file
      ansible.builtin.copy:
        src: files/config.yml
        dest: /etc/myapp/config.yml
        owner: root
        group: root
        mode: "0644"
        backup: true

    - name: Generate a configuration from a template
      ansible.builtin.template:
        src: templates/app.conf.j2
        dest: /etc/myapp/app.conf
        owner: root
        group: root
        mode: "0644"

    - name: Create the directory structure
      ansible.builtin.file:
        path: "/opt/myapp/{{ item }}"
        state: directory
        owner: www-data
        mode: "0755"
      loop:
        - logs
        - data
        - tmp

    - name: Download a file and verify its checksum
      ansible.builtin.get_url:
        url: https://example.com/file.tar.gz
        dest: /tmp/file.tar.gz
        checksum: "sha256:{{ file_sha256 }}"
        mode: "0644"

Use ansible.builtin.dnf for RHEL-family systems; ansible.builtin.yum remains as an alias of the same module. Where a role must support both families, ansible.builtin.package with a per-OS variable (as in the role above) avoids duplicate tasks.

2. Cloud modules:

code
---
- name: Cloud modules
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Launch an EC2 instance
      amazon.aws.ec2_instance:
        name: web-server
        key_name: my-key
        instance_type: t3.micro
        image_id: "{{ lookup('amazon.aws.ssm_parameter', '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64', region='us-east-1') }}"
        region: us-east-1
        vpc_subnet_id: subnet-12345678
        security_group: web-sg
        metadata_options:
          http_tokens: required
        tags:
          Environment: production
          Role: webserver

    - name: Upload a backup to S3
      amazon.aws.s3_object:
        bucket: my-bucket
        object: /backups/db-backup.sql
        src: /tmp/db-backup.sql
        mode: put

The AMI is resolved from the public SSM parameter at run time instead of hard-coding an image ID that goes stale, and the instance requires IMDSv2. The amazon.aws.s3_object module replaced the old aws_s3 name, which survives only as a redirect. Azure resources live in the azure.azcollection collection, which needs its own Python requirements installed.

3. Container modules:

code
---
- name: Container modules
  hosts: all
  become: true
  tasks:
    - name: Run a container
      community.docker.docker_container:
        name: myapp
        image: registry.example.com/myapp:1.4.2
        state: started
        restart_policy: unless-stopped
        published_ports:
          - "8080:8080"
        env:
          DATABASE_URL: "postgresql://db:5432/myapp"
          REDIS_URL: "redis://redis:6379"
        volumes:
          - /opt/myapp/data:/data

    - name: Build an image
      community.docker.docker_image_build:
        name: registry.example.com/myapp
        tag: 1.4.2
        path: /opt/myapp
        dockerfile: Dockerfile

    - name: Push the image
      community.docker.docker_image_push:
        name: registry.example.com/myapp
        tag: 1.4.2

The community.docker collection recommends its single-purpose modules (docker_image_build, docker_image_push, docker_image_pull, and so on) over the older all-in-one docker_image, which still works. Pin image tags to a version instead of latest.

# Ansible Vault

## Encrypting sensitive data

code
# Create an encrypted file
ansible-vault create secrets.yml

# Edit, view, encrypt, and decrypt files
ansible-vault edit secrets.yml
ansible-vault view secrets.yml
ansible-vault encrypt vars/production.yml
ansible-vault decrypt vars/production.yml

# Encrypt a single value to paste into an otherwise readable vars file
ansible-vault encrypt_string 's3cr3t' --name 'db_password'

# Change the vault password
ansible-vault rekey secrets.yml

Using Vault in playbooks:

code
---
- name: Deploy with secrets
  hosts: webservers
  become: true
  vars_files:
    - vars/common.yml
    - vars/secrets.yml # encrypted with ansible-vault

  tasks:
    - name: Configure the database connection
      ansible.builtin.template:
        src: database.yml.j2
        dest: /etc/myapp/database.yml
        owner: root
        group: myapp
        mode: "0640"
      no_log: true

no_log: true keeps the task's arguments and results out of the console and logs. It does not encrypt anything; the encryption comes from Vault.

Running with Vault:

code
# Prompt for the password
ansible-playbook vault_play.yml --ask-vault-pass

# Read the password from a file kept outside the repository
ansible-playbook vault_play.yml --vault-password-file ~/.vault_pass

# Label vault IDs to separate environments
ansible-playbook vault_play.yml --vault-id prod@~/.vault_pass_prod

Never commit the password file. For larger teams, pair Vault with an external secrets manager and fetch values with a lookup plugin at run time.

# Adopting Ansible on an existing fleet

  1. •Inventory first. Describe every host and group in an inventory, using dynamic inventory plugins for cloud instances.
  2. •Baseline role. Capture what is true of every server (users, SSH settings, time sync, logging agents) in one role and apply it with --check --diff before changing anything.
  3. •Application roles. Move deployments into roles with their own defaults, templates, and handlers, and keep environment differences in group_vars.
  4. •Secrets. Move credentials into Vault or an external manager before sharing the repository.
  5. •Automation. Lint and test in CI with ansible-lint and Molecule, then run playbooks from a controlled service. Advanced Ansible: Dynamic Inventory, Custom Modules, and AWX covers that last step, including the current state of AWX and Red Hat Ansible Automation Platform.

If servers are provisioned with Terraform, a common split is Terraform for infrastructure and Ansible for what runs on it; see Terraform Infrastructure as Code: Complete Guide. The shell and permission fundamentals behind many Ansible tasks are in Linux Essentials for DevOps.

# Common issues and troubleshooting

## Issue 1: SSH connection failures

Symptoms:

  • →"Permission denied" errors
  • →Connection timeouts
  • →"Host key verification failed"

Diagnosis:

code
# Test connectivity and authentication with maximum verbosity
ansible all -m ansible.builtin.ping -vvv

# Reproduce with plain SSH
ssh -vvv user@host

Solutions: fix the cause rather than disabling verification.

code
# Record host keys for new hosts (verify fingerprints out of band for production)
ssh-keyscan -H web1.example.com >> ~/.ssh/known_hosts
code
# ansible.cfg: trust new hosts on first contact, but refuse changed keys
[defaults]
timeout = 30

[ssh_connection]
ssh_common_args = -o StrictHostKeyChecking=accept-new

Setting host_key_checking = False is acceptable only for throwaway lab machines.

## Issue 2: privilege escalation failures

Symptoms:

  • →"sudo: a password is required" errors
  • →Permission denied on system operations

Solutions:

code
---
- name: Privilege escalation
  hosts: all
  tasks:
    - name: Task requiring root
      ansible.builtin.apt:
        name: nginx
        state: present
      become: true
      become_method: ansible.builtin.sudo
      become_user: root
code
# Prompt for the sudo password
ansible-playbook deploy.yml --ask-become-pass

For unattended runs, give the automation account passwordless sudo for the commands it needs through a file in /etc/sudoers.d/, validated with visudo -c.

## Issue 3: idempotency problems

Symptoms:

  • →Tasks always report "changed"
  • →Unnecessary operations on every run

Solutions:

code
---
- name: Idempotency patterns
  hosts: all
  become: true
  tasks:
    - name: Download the archive (skipped when dest already exists)
      ansible.builtin.get_url:
        url: https://example.com/file.tar.gz
        dest: /tmp/file.tar.gz
        mode: "0644"

    - name: Run an installer only once
      ansible.builtin.command: /opt/myapp/install.sh
      args:
        creates: /opt/myapp/.installed

    - name: Check whether the service unit exists
      ansible.builtin.stat:
        path: /etc/systemd/system/myapp.service
      register: service_file

    - name: Install the service unit
      ansible.builtin.template:
        src: myapp.service.j2
        dest: /etc/systemd/system/myapp.service
        owner: root
        group: root
        mode: "0644"
      when: not service_file.stat.exists

get_url is already idempotent: with the default force: false it downloads only when the destination does not exist, and it does not accept a creates argument (adding args: creates: to it fails with "Unsupported parameters"). creates belongs to command and shell. Prefer a purpose-built module over command or shell, and add changed_when to commands that cannot detect their own changes.

## Issue 4: "couldn't resolve module/action"

Symptoms:

  • →Syntax check fails on a task that worked in an older tutorial

Solutions: install the collection that provides the module (ansible-galaxy collection install -r requirements.yml) and use the FQCN. Run ansible-doc -l <collection> to confirm the module name, and let ansible-lint find the remaining short names.

# Best practices

## Playbook organization

  • →Use roles for reusable pieces and keep playbooks short.
  • →Use FQCNs for every module and pin collections in requirements.yml.
  • →Write booleans as true and false, quote file modes, and give every task a name.

## Variables

  • →Put environment data in group_vars and host_vars, not in playbooks.
  • →Never name a variable after a playbook keyword (environment, tags, name, hosts).
  • →Read facts through ansible_facts['...'], and prefix role variables with the role name.
  • →Encrypt secrets with Vault or fetch them at run time.

## Idempotency

  • →Prefer modules over command and shell.
  • →Run playbooks twice in CI and require the second run to report no changes.
  • →Use --check --diff before applying to production.

## Error handling

  • →Use block, rescue, and always for deployments that need rollback.
  • →Combine serial with max_fail_percentage for rolling changes, as shown in the advanced guide.

## Testing

  • →Run ansible-lint and ansible-playbook --syntax-check on every pull request.
  • →Test roles with Molecule, and try changes in a non-production inventory first.

# Key takeaways

  • →Install ansible or ansible-core with pipx or pip, pin collections in requirements.yml, and refer to every module by its fully qualified collection name.
  • →ansible-core 2.21 is current, supports Python 3.12 through 3.14 on the control node, and the project maintains the latest three ansible-core releases.
  • →Do not disable SSH host key checking globally; manage known_hosts or use StrictHostKeyChecking=accept-new.
  • →Never use a playbook keyword such as environment or tags as a variable name; the documentation lists keywords as invalid variable names.
  • →For the AWS inventory plugin, read tags from ec2_tags and set use_deprecated_tags: false, because the tags host variable is slated for removal after December 1, 2026.
  • →Reference facts as ansible_facts['os_family']; the injected ansible_os_family form is deprecated and will stop being the default in ansible-core 2.24.
  • →get_url is idempotent by default and rejects creates; use creates and changed_when with command and shell.

# Further reading

Test yourself: Ansible Automation assessment

All posts