6

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
Dawny33
  • 10,543
  • 21
  • 82
  • 134

3 Answers3

7

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.

Dawny33
  • 10,543
  • 21
  • 82
  • 134
3

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])
Jameel Grand
  • 2,294
  • 16
  • 32
  • Thanks, But, it is giving me this error: http://pastebin.com/xZdAqbNu I did this: `- name: Run Python Script script: /home/ec2-user/AnsibleDir/GitRepo/processing.py --some-arguments N, bucket_name` – Dawny33 Feb 03 '17 at 11:35
  • I did attach the link to pastebin of the error in the above comment. Anyways, here it is: http://pastebin.com/xZdAqbNu – Dawny33 Feb 03 '17 at 11:38
  • how you are catching those arguments???? in script??? i mean using sys.argv??????? – Jameel Grand Feb 03 '17 at 11:39
  • Yes. With sys.argv. `N = sys.argv[1]` – Dawny33 Feb 03 '17 at 11:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/134758/discussion-between-dawny33-and-jameel-grand). – Dawny33 Feb 03 '17 at 11:46
0

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.

U880D
  • 8,601
  • 6
  • 24
  • 40