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!
To convert Python Dictionary keys to List, you can use dict. keys() method which returns a dict_keys object. This object can be iterated, and if you pass it to list() constructor, it returns a list object with dictionary keys as elements.
The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.
For Ansible, nearly every YAML file starts with a list. Each item in the list is a list of key/value pairs, commonly called a “hash” or a “dictionary”. So, we need to know how to write lists and dictionaries in YAML. There's another small quirk to YAML.
with_dict: - "{{ zones_hash }}" declares a list with a dict as the first index, and Ansible rightfully complains since it expects a dict. The solution kfreezy mentioned works since it actually gives a dictionary to with_dict and not a list: with_dict: "{{ zones_hash }}" Follow this answer to receive notifications.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With