Pranav Barve
Pranav Barve

Reputation: 105

Passing nested dictionary as extra_vars to ansible-playbooks

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.

Upvotes: 2

Views: 1588

Answers (1)

guzmonne
guzmonne

Reputation: 2540

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.

Upvotes: 1

Related Questions