简体   繁体   中英

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!

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 with a dash "-" in YAML . Adding additional items under each item of a list makes it a list of lists.

Example of a list:

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

Example of a list of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM