Last modified: Oct 04, 2026

Automate Servers with Ansible and Python

Server automation saves time and reduces errors. Manual work is slow and risky. Ansible and Python make automation simple and powerful.

This guide shows you how to combine both tools. You will learn the basics and see real examples. By the end, you can automate your own servers.

What Is Ansible?

Ansible is an open-source automation tool. It manages servers, networks, and cloud systems. It uses simple text files called playbooks.

Ansible works without agents. It connects over SSH. This makes setup fast and clean. You do not install software on target machines.

The core of Ansible is the playbook. A playbook is a YAML file. It lists tasks to run on your servers.

What Is Python Doing Here?

Ansible itself is written in Python. Many of its modules use Python under the hood. You can also write your own modules in Python.

Python adds flexibility. You can create custom logic. You can call APIs. You can process data before or after Ansible runs.

Together, they cover almost any automation need. Ansible handles orchestration. Python handles the complex parts.

Why Combine Ansible and Python?

Ansible is great for standard tasks. It installs packages, copies files, and restarts services. But sometimes you need more.

Maybe you need to parse a JSON response. Maybe you need to calculate values. Python fills that gap easily.

You can also use Python to generate dynamic inventories. This is useful for cloud servers that change often.

Another benefit is testing. You can write Python tests for your playbooks. This keeps your automation reliable.

Setting Up Ansible with Python

First, install Python on your control machine. Most Linux systems have it already. Check the version with a simple command.


python3 --version

You should see something like this:


Python 3.11.2

Next, install Ansible using pip. The pip install command makes this easy.


pip install ansible

Verify the installation with the ansible --version command.


ansible --version

You will see the Ansible version and the Python version it uses. This confirms everything works.

Your First Ansible Playbook

Create a file called install_nginx.yml. This playbook installs Nginx on a remote server.


# install_nginx.yml
- name: Install Nginx on web servers
  hosts: webservers
  become: yes
  tasks:
    - name: Install nginx package
      apt:
        name: nginx
        state: present

    - name: Start nginx service
      service:
        name: nginx
        state: started

The apt module handles package installation. The service module manages the service state.

Run the playbook with the ansible-playbook command.


ansible-playbook -i inventory.ini install_nginx.yml

You will see output like this:


PLAY [Install Nginx on web servers] ***************************

TASK [Gathering Facts] ****************************************
ok: [192.168.1.10]

TASK [Install nginx package] **********************************
changed: [192.168.1.10]

TASK [Start nginx service] ************************************
changed: [192.168.1.10]

PLAY RECAP ****************************************************
192.168.1.10 : ok=3 changed=2 unreachable=0 failed=0

The recap shows success. Two tasks changed the server. One task gathered facts.

Writing a Custom Python Module

Ansible has many modules. But sometimes you need a custom one. Python makes this possible.

Create a folder called library next to your playbook. Place your Python module inside it.

Here is a simple module that checks disk space.


#!/usr/bin/python
# disk_check.py

from ansible.module_utils.basic import AnsibleModule
import shutil

def main():
    module = AnsibleModule(
        argument_spec=dict(
            path=dict(type='str', required=True)
        )
    )

    path = module.params['path']
    total, used, free = shutil.disk_usage(path)

    # Convert bytes to gigabytes
    free_gb = round(free / (1024 ** 3), 2)

    module.exit_json(changed=False, free_space_gb=free_gb)

if __name__ == '__main__':
    main()

The AnsibleModule class handles input and output. The exit_json method returns results to Ansible.

Now use this module in a playbook.


# check_disk.yml
- name: Check disk space on servers
  hosts: all
  tasks:
    - name: Run custom disk check
      disk_check:
        path: /var
      register: disk_result

    - name: Show free space
      debug:
        msg: "Free space is {{ disk_result.free_space_gb }} GB"

Run it and you will see the free space for each server. This shows how Python extends Ansible.

Using Python for Dynamic Inventory

Static inventories work for fixed servers. But cloud servers change often. A dynamic inventory solves this.

Write a Python script that outputs JSON. Ansible reads this JSON as its inventory.


#!/usr/bin/python
# inventory.py

import json

inventory = {
    "webservers": {
        "hosts": ["192.168.1.10", "192.168.1.11"],
        "vars": {
            "ansible_user": "ubuntu"
        }
    },
    "dbservers": {
        "hosts": ["192.168.1.20"],
        "vars": {
            "ansible_user": "admin"
        }
    }
}

print(json.dumps(inventory))

The json.dumps function converts the dictionary to a JSON string. Ansible uses this output directly.

Run your playbook with this inventory.


ansible-playbook -i inventory.py install_nginx.yml

This approach scales well. You can pull server lists from AWS, Azure, or any API.

Best Practices for Ansible and Python

Keep your playbooks simple. Use roles to organize tasks. Roles make playbooks reusable and clean.

Store secrets in Ansible Vault. Never put passwords in plain text. The ansible-vault command encrypts sensitive files.

Test your Python modules locally first. Use the python3 command to run them directly. Fix bugs before using them in playbooks.

Use version control for everything. Git tracks changes to playbooks and modules. This helps you roll back if something breaks.

Idempotency is key in Ansible. Tasks should be safe to run many times. They should only change things when needed.

Document your custom modules. Add comments and docstrings. Future you will thank present you.

Common Mistakes to Avoid

Do not hardcode IP addresses. Use inventory variables instead. This makes playbooks portable.

Do not ignore errors. Add error handling in Python modules. Use try and except blocks.

Do not run playbooks as root unless needed. Use become only for tasks that require it.

Do not skip testing. Run playbooks in a staging environment first. Catch issues before they hit production.

Real-World Use Cases

You can automate server patching. A playbook updates all packages on a schedule.

You can deploy applications. Python scripts build and package code. Ansible pushes it to servers.

You can monitor systems. Python collects metrics. Ansible configures alerts and dashboards.

You can manage cloud resources. Python calls cloud APIs. Ansible configures the resulting servers.

The combination is powerful. It handles small tasks and large infrastructures alike.

Conclusion

Ansible and Python are a strong team. Ansible brings simple orchestration. Python brings deep flexibility.

Start with basic playbooks. Then add custom modules. Then build dynamic inventories. Each step adds power.

Automation reduces errors and saves time. Your servers become consistent and reliable. You focus on important work.

Try the examples in this guide. Install Ansible. Write a playbook. Create a Python module. You will see results fast.

Server automation is a skill worth learning. With Ansible and Python, you have everything you need to start today.