'Ansible how to create list of dictionary keys

I am probably missing something simple. I have the dictionary in vars.yml

deploy_env:
  dev:
    schemas:
      year1:
        - main
        - custom
      year2:
        - main
        - custom
        - security
      year3:
        - main
        - custom

then in my playbook.yml I have something like

- set_fact:
    years: "{{ deploy_env.dev.schemas }}"

- name: Create schemas
  shell: "mysql ....params go here... {{ item }}"
  with_nested:
    - "{{ years }}"

The above works fine if schemas in vars.yml was a simple list ie:

...schemas:
     - year1
     - year2
     - year3

But as soon as I add additional items under each year (making this a dictionary(?) I start getting errors on the line: - "{{ years }}".

I basically want to populate {{ years }} with year1,year2,year3 values for this task.

I've looked at many examples but everything I looked at was soo complex and it was about how to create dictionaries which is not helpful.

Thanks!



Solution 1:[1]

It's possible to create a list of the dictionary keys. For example

    - set_fact:
        years: "{{ deploy_env.dev.schemas.keys()|list }}"
    - debug:
        var: item
      loop: "{{ years }}"

gives

    "item": "year1"
    "item": "year2"
    "item": "year3"

List vs Dictionary

Quoting:

"add additional items under each year (making this a dictionary(?)"

Adding items doesn't change a list to a dictionary. An item of a list is introduced by a dash - in YAML.

Example of a list:

    schemas:
      - year1
      - year2
      - year3

Example of a list of hashes with single lists

    schemas:
      - year1:
          - main
          - custom
      - year2:
          - main
          - custom
          - security
      - year3:
          - main
          - custom

Example of a dictionary:

    schemas:
      year1:
        - main
        - custom
      year2:
        - main
        - custom
        - security
      year3:
        - main
        - custom

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1