DevOpsCloud

Advanced Ansible: Dynamic Inventory, Custom Modules, and AWX

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

Advanced Ansible work usually falls into four areas: inventory that follows the cloud instead of a hand-edited file, custom modules for logic no existing module covers, orchestration patterns such as rolling updates, and a central service that runs automation for a team. EduGeek explains each, including the naming and support status of the central service as of October 2026: Ansible Tower is now the automation controller inside Red Hat Ansible Automation Platform, and its upstream project, AWX, has paused releases. Familiarity with Ansible Automation: Complete Configuration Management Guide is assumed. The playbooks, module, and inventory script were linted and run against ansible-core 2.21, and the AWS inventory configuration was tested against a local AWS API emulator.

# Dynamic inventory

## AWS EC2 inventory

inventory/production.aws_ec2.yml (the file name must end with aws_ec2.yml or aws_ec2.yaml):

code
---
plugin: amazon.aws.aws_ec2
use_deprecated_tags: false

regions:
  - us-east-1
  - us-west-2
  - eu-west-1

filters:
  instance-state-name: running
  tag:Managed: ansible

keyed_groups:
  # Group by instance type
  - key: instance_type
    prefix: type
  # Group by tag values
  - key: ec2_tags.Environment
    prefix: env
  - key: ec2_tags.Application
    prefix: app
  # Group by availability zone
  - key: placement.availability_zone
    prefix: az

hostnames:
  - tag:Name
  - private-ip-address

compose:
  ansible_host: private_ip_address
  # Per-instance SSH user from a tag, defaulting to the Amazon Linux user
  ansible_user: ec2_tags.get('SshUser', 'ec2-user')

groups:
  production: ec2_tags.get('Environment') == 'production'
  staging: ec2_tags.get('Environment') == 'staging'
  webservers: ec2_tags.get('Role') == 'web'
  databases: ec2_tags.get('Role') == 'db'
code
# List and graph the inventory
ansible-inventory -i inventory/production.aws_ec2.yml --list
ansible-inventory -i inventory/production.aws_ec2.yml --graph

# Run a playbook against it
ansible-playbook -i inventory/production.aws_ec2.yml deploy.yml

Points worth knowing:

  • →Tags live in ec2_tags. The plugin's older tags host variable is deprecated, scheduled for removal in a release after December 1, 2026, and collides with an Ansible reserved word. use_deprecated_tags: false turns it off now. ec2_tags was added in amazon.aws 11.2.0.
  • →compose and groups take Jinja2 expressions. The ansible_user expression reads an optional SshUser tag and falls back to ec2-user. Earlier examples derived the user from image_id, which is an AMI ID such as ami-0abc... and never contains an operating system name, so the condition was always false.
  • →Credentials come from the standard AWS chain; prefer an IAM instance profile on the control node over access keys. The plugin needs boto3 and botocore on the control node.
  • →Host addresses. private_ip_address assumes the control node can reach the VPC. Use public_ip_address only for instances meant to be internet reachable.

## Azure inventory

inventory/azure_rm.yml (the file name must end with azure_rm.yml or azure_rm.yaml):

code
---
plugin: azure.azcollection.azure_rm
auth_source: auto

include_vm_resource_groups:
  - production-rg
  - staging-rg

keyed_groups:
  - prefix: tag
    key: tags
  - prefix: azure_loc
    key: location
  - prefix: azure_os
    key: os_profile.system

conditional_groups:
  linux: "'linux' in os_profile.system"
  windows: "'windows' in os_profile.system"
  production: "tags.environment | default('') == 'production'"

The plugin is azure.azcollection.azure_rm. It needs the azure.azcollection collection plus the Python packages in that collection's requirements.txt. The os_profile.system host variable is lowercase (linux, windows), so expressions must match that case, and tags is a dictionary of the VM's Azure tags.

## A custom inventory script

When the source of truth is an internal API, an inventory script is still supported: Ansible runs it with --list and expects JSON. Returning _meta.hostvars from --list means Ansible never calls the script per host. For anything long-lived, consider a small inventory plugin or a collection that already supports your CMDB, but a script is the quickest route.

inventory/api_inventory.py:

code
#!/usr/bin/env python3
"""Dynamic inventory script for an internal inventory API.

Ansible calls this script with --list (all groups and host variables) or
--host <name>. Returning '_meta' from --list means --host is never called.
"""
import json
import os
import sys

import requests

API_URL = os.environ.get("INVENTORY_API_URL", "https://api.example.com")
TIMEOUT_SECONDS = 10


def build_inventory(servers):
    inventory = {"_meta": {"hostvars": {}}}

    for server in servers:
        for group in server["groups"]:
            entry = inventory.setdefault(group, {"hosts": [], "vars": {}})
            entry["hosts"].append(server["hostname"])

        inventory["_meta"]["hostvars"][server["hostname"]] = {
            "ansible_host": server["ip_address"],
            "ansible_user": server["ssh_user"],
            "deploy_env": server["environment"],
            "application": server["application"],
        }

    return inventory


def fetch_servers():
    response = requests.get(f"{API_URL}/inventory", timeout=TIMEOUT_SECONDS)
    response.raise_for_status()
    return response.json()["servers"]


def main():
    if len(sys.argv) == 2 and sys.argv[1] == "--list":
        print(json.dumps(build_inventory(fetch_servers()), indent=2))
    elif len(sys.argv) == 3 and sys.argv[1] == "--host":
        print(json.dumps({}))  # all variables already come from _meta
    else:
        print("Usage: api_inventory.py --list | --host <hostname>", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    try:
        main()
    except (requests.RequestException, KeyError, ValueError) as error:
        print(f"inventory error: {error}", file=sys.stderr)
        sys.exit(1)

This version sets a request timeout, fails with a clear message instead of a traceback, takes the API URL from an environment variable, and uses deploy_env rather than environment, which is a reserved playbook keyword. Make the script executable (chmod +x) and pass it with -i.

# Ansible Tower, automation controller, and AWX

## Names and status

NameWhat it isStatus
Ansible TowerThe original web UI, REST API, and task engine for AnsibleRenamed: Red Hat now calls it the automation controller
Red Hat Ansible Automation Platform (AAP)The supported product: automation controller, automation hub, Event-Driven Ansible, and the platform gatewayAAP 2.6 became generally available on October 8, 2025
AWXThe community upstream project for the controllerReleases paused since July 2, 2024

Red Hat's FAQ describes the automation controller as "formerly Ansible Tower," derived from AWX, and states that AWX is community-supported only and not recommended by Red Hat for production. The AWX repository's own README carries a caution that "releases of this project are now paused during a large scale refactoring"; the last release (24.6.1) is dated July 2, 2024, and the latest AWX Operator release (2.19.1) is from the same day. Use the Ansible Forum for current plans.

The practical guidance follows from that. For production automation, use AAP (or run automation from CI with the tools described below). For learning, evaluation, and test environments, AWX still works but should be treated as frozen at its 2024 state.

## Installing AWX

The Docker Compose file that older versions of this guide showed does not correspond to an official installation method. The AWX installation guide names the AWX Operator on Kubernetes as the preferred route; running AWX in Docker is documented only for development and test use and has no official published release. The operator is installed with Kustomize:

kustomization.yaml:

code
---
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  # Pick a tag from https://github.com/ansible/awx-operator/releases
  - github.com/ansible/awx-operator/config/default?ref=<tag>

# Set the image tag to match the ref above
images:
  - name: quay.io/ansible/awx-operator
    newTag: <tag>

namespace: awx
code
kubectl apply -k .
kubectl get pods -n awx

Then create an AWX resource and apply it:

awx-demo.yml:

code
---
apiVersion: awx.ansible.com/v1beta1
kind: AWX
metadata:
  name: awx-demo
spec:
  service_type: nodeport

The operator provisions the web and task pods, a PostgreSQL database, and the service; the operator documentation covers ingress, TLS, external databases, and persistent project storage. If you already run Kubernetes, Kubernetes Fundamentals covers the building blocks involved.

## The awx CLI and API

awxkit provides the awx command-line client. Its last release (24.6.1) predates current Python releases: it imports pkg_resources, so it needs setuptools<81, and in testing it failed with an argparse TypeError on Python 3.12 while awx --help worked on Python 3.11. Run it in a pinned Python 3.11 environment, call the REST API directly, or manage the controller from playbooks.

Authenticate with a token rather than putting a password on every command line, as the CLI documentation recommends:

code
export CONTROLLER_HOST=https://awx.example.com
$(CONTROLLER_USERNAME=alice CONTROLLER_PASSWORD=secret awx login -f human)
awx config

Create a project and job template and launch it (these examples follow the CLI's own documentation):

code
awx projects create --wait \
    --organization 1 --name 'MyProject' \
    --scm_type git --scm_url 'https://github.com/myorg/ansible-playbooks.git' \
    -f human

awx job_templates create \
    --name 'Deploy Application' --project 'MyProject' \
    --playbook deploy.yml --inventory 'Production' \
    -f human

awx job_templates launch 'Deploy Application' --monitor -f human

## Execution environments

Controller jobs run inside execution environments: container images that package ansible-core, the collections a job needs, and their Python dependencies, so a playbook behaves the same on a laptop, in CI, and on the controller. ansible-builder builds them from a definition file, and ansible-navigator runs playbooks inside one locally.

ee/execution-environment.yml:

code
---
version: 3

images:
  base_image:
    name: quay.io/fedora/fedora:latest

dependencies:
  ansible_core:
    package_pip: ansible-core
  ansible_runner:
    package_pip: ansible-runner
  galaxy:
    collections:
      - name: amazon.aws
      - name: ansible.posix
      - name: community.general
  python_interpreter:
    package_system: python3
    python_path: /usr/bin/python3
code
ansible-builder build --tag my-ee:1.0 -f ee/execution-environment.yml
ansible-navigator run deploy.yml --execution-environment-image my-ee:1.0 --mode stdout

The definition above passes ansible-builder create, which generates the build context; the build step additionally needs Podman or Docker. Pin the base image to a tag you control instead of latest for reproducible builds.

# Custom modules

## A simple custom module

Write a module when no existing one covers the logic and a command task would be fragile. A module declares its arguments, returns structured results, supports check mode when it can, and documents itself so ansible-doc works.

library/check_port.py:

code
#!/usr/bin/python

# Copyright: (c) 2026, Example Team
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import annotations

DOCUMENTATION = r"""
---
module: check_port
short_description: Check whether a TCP port accepts connections
description:
  - Opens a TCP connection from the managed node to the given host and port.
  - Never changes anything, so it is safe in check mode.
options:
  host:
    description: Host name or IP address to connect to.
    type: str
    required: true
  port:
    description: TCP port to connect to.
    type: int
    required: true
  timeout:
    description: Connection timeout in seconds.
    type: int
    default: 5
author:
  - Example Team (@example)
"""

EXAMPLES = r"""
- name: Check that HTTPS is reachable from the managed node
  check_port:
    host: example.com
    port: 443
    timeout: 10
  register: port_check
"""

RETURN = r"""
port_open:
  description: Whether the connection succeeded.
  returned: always
  type: bool
"""

import socket

from ansible.module_utils.basic import AnsibleModule


def port_is_open(host, port, timeout):
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except OSError:
        return False


def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type="str", required=True),
            port=dict(type="int", required=True),
            timeout=dict(type="int", default=5),
        ),
        supports_check_mode=True,
    )

    host = module.params["host"]
    port = module.params["port"]

    # A read-only probe, so it runs the same way in check mode
    is_open = port_is_open(host, port, module.params["timeout"])

    if is_open:
        module.exit_json(changed=False, msg=f"Port {port} is open on {host}", port_open=True)
    module.fail_json(msg=f"Port {port} is closed on {host}", port_open=False)


if __name__ == "__main__":
    main()

Corrections compared with many published examples: the module probes the port in check mode as well, because the probe changes nothing (returning early in check mode made the module report success without checking), it closes the socket with a context manager, and it carries DOCUMENTATION, EXAMPLES, and RETURN blocks. A module in a playbook-adjacent library/ directory is available by its short name. To share modules, package them in a collection, which also gives them a fully qualified name.

Usage:

code
---
- name: Verify the database port from the control node
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Check if the port is open
      check_port:
        host: example.com
        port: 443
        timeout: 10
      register: port_check

    - name: Display the result
      ansible.builtin.debug:
        msg: "Port is {{ 'open' if port_check.port_open else 'closed' }}"

Modules execute on the managed node, so host: example.com tests connectivity from that node. Delegate the task to localhost, as in the play above, to test from the control node.

# Advanced playbook patterns

## Rolling updates with serial

code
---
- name: Rolling update with health checks
  hosts: webservers
  become: true
  serial: "25%"
  max_fail_percentage: 25

  pre_tasks:
    - name: Remove from load balancer
      ansible.builtin.uri:
        url: "http://lb.example.com/api/remove/{{ inventory_hostname }}"
        method: POST
      delegate_to: localhost
      become: false
      register: lb_remove
      until: lb_remove.status == 200
      retries: 3
      delay: 5

  tasks:
    - name: Stop application
      ansible.builtin.service:
        name: myapp
        state: stopped

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

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

    - name: Wait for the application port
      ansible.builtin.wait_for:
        port: 8080
        delay: 10
        timeout: 60

    - name: Run health check
      ansible.builtin.uri:
        url: "http://{{ inventory_hostname }}:8080/health"
        status_code: 200
      delegate_to: localhost
      become: false
      register: health_check
      until: health_check.status == 200
      retries: 5
      delay: 10

  post_tasks:
    - name: Add back to load balancer
      ansible.builtin.uri:
        url: "http://lb.example.com/api/add/{{ inventory_hostname }}"
        method: POST
      delegate_to: localhost
      become: false
      register: lb_add
      until: lb_add.status == 200
      retries: 3
      delay: 5

How it works: serial: "25%" runs the whole play on a quarter of the hosts at a time, and max_fail_percentage: 25 aborts the play when failures exceed that share of a batch. The load balancer and health check calls are delegated to the control node because they talk to HTTP endpoints, with become: false so they do not try to escalate there. until, retries, and delay retry a task until its condition holds. The deployment step uses unarchive; the older example copied a tarball into place without extracting it.

## Delegation and run_once

code
---
- name: Database migration
  hosts: webservers
  tasks:
    - name: Run the database migration once, from a database host
      ansible.builtin.command: /opt/myapp/migrate.sh
      run_once: true
      delegate_to: "{{ groups['databases'][0] }}"
      changed_when: true

    - name: Clear the cache on every node
      ansible.builtin.command: /opt/myapp/clear-cache.sh
      changed_when: true

    - name: Notify the monitoring system once
      ansible.builtin.uri:
        url: "https://monitoring.example.com/api/deployment"
        method: POST
        body_format: json
        body:
          application: myapp
          version: "{{ app_version }}"
          hosts: "{{ groups['webservers'] }}"
      delegate_to: localhost
      run_once: true

run_once: true runs a task for the first host in the batch and applies the result to the rest. ansible-lint warns that run_once can behave differently under the free strategy, which matters only if you set strategy: free.

# Running automation for a team

Whether the runner is AAP, AWX, or a CI job, the same practices apply:

  • →Source of truth in Git. Playbooks, roles, requirements.yml, and execution environment definitions live in version control, and the runner only pulls them.
  • →Credentials stay with the runner. SSH keys, cloud credentials, and Vault passwords are stored in the platform's credential store (or a CI secret store), never in playbooks.
  • →Least privilege per job. Give each job template or pipeline the inventory, credentials, and permissions for one purpose, and use role-based access control to decide who may launch it.
  • →Approval and review. Run --check --diff or a plan-style job first, then require a human approval for production changes.
  • →Repeatable runtime. Build one execution environment per automation domain and promote it through the same stages as code.
  • →Audit. Keep job output and who-ran-what history where your compliance process can reach it.
  • →Cleanup. Expire old job data and back up the controller database.

For infrastructure provisioning that runs before these playbooks, see Terraform Infrastructure as Code: Complete Guide.

# Best practices

## Inventory

  • →Use dynamic inventory for cloud hosts and group by tags you control (ec2_tags, Azure tags).
  • →Verify groups with ansible-inventory --graph before running playbooks.
  • →Never name a variable after a playbook keyword (environment, tags).

## Playbooks and modules

  • →Keep playbooks idempotent and use fully qualified collection names.
  • →Use serial and max_fail_percentage for anything that can take capacity out of service.
  • →Document custom modules with DOCUMENTATION, EXAMPLES, and RETURN, and package shared ones in collections.

## Security

  • →Use Ansible Vault or an external secrets manager, and rotate credentials on a schedule.
  • →Prefer instance profiles and short-lived credentials for the cloud inventory plugins.
  • →Limit who can launch production job templates.

## Performance

  • →Cache facts (gathering = smart with a cache plugin) and enable SSH pipelining where requiretty allows.
  • →Use serial batches and async for long tasks, and trim inventory filters so plugins query only the instances you need.

## Maintenance

  • →Track ansible-core support dates and upgrade collections on a schedule.
  • →Rebuild execution environments regularly to pick up Python and collection fixes.

# Key takeaways

  • →Ansible Tower is now the automation controller in Red Hat Ansible Automation Platform; AWX is the community upstream project, is supported only by the community, and has had no release since July 2, 2024.
  • →AWX installs through the AWX Operator on Kubernetes; the Docker Compose route is for development and test only and has no official release.
  • →The awx CLI (awxkit 24.6.1) needs setuptools<81 and failed on Python 3.12 in testing, so pin an older Python or use the REST API.
  • →In the AWS inventory plugin, read tags from ec2_tags and set use_deprecated_tags: false; the tags variable is scheduled for removal after December 1, 2026.
  • →Package automation in execution environments built with ansible-builder, so the same collections and Python dependencies run locally, in CI, and on the controller.
  • →A custom module should document itself, support check mode honestly, and return structured results; modules run on the managed node unless the task is delegated.
  • →Combine serial, max_fail_percentage, retries, and health checks to make rolling updates fail safely.

# Further reading

Test yourself: Advanced Ansible assessment

All posts