Ansible Automation with Python — Core Concepts

What Ansible does

Ansible is a configuration management and automation tool. It connects to remote servers via SSH, ensures they’re in a desired state, and reports what changed. Unlike Puppet or Chef, Ansible is agentless — the remote servers don’t need any special software installed beyond Python and SSH.

Red Hat acquired Ansible in 2015 for $150 million, and it remains one of the most widely used automation tools in the industry, with over 60,000 GitHub stars.

How it works

The workflow is straightforward:

  1. You define an inventory listing your servers (by IP or hostname, grouped logically)
  2. You write playbooks in YAML describing the desired state
  3. Ansible connects via SSH, gathers facts about each server, and executes tasks to reach the desired state
  4. Each task uses a module — a Python script that performs a specific action

When Ansible runs a task, it copies a small Python script (the module) to the remote machine, executes it, reads the JSON output, and cleans up. This is why the remote machine needs Python installed.

Key concepts

Idempotency is Ansible’s core principle. Running a playbook twice produces the same result as running it once. If Nginx is already installed and running, the “install nginx” task reports “ok” and moves on. This makes it safe to run playbooks repeatedly — for enforcement, not just initial setup.

Inventory groups servers logically: web servers, database servers, staging vs. production. You can use static files or dynamic inventory scripts (written in Python) that query AWS, GCP, or your CMDB.

Roles package related tasks, files, templates, and variables into reusable units. Ansible Galaxy, the community hub, hosts thousands of roles — from installing PostgreSQL to hardening SSH.

Facts are system information Ansible gathers automatically: OS version, CPU count, network interfaces, disk space. Your playbooks can use facts to make conditional decisions.

The Python connection

Ansible’s relationship with Python goes beyond implementation:

Modules are Python. The 3,000+ built-in modules (managing packages, files, services, cloud resources, databases) are Python scripts following a standard input/output contract.

Custom modules. When built-in modules don’t cover your use case, you write Python:

from ansible.module_utils.basic import AnsibleModule

def main():
    module = AnsibleModule(
        argument_spec={
            "name": {"type": "str", "required": True},
            "state": {"type": "str", "choices": ["present", "absent"]},
        }
    )
    name = module.params["name"]
    # Your logic here
    module.exit_json(changed=True, msg=f"Processed {name}")

if __name__ == "__main__":
    main()

Filters and plugins. Ansible’s Jinja2 templates support custom filters written in Python. Connection plugins, callback plugins, and lookup plugins are all Python extension points.

ansible-runner. This Python library lets you invoke Ansible programmatically from your Python applications, capturing output as structured data rather than terminal text.

Common misconception

Developers often confuse Ansible (configuration management) with Terraform (infrastructure provisioning). They’re complementary: Terraform creates servers, Ansible configures them. Terraform says “I need 5 EC2 instances,” Ansible says “each instance should have Nginx, Python 3.12, and these environment variables.” Many teams use both together.

When Ansible fits

  • Server setup and maintenance — packages, users, firewall rules, cron jobs
  • Application deployment — pulling code, running migrations, restarting services
  • Compliance enforcement — running playbooks on a schedule to ensure drift hasn’t occurred
  • Network automation — configuring routers and switches (Ansible has network-specific modules)
  • Multi-cloud orchestration — managing resources across AWS, GCP, and Azure with consistent syntax

Limitations

Ansible runs sequentially by default (though you can increase parallelism with forks). For managing thousands of servers, tools like SaltStack offer better performance. Ansible also lacks a built-in daemon for continuous enforcement — you typically run playbooks via cron or CI/CD.

The one thing to remember: Ansible’s Python DNA means Python developers can automate servers using a tool they can read, debug, and extend in their native language.

pythonansibleautomationdevops

See Also