Ansible Run Python Scripts: Execute & Manage Python on Remote Hosts
By Luca Berton · Published 2024-01-01 · Category: installation
How to run Python scripts with Ansible on remote hosts. Use command, script, and shell modules to execute Python code and handle output with examples.
Ansible is a versatile automation tool that can run Python scripts on target systems, making it a valuable resource for managing Python-based workflows and tasks. This article explores how Ansible can execute Python scripts, its requirements, and best practices for integrating Python into your automation pipelines.
Can Ansible Run Python Scripts?
Yes, Ansible can execute Python scripts on target systems using modules like script, command, or shell. By leveraging these modules, you can deploy, execute, and manage Python scripts efficiently.
Key Features:
- Cross-Platform Compatibility: Run Python scripts on Linux, Windows, and other platforms.
- Integration with Workflows: Combine Python scripts with Ansible tasks for end-to-end automation.
- Dynamic Execution: Pass arguments or environment variables to scripts during execution.
How to Run Python Scripts with Ansible
1. Using the script Module
The script module is designed to transfer and execute scripts on remote hosts.
Example:
- name: Execute Python script
hosts: all
tasks:
- name: Run Python script
ansible.builtin.script: /path/to/script.pyIn this example:
- The Python script is transferred to the target system and executed.
- The output of the script is captured for debugging or further use.
2. Using the command Module
The command module executes commands directly on the target system.
Example:
- name: Run Python script with command module
hosts: all
tasks:
- name: Execute Python script
ansible.builtin.command:
cmd: python3 /path/to/script.py3. Using the shell Module
The shell module provides more flexibility by allowing environment variables or shell-specific features.
Example:
- name: Run Python script with environment variables
hosts: all
tasks:
- name: Execute Python script with arguments
ansible.builtin.shell: python3 /path/to/script.py --arg1 value1
environment:
ENV_VAR: "example_value"4. Passing Arguments to Python Scripts
You can pass arguments directly to the script:- name: Run Python script with arguments
hosts: all
tasks:
- name: Execute script with arguments
ansible.builtin.command:
cmd: python3 /path/to/script.py arg1 arg2See also: Project Policy Validation with OPA and ansible-policy
Deploying and Executing Python Scripts
If the script is not present on the target system, use the copy module to transfer it before execution.
Example:
- name: Deploy and run Python script
hosts: all
tasks:
- name: Copy Python script to target
copy:
src: /local/path/to/script.py
dest: /remote/path/script.py
mode: '0755'
- name: Execute Python script
shell: python3 /remote/path/script.pyCapturing Script Output
Use the register keyword to capture the output of a Python script:
- name: Capture script output
hosts: all
tasks:
- name: Run Python script
command: python3 /path/to/script.py
register: script_output
- name: Display script output
debug:
var: script_output.stdoutSee also: Ansible vs Terraform: Key Differences & When to Use Each (2026 Guide)
Best Practices for Running Python Scripts with Ansible
- Validate Scripts:
- Secure Sensitive Data:
- Organize Scripts:
scripts/ directory within your project.
- Use Virtual Environments:
Example:
- name: Run script in virtual environment
shell: source /path/to/venv/bin/activate && python script.py
- Monitor Execution:
Use Cases for Ansible and Python Scripts
- Data Processing:
- Application Deployment:
- Infrastructure Management:
- Custom Automation:
See also: Ansible vs Terraform: Are They the Same? Key Differences Explained (2026)
Conclusion
Ansible provides robust support for executing Python scripts, making it a valuable tool for integrating custom automation and workflows. By leveraging modules like script, command, or shell, you can efficiently deploy and manage Python-based tasks across your infrastructure.
Learn More About Running Python Scripts with Ansible
Run Local Script on Remote Host
# script module copies and executes in one step
- name: Run Python script
ansible.builtin.script: files/setup.py
args:
executable: python3Run Remote Script
- name: Execute Python on remote
ansible.builtin.command:
cmd: python3 /opt/scripts/process_data.py
register: result
- debug: var=result.stdoutRun with Arguments
- ansible.builtin.command:
cmd: "python3 /opt/scripts/deploy.py --env production --version {{ app_version }}"
register: deploy_resultRun Inline Python
- ansible.builtin.shell: |
python3 -c "
import json
data = {'hostname': '{{ inventory_hostname }}', 'ip': '{{ ansible_host }}'}
print(json.dumps(data))
"
register: output
- set_fact:
host_data: "{{ output.stdout | from_json }}"Deploy and Run Script
- name: Deploy script
ansible.builtin.copy:
src: files/process.py
dest: /opt/scripts/process.py
mode: '0755'
become: true
- name: Install dependencies
ansible.builtin.pip:
requirements: /opt/scripts/requirements.txt
virtualenv: /opt/scripts/venv
become: true
- name: Run with virtualenv
ansible.builtin.command:
cmd: /opt/scripts/venv/bin/python /opt/scripts/process.py
register: resultCapture and Parse Output
- name: Run Python data processor
ansible.builtin.command:
cmd: python3 /opt/scripts/get_stats.py --format json
register: stats_raw
- set_fact:
stats: "{{ stats_raw.stdout | from_json }}"
- debug:
msg: "CPU: {{ stats.cpu_percent }}%, Memory: {{ stats.memory_percent }}%"Run in Virtual Environment
- ansible.builtin.command:
cmd: "{{ venv_path }}/bin/python {{ script_path }}"
environment:
VIRTUAL_ENV: "{{ venv_path }}"
PATH: "{{ venv_path }}/bin:{{ ansible_env.PATH }}"Error Handling
- ansible.builtin.command:
cmd: python3 /opt/scripts/validate.py
register: validation
failed_when: validation.rc != 0
changed_when: "'changes made' in validation.stdout"
- debug:
msg: "Validation failed: {{ validation.stderr }}"
when: validation.rc != 0script vs command vs shell
| Module | Source | Shell | Use Case |
|---|---|---|---|
script | Controller | No | Run local .py on remote |
command | Remote | No | Run remote .py (safe) |
shell | Remote | Yes | Pipes, redirects, inline |
FAQ
script module — does it install Python?
No. Python must already be on the remote host. The script module copies and executes your file.
How do I pass Ansible variables to Python?
Via arguments: python3 script.py --name {{ var }}
Via environment: environment: { MY_VAR: "{{ var }}" }
Via stdin: shell: echo '{{ data | to_json }}' | python3 script.py
Can I use pip module instead of running scripts?
For package management, use ansible.builtin.pip. For custom logic, run scripts.
Run Remote Python Script
- ansible.builtin.command: python3 /opt/scripts/process-data.py
register: result
- debug:
msg: "{{ result.stdout }}"Run Local Script on Remote Host
# Copies local script to remote, executes, then removes
- ansible.builtin.script: scripts/setup.py
args:
executable: python3
register: outputInline Python
- shell: |
python3 -c "
import json
data = {'status': 'ok', 'count': 42}
print(json.dumps(data))
"
register: result
- set_fact:
parsed: "{{ result.stdout | from_json }}"Python with Arguments
- command: >
python3 /opt/scripts/deploy.py
--environment {{ env }}
--version {{ app_version }}
--config /etc/myapp/config.yml
register: deploy_resultPython with Virtual Environment
# Create venv and install deps
- pip:
requirements: /opt/myapp/requirements.txt
virtualenv: /opt/myapp/venv
virtualenv_command: python3 -m venv
# Run with venv
- command: /opt/myapp/venv/bin/python /opt/myapp/main.pyCapture JSON Output
- command: python3 /opt/scripts/inventory.py
register: inventory_raw
- set_fact:
inventory_data: "{{ inventory_raw.stdout | from_json }}"
- debug:
msg: "Found {{ inventory_data.servers | length }} servers"Error Handling
- command: python3 /opt/scripts/validate.py
register: validation
failed_when: validation.rc != 0
changed_when: "'CHANGED' in validation.stdout"
- debug:
msg: "Validation: {{ validation.stdout }}"
when: validation.rc == 0Deploy and Run Pattern
- name: Deploy Python script
copy:
src: scripts/process.py
dest: /opt/scripts/process.py
mode: '0755'
become: true
- name: Install dependencies
pip:
name: [requests, pyyaml]
state: present
become: true
- name: Execute script
command: python3 /opt/scripts/process.py
register: result
environment:
API_KEY: "{{ vault_api_key }}"
no_log: truePython One-Liners
# Check Python version
- command: python3 --version
register: py_version
# Generate random string
- shell: python3 -c "import secrets; print(secrets.token_hex(16))"
register: random_token
# Parse YAML
- shell: python3 -c "import yaml; print(yaml.safe_load(open('/etc/config.yml'))['key'])"
register: config_valueFAQ
command vs shell for Python scripts?
Use command for simple script execution. Use shell if you need pipes, redirects, or environment variable expansion.
Do I need Python on the remote host?
Yes — Ansible itself requires Python on managed nodes. Your scripts can use the same Python installation.
How to pass secrets to Python scripts?
Use environment parameter with no_log: true, or write to a temp file and clean up after.
Related Articles
Category: installation