There are several ways to print out a dictionary object in Ansible, depending on your desired level of detail and formatting:
1. Using debug
Module:
This is the simplest way to print the entire dictionary, including keys and values.
YAML
- debug:
var: my_dict
2. Using Jinja2 Template Filters:
json_encode
filter: Converts the dictionary to a JSON string for a structured representation.
YAML
- debug:
msg: "Dictionary as JSON: {{ my_dict | json_encode }}"
to_yaml
filter (if using theyaml
collection): Converts the dictionary to a YAML string.
YAML
- debug:
msg: "Dictionary as YAML: {{ my_dict | to_yaml }}"
- Custom filters: Create custom filters to format the output according to your specific needs.
3. Looping through the Dictionary:
For a more controlled output, iterate through the dictionary using a loop and print individual key-value pairs.
YAML
- debug:
msg: "Key: {{ item.key }}, Value: {{ item.value }}"
loop: "{{ my_dict }}"
vars:
item: key_value # Adjust variable name if needed
4. Using dict
Lookup Plugin:
The dict
lookup plugin allows you to access specific values within the dictionary:
YAML
- debug:
msg: "Value of key 'foo': {{ lookup('dict', my_dict.foo) }}"
Choosing the Best Method:
- Use
debug
for quick inspection of the entire dictionary. - Use Jinja2 filters for structured output (JSON or YAML) or with custom formatting.
- Use loop for controlled output and accessing specific key-value pairs.
- Use
dict
lookup plugin for retrieving specific values within the dictionary.
Just to mention if you are looking for your next Techie Job in UK - Check this out