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.
Create a directory structure like this for your Ansible project:
ansible-python-example/ ├── inventory.ini ├── playbook.yml └── python_script.py
Create an inventory file to specify the target server(s). Replace server1.codetryout.com and server2.codetryout.com with your server’s actual IP addresses or hostnames.
[servers] server1.codetryout.com server2.codetryout.com
Create a playbook YAML file that defines the tasks you want to perform. In this case, we’ll copy and execute the python_script.py to the remote servers.
--- - name: Copy and run Python script hosts: servers tasks: - name: Copy Python script to remote servers copy: src: python_script.py dest: /tmp/python_script.py mode: 0755 # Make the script executable - name: Run Python script on remote servers command: python3 /tmp/python_script.py
Create a Python script (e.g., python_script.py) to execute on the remote servers. For example, let’s create a simple script that prints “Hello, Ansible!”.
# python_script.py print("Hello, Ansible!")
- 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/python_script.py, 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.