2

I want to pass a huge nested dictionary as an extra_vars to an Ansible playbook. I want to use values from that dictionary in my playbook.

sample_dict = { 'student' : {'name' : 'coder', 'marks' : 100} }

I want to pass this dictionary as an extra_var I want to use the values from it. I am not able to access separate values from the dictionary using jinja templating.

Example: If I want to use the value of marks in an ansible-playbook, how do I access it?

I am using python3.5 and ansible 2.8. I am using ansible-runner module to run the playbooks.

guzmonne
  • 2,490
  • 1
  • 16
  • 22
Pranav Barve
  • 105
  • 1
  • 7

1 Answers1

1

You can walk dictionaries in jinja in two ways:

  1. Using the python interface.
  2. Using the json_query filter

The first one uses brackets [] to travel through the dictionary. And, json_query takes in a string with the path to key you want to read.

Check this playbook example:

---
- name: Diff test
  hosts: local
  connection: local
  gather_facts: no
  vars:
    sample_dict:
      student:
        name: 'coder'
        marks: 100
  tasks:
    - name: Using python dictionary interface
      debug:
        msg: '{{ sample_dict["student"]["marks"] }}'

    - name: Using json_query
      debug:
        msg: '{{ sample_dict | json_query("student.marks") }}'

Each task uses a different method to access the same variable.

I hope it helps.

guzmonne
  • 2,490
  • 1
  • 16
  • 22
  • Thanks for the answer. But actual situation is that, I am passing the dictionary from my python program as extra_vars to the ansible-playbook. My dictionary is not declared in yaml itself. – Pranav Barve Aug 09 '19 at 06:31
  • It doesn't matter how you pass the dict. It works the same. If it isn't, then the problem is that what you think is a dictionary actually isn't. If you can't read it with this code then you need to check the type of your variable and confirm that it is a dictionary. – guzmonne Aug 09 '19 at 11:49