Python Ansible example Playbook and execution

Ansible is a powerful tool for configuration management, application deployment, and task automation. Here’s a simple Python Ansible example demonstrating how to run a Python script on remote servers.


  • You have Ansible installed on your local machine.
  • You have SSH access to the remote server(s) where you want to run the Python script.

Directory Structure:
Create a directory structure like this for your Ansible project:

├── inventory.ini
├── playbook.yml
  1. inventory.ini:
    Create an inventory file to specify the target server(s). Replace and with your server’s actual IP addresses or hostnames.
  1. playbook.yml:
    Create a playbook YAML file that defines the tasks you want to perform. In this case, we’ll copy and execute the to the remote servers.
- name: Copy and run Python script
  hosts: servers
    - name: Copy Python script to remote servers
        dest: /tmp/
        mode: 0755  # Make the script executable

    - name: Run Python script on remote servers
      command: python3 /tmp/
    Create a Python script (e.g., to execute on the remote servers. For example, let’s create a simple script that prints “Hello, Ansible!”.
print("Hello, Ansible!")
  1. Running Ansible:
    Open your terminal and navigate to the ansible-python-example directory. To execute the Ansible playbook, use the following command:
ansible-playbook -i inventory.ini playbook.yml

Ansible will connect to the remote servers specified in the inventory, copy the Python script to /tmp/, and then execute it. You should see the “Hello, Ansible!” output in your terminal for each server.

This is a simple example, but Ansible can manage complex infrastructure and automate various tasks on remote servers. You can expand on this foundation to create more advanced Ansible playbooks for your specific needs.