Running Python script via ansible

try to use script directive, it works for me

my main.yml

---
- name: execute install script
  script: get-pip.py

and get-pip.py file should be in files in the same role


If you want to be able to use a relative path to your script rather than an absolute path then you might be better using the role_path magic variable to find the path to the role and work from there.

With the structure you are using in the question the following should work:

- name: run my script!
  command: ./mypythonscript.py
  args:
    chdir: "{{ role_path }}"/files
  delegate_to: 127.0.0.1
  run_once: true

An alternative/straight forward solution: Let's say you have already built your virtual env under ./env1 and used pip3 install the needed python modules. Now write playbook task like:

 - name: Run a script using an executable in a system path
  script: ./test.py
  args:
    executable: ./env1/bin/python
  register: python_result
  
  - name: Get stdout or stderr from the output
    debug:
      var: python_result.stdout