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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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])

5 Comments

Thanks, But, it is giving me this error: pastebin.com/xZdAqbNu I did this: - name: Run Python Script script: /home/ec2-user/AnsibleDir/GitRepo/processing.py --some-arguments N, bucket_name
I did attach the link to pastebin of the error in the above comment. Anyways, here it is: pastebin.com/xZdAqbNu
how you are catching those arguments???? in script??? i mean using sys.argv???????
Yes. With sys.argv. N = sys.argv[1]
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.