Python – Passing the list of values to a python script as arguments inside ansible script

ansible-playbookpython

I have a python script inside ansible playbook:

---
 - hosts: localhost
   become: yes
   become_method: sudo
   become_user: root
   gather_facts: false
   tasks:
     - name: execute script
       command: ./qwe.py
       register: python_output

     - debug:
          var: python_output.stdout_lines

qwe.py :

#!/usr/bin/python
import subprocess 
import os
import json
import ssl
import platform
from requests import get
#import psutil
data = subprocess.Popen(['uname', '-r'], stdout = subprocess.PIPE)
output = str(data.communicate())
a = output[2:len(output)-10]
if "3.10.0-1062.9.1.el7.x86_64" ==  a:
  print(json.dumps({"status":"pass", "kernelVersion":a}))
else:
  print(json.dumps({"status":"fail", "kernelVersion":a}))

b = ssl.OPENSSL_VERSION
if "OpenSSL 1.0.2k-fips  26 Jan 2017" == b:
  print(json.dumps({ "status":"pass","OpenSSLVersion":b}))
else:
  print(json.dumps({"status":"fail", "OpenSSLVersion":b}))

I need to pass these list of values, for example :"OpenSSL 1.0.2k-fips 26 Jan 2017","3.10.0-1062.9.1.el7.x86_64" from outside the script instead of haedcoding it.In this way, i have 15 values I need to pass.

How can we achive it?
Thanks for your help and time!!

Best Answer

You have many possibilities.

  • Template out a .py of file with your vars/config and import it.
  • Template out your complete script.
  • Pass the data as a command line argument. Perhaps base64 encoded so you don't deal with as many problems escaping. See the docs for the b64encode filter, and maybe the to_json filters. Would be easy enough to do command: a.py {{ some_ansible_var | to_json|b64encode }}.
  • Write the data out to some kind of delimited temporary file and give the command the path to the temporary file. Writing out a file with template, use the
  • Pass the data via stdin. (You need shell instead of command)
  • Set environment variables (see the task argument environment)
  • Re-write your script as an ansible module. Then you can have full access to your variables.

Since I am sure this is just a bare bones example, I am not sure which idea would work best in your case.

Keep in mind that if all your software is installed via the distro package management system you could probably get everything you need just from the package_facts module. You may be re-inventing the wheel here.