Skip to Content

Using dict2items in Ansible

The dict2items filter in Ansible is used to transform a dictionary into a list of key-value pairs. It’s particularly useful for iterating over a dictionary in playbooks or templates.

Dict2items Basic Usage

  1. Define a Dictionary: Start with a dictionary that you wish to convert into a list of items.
    
            vars:
              my_dict:
                key1: value1
                key2: value2
                key3: value3
            
  2. Use dict2items Filter: Apply the dict2items filter to the dictionary.
    
            - name: Convert dictionary to a list of items
              set_fact:
                my_list: "{{ my_dict | dict2items }}"
            

    This converts my_dict into a list where each item is a dictionary containing key and value pairs.

Example of dict2items in a Playbook

An example playbook demonstrating the use of dict2items:


- hosts: localhost
  gather_facts: no
  vars:
    my_dict:
      key1: value1
      key2: value2
      key3: value3

  tasks:
    - name: Convert dictionary to items
      set_fact:
        my_list: "{{ my_dict | dict2items }}"

    - name: Display each item
      debug:
        msg: "Key: {{ item.key }}, Value: {{ item.value }}"
      loop: "{{ my_list }}"

In this playbook, my_dict is converted into a list (my_list), and each item’s key and value are displayed.

Playbook Example with Outputs using dict2items in Ansible

This playbook demonstrates how to use the dict2items filter in Ansible, converting a dictionary into a list of items and displaying each item.

Get Your Free Linux training!

Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!

Playbook Example with Outputs:


- hosts: localhost
  gather_facts: no
  vars:
    my_dict:
      key1: value1
      key2: value2
      key3: value3

  tasks:
    - name: Convert dictionary to items
      set_fact:
        my_list: "{{ my_dict | dict2items }}"

    - name: Display each item
      debug:
        msg: "Key: {{ item.key }}, Value: {{ item.value }}"
      loop: "{{ my_list }}"

Outputs:

  1. After Converting Dictionary to Items with dict2items:my_list will contain:
    
            [
              {"key": "key1", "value": "value1"},
              {"key": "key2", "value": "value2"},
              {"key": "key3", "value": "value3"}
            ]
            

    This is a list of dictionaries, each containing a key and value from the original my_dict.

  2. Output of Display Each Item Task:This task loops over my_list and displays each key-value pair. The output will show each key and value of the items in my_list.
    
            TASK [Display each item] ********************************
            ok: [localhost] => (item={'key': 'key1', 'value': 'value1'}) =>
              msg: 'Key: key1, Value: value1'
            ok: [localhost] => (item={'key': 'key2', 'value': 'value2'}) =>
              msg: 'Key: key2, Value: value2'
            ok: [localhost] => (item={'key': 'key3', 'value': 'value3'}) =>
              msg: 'Key: key3, Value: value3'
            

Notes: The dict2items filter simplifies handling dictionaries in Ansible, allowing easy iteration over them and interfacing with modules that expect a list of items.

Advanced Use of dict2items in Ansible

The dict2items filter in Ansible can be utilized for advanced data manipulation beyond simple key-value pair transformations. Here are some complex scenarios where dict2items proves to be exceptionally useful.

1. Customizing Item Structure

Modify the structure of the list items by specifying custom names for the keys and values.


- set_fact:
    custom_list: "{{ my_dict | dict2items(key_name='myCustomKey', value_name='myCustomValue') }}"

2. Filtering and Selecting Data

Combine with other filters to select specific data points from the dictionary.


- set_fact:
    filtered_list: "{{ my_dict | dict2items | selectattr('value', 'equalto', 'someValue') | list }}"

3. Dynamic Attribute Assignment

Use in conjunction with loops for dynamic attribute assignment in tasks or templates.


- name: Configure multiple users
  user:
    name: "{{ item.key }}"
    state: "{{ item.value.state }}"
    groups: "{{ item.value.groups }}"
  loop: "{{ users_dict | dict2items }}"

4. Complex Data Manipulation

Part of sophisticated data manipulation strategies, especially when combined with map and other transformation filters.


- set_fact:
    transformed_list: "{{ my_dict | dict2items | map('regex_replace', 'somePattern', 'replacement') | list }}"

5. Using in Templates for Dynamic Content Generation

Employ dict2items in templates to dynamically generate content based on dictionary data.


{% for item in my_dict | dict2items %}
{{ item.key }}: {{ item.value }}
{% endfor %}

Best practices of using dict2items

  • dict2items is best used when you need to iterate over dictionary keys and values or pass dictionary data to a module that requires a list.
  • Utilize dict2items for simplified looping over dictionary elements. It makes your playbooks more readable and easier to manage.
  • Combine dict2items with other Jinja2 filters for complex data transformations. For example, you can filter or map the transformed list items for more tailored results.

 

dict2items offers a convenient way to handle complex data structures in Ansible, enhancing automation tasks.Ensure compatibility of the dictionary structure with dict2items. This filter is available in Ansible 2.5 and later versions.