Using python variables in ansible

I tried this one

---
- name: py
  hosts: master
  tasks:
  - name:
    command: /home/vagrant/test.py
    register: csvfile
    changed_when: false
  - debug:
      var: csvfile
  - name: Create csvfile directories
    file:
      path: "/tmp/{{ item.host }}_{{ item.app }}"
      state: directory
    with_dict: "{{ csvfile }}"

Test.py results are:

{'key': 'stdout_lines', 'value': ["{'host': '123', 'app': 'abc'}", "{'host': '2345', 'app': 'def'}", "{'host': '8484', 'app': 'ghju'}", "{'host': '89393', 'app': 'yruru'}"]}

and i'm getting error at "/{{ item.host }}_{{ item.app }}"

Can someone help me?

The registered variable csvfile must have the attribute stdout_lines

csvfile:
  stdout_lines:
    - {'host': '123', 'app': 'abc'}
    - {'host': '2345', 'app': 'def'}
    - {'host': '8484', 'app': 'ghju'}
    - {'host': '89393', 'app': 'yruru'}

The simple loop should do the job

  - name: Create csvfile directories
    file:
      path: "/tmp/{{ item.host }}_{{ item.app }}"
      state: directory
    loop: "{{ csvfile.stdout_lines }}"

The key/value decomposition was added very probably by with_dict. Please confirm, update and fix the question. Post the output of the task

  - debug:
      var: csvfile

Frequently Asked Questions — Ansible Documentation, How can I set the PATH or any other environment variable for a task or entire or use '-c ssh' to use Native OpenSSH for connections instead of the python� Thus, at the very least you would need with_dict: "{{ csvfile.stdout }}" but that, too, will not work because the output is not an interoperability format that ansible can use. Just because it is written in python and your script is written in python does not mean they can communicate. You will need to have the test.py call json.dump or json

There are a bunch of things wrong, so while this is an "answer" because it is too big to fit into a comment here on S.O., it is not the fix to your problem because there is so much wrong with your code.

As your debug output demonstrates, the register: captures the output of the whole task, and not just the output from your program. Thus, at the very least you would need with_dict: "{{ csvfile.stdout }}" but that, too, will not work because the output is not an interoperability format that ansible can use. Just because it is written in python and your script is written in python does not mean they can communicate

You will need to have the test.py call json.dump or json.dumps on the results, and not just print() or repr or whatever it is calling now, so that the output can be parsed by ansible back into an actual data structure in your playbook

Then, what happens next depends on whether you continue to write out each dictionary from test.py on a per-line basis, or you choose to package them all into a list of dictionaries and dump that as JSON

Start by fixing the output from test.py to be parseable by ansible, and we'll go from there

Using Variables — Ansible Documentation, Creating valid variable names; Defining variables in inventory; Defining variables in a because they collide with attributes and methods of python dictionaries. If you have done some programming in Python, Java, C, C++ or in any other programming language, then variables are not alien. Just like in programming languages, variables in Ansible are used to store a value. In Ansible, variables provide the much-needed flexibility in Playbooks, templates and inventories as we shall later see in this tutorial.

Sumanth, you can try the same approach but using with_items:

  - name: Create csvfile directories
    file:
      path: "/tmp/{{ item.host }}_{{ item.app }}"
      state: directory
    with_items: "{{ csvfile.stdout_lines }}"

Python 3 Support — Ansible Documentation, Previous to 2.5, using Python 3 was considered a tech preview. a Python 3 interpreter, set the ansible_python_interpreter inventory variable at a group or host� What follows is an Ansible guide that will take you from installing Ansible to automatically deploying a long-running Python to a remote machine and running it in a Conda environment using supervisord. It presumes your development machine is on OS X and the remote machine is Debian-like; however, it shouldn't require too many changes to run it

How do i register the python variables in a Ansible task, You have to use register . If you modify your script to output json that might ease your work a little bit. - name: Execute Script command:� Ansible Vault can encrypt any structured data file used by Ansible. This can include “group_vars/” or “host_vars/” inventory variables, variables loaded by “include_vars” or “vars_files”, or variable files passed on the ansible-playbook command line with -e @file.yml or -e @file.json.

How to access Ansible variables in the Python code � Issue #1040 , The code works, but instead of hardcoding the string (my_username on the example), I wanted to import my role's default file and use the� You can use the Ansible Python API to control nodes, you can extend Ansible to respond to various Python events, you can write plugins, and you can plug in inventory data from external data sources. This document gives a basic overview and examples of the Ansible execution and playbook API.

Write a Ansible module with Python | by Austin Cunningham, Pass variables in and out of a Python Module. I was working on an upgrade script and I needed to bump the Semantic Versioning i.e. bumping� By default, Ansible assumes it can find a /usr/bin/python on your remote system that is either Python2, version 2.6 or higher or Python3, 3.5 or higher. Setting the inventory variable ansible_python_interpreter on any host will tell Ansible to auto-replace the Python interpreter with that value instead.

Comments
  • currently we are using V2.3 and Python 2.7. loops aren't working.
  • Thanks for your help, As i cant post everything here i posted as an answer can you please guide me on this
  • The offending line appears to be: file: splunkapps.csv path: "/tmp/{{ item.host }}_{{ item.app }}" ^ here We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" I go this error
  • If you are testing with values with special chars, you can always set {{ item.host | string}} or {{ item.app | string}} to cast it to strings.
  • I added | string as mentioned; I am with this error FAILED! => {"failed": true, "msg": "with_dict expects a dict"}
  • Have you added it to the csvfile.stdout_lines or to each item? Could you put a snippet of code of how this is actually looking right now? You can as well, create a debug with the following code [just before the Create csvfile directories]: ` - name: Debugging csvfile debug: var: "{{ item }}" with_items: "{{ csvfile.stdout_lines }}" ` This will output what is the item content, to see if we have to deep dive into this.
  • --- - name: py hosts: master tasks: - name: command: /home/vagrant/test.py register: csvfile changed_when: false - debug: var: csvfile - name: Create csvfile directories file: path: "/tmp/{{ item.AppName | string }}_{{ item.SealID | string }}" state: directory with_dict: "{{ csvfile.stdout_lines }}"