Run Python script with arguments in Ansible

Question:

I want to run a Python script from inside of an ansible playbook, with input arguments. How do I do it?

I tried command, but it doesn’t seem to take any input arguments.
I also tried script, but it seems to be considering only bash scripts.

PS: I am taking in the input arguments as --extra-vars.

Asked By: Dawny33

||

Answers:

No, script module is for all type of scripts

you have to give #!/usr/bin/python at very first line in your python script file.

# Example from Ansible Playbooks
- script: /some/local/script.py 1234

Python file example :

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print '1st Argument :', str(sys.argv[1])
Answered By: Jameel Grand

I was able to run the script with the following statement:

- name: Run Py script
  command: /path/to/script/processing.py {{ N }} {{ bucket_name }}
  become: yes
  become_user: root

This solved the problem.

Answered By: Dawny33

Regarding

I want to run a Python script from inside of an Ansible playbook, with input arguments. … I tried command, but it doesn’t seem to take any input arguments.

and technically, the command module itself, as well inline code can just be used with facts and therefore --extra-vars.

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Python inline code example
    command: /usr/bin/python
    args:
      stdin: |
        import glob
        print(glob.glob("/home/{{ ansible_user }}/*"))
    register: results

  - name: Show result
    debug:
      msg: "{{ results.stdout }}"

… even if that (inline code) is not a recommended way to use Ansible and his capabilities.

Answered By: U880D
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.