Loading...

Watch: Run a Python Script on Remote Machines - Ansible module script

How to automate the execution of a "cars.py" custom Python script on a remote machine after transferring it and processing the output as an Ansible JSON variable using Ansible Playbook and script module.

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](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/script_module.html)

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

``python

#!/usr/bin/env python3

import json

cars = {

"manufacturers": [

"Acura", "Alfa-Romeo", "Aston-Martin", "Audi", "Bentley", "BMW",

"Bugatti", "Buick", "Cadillac", "Chevrolet", "Chrysler", "Citroen",

"Deus Automobiles", "Dodge", "Ferrari", "Fiat", "Ford", "Geely",

"Genesis", "GMC", "Honda", "Hyundai", "Infiniti", "Jaguar", "Jeep",

"Kia", "Koenigsegg", "Lamborghini", "Lancia", "Land Rover", "Lexus",

"Lincoln", "Lotus", "Maserati", "Maybach", "Mazda", "McLaren", "Mercedes",

"Mini", "Mitsubishi", "Nissan", "Opel", "Pagani", "Peugeot", "Pontiac",

"Porsche", "Ram", "Renault", "Rolls-Royce", "Skoda", "Smart", "Subaru",

"Suzuki", "Tesla", "Toyota", "Volkswagen", "Volvo"

]

}

print(json.dumps(cars, indent=4))

`

  • run_python_script.yml

``yaml

---

  • name: run Python script

hosts: all

tasks:

- name: run cars.py script

ansible.builtin.script:

executable: python3

cmd: cars.py

register: cars_raw_output

- name: print cars_raw_output

ansib

Read the full tutorial: Run a Python Script on Remote Machines - Ansible module script