Generic Ansible Playbook for Running a Python Script

The below is a generic Ansible playbook for running a Python Script on a remote server. I'm actually using this with Ansible Tower / AWX (where the software is pulled from GIT onto a remote server, and run on the remote server.) 


---

- name: name_of_execution

  hosts: all

  gather_facts: False

 

  vars:

    code_dir: project_code_folder

    src_code_dir: template_code_folder

    script_name: the_script_you_want_to_run.py

    double_quote: '"'

 

  tasks:

  - name: set region

    set_fact:

      region: "{{ hostvars[inventory_hostname].region | default('??') }}"

 

  - name: setup

    setup:

 

  - name: generate collection id

    set_fact:

      collection_id: "{{(ansible_date_time['epoch']|int/3600)|int}}"

    run_once: True

    delegate_to: localhost

    when: collection_id is not defined

 

  - name: set win/linux

    set_fact:

      master_is_linux: "{{ 'WIN' not in (ansible_system | upper) }}"

 

  - name: make working dir

    file:

      name: ~/{{code_dir}}

      state: directory

    when: master_is_linux

 

  - name: deploy scripts

    copy:

      src: ../{{src_code_dir}}

      dest: ~/{{code_dir}}

    when: master_is_linux

 

  - name: execute python script

    shell: |

      if command -v python3

      then

      alias python='python3'

      fi;

      source /opt/folder/bin/activate;

      export PYTHONPATH=~/{{code_dir}}/{{src_code_dir}};

      cd ~/{{code_dir}}/{{src_code_dir}};

 

      python ~/{{code_dir}}/{{src_code_dir}}/{{script_name}};

    register: save_python_script_response

    when: master_is_linux

Comments