have searched the site but have been unable to find an answer. Does anyone know how to pass variables from an Ansible playbook to python.
Here is my basic code for testing
---
- hosts: localhost
gather_facts: false
vars:
numbers:
- 1
- 2
tasks:
- name: Run Python Script
script: pythontest.py
register: output
- debug:
var: output
and my basic python script
#!/usr/bin/python3.6
print('hello world')
print(numbers)
Have tried numerous ways to port the variable "number" to python with no luck, does anyone have any ideas?
CodePudding user response:
when you are using arg with python script, you can use only string
args, so if you want to use list or dictionary, i suggest you to use json string:
#!/usr/bin/python3.6
import sys
import json
numbers=json.loads(sys.argv[1])
print('hello world')
print(numbers)
print(numbers[0])
the playbook:
- hosts: localhost
gather_facts: false
vars:
numbers: >-
[1,2]
tasks:
- name: Run Python Script
script: pythontest.py {{numbers}}
register: output
- debug:
var: output
output:
ok: [localhost] => {
"output": {
"changed": true,
"failed": false,
"rc": 0,
"stderr": "",
"stderr_lines": [],
"stdout": "hello world\n[1, 2]\n1\n",
"stdout_lines": [
"hello world",
"[1, 2]",
"1"
]
}
}