Ansible script Module: Run Local Scripts on Remote Hosts Guide
By Luca Berton · Published 2024-01-01 · Category: installation
How to run local scripts on remote hosts with Ansible script module. Execute Python, Bash, and custom scripts without copying them first. Examples included.
How to Run Python Script on Remote Machines after transferring it? I'm going to show you a live Playbook with some simple Ansible code. I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Run Python Script on Remote Machines • ansible.builtin.script • Runs a local script on a remote node after transferring it
Let’s talk about the Ansible module script. The full name is ansible.builtin.script, which means that is part of the Ansible builtin modules included in ansible-core. The purpose of the module is to Runs a local script on a remote node after transferring it.
Parameters • cmd string - script name or path • executable string - executable name or path
Let me summarize the main parameters of the module script. This module doesn't have any required parameters bus some options become necessary in this use case. The cmd parameter specifies the script name or path. The executable parameter specifies the interpreter name or path.
Links • ansible.builtin.script
Demo Let's jump into a real-life Ansible Playbook to Run Python Script on Remote Machines after transferring it. I'm going to show you how to create a cars.py custom Python script that output a JSON file, transfers it to a remote machine, and executes it using python3 interpreter.
code • cars.py • run_python_script.yml
execution
verbosity two execution
Conclusion
Now you know how to Run Python Script on Remote Machines after transferring it with Ansible.
Run a Python Script
With Arguments
Conditional Execution (creates)
Specify Interpreter
Capture Output
Script with Environment
script vs command vs shell
| Module | Source | Features | |--------|--------|----------| | script | Local script → remote | Transfers and executes | | command | Remote command | No shell features | | shell | Remote command | Shell pipes, redirects |
When to Use script
Idempotent Script Pattern
FAQ
Does the script need to exist on remote?
No — script copies from controller to remote, executes, then removes. The script only needs to exist on your Ansible controller.
How to make script idempotent?
Use creates: (skip if file exists) or removes: (only run if file exists). Or handle idempotency within the script itself.
Can I run scripts from a role?
Related Articles • Ansible JSON Conversion Guide • Ansible Handlers Guide • Ansible Become Guide • Ansible Inventory Guide • Ansible set_fact Guide
Category: installation
Watch the video: Ansible script Module: Run Local Scripts on Remote Hosts Guide — Video Tutorial