Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping on a dictionary with Ansible

I’m trying to create a loop that pulls data from a dictionary using Ansible and create resources (e.g. Group), based on https://docs.ansible.com/ansible/2.9/plugins/lookup/dict.html

# main.yaml
- name: 'Linux | Adding groups'
  ansible.builtin.group:
    name: "{{ item.key }}"
    state: "{{ item.value.state }}"
    gid: "{{ item.value.gid }}"
    system: False
  loop: "{{ lookup('dict', groups) }}"
# vars.yaml
groups:
  my_group:
    state: present
    gid: 1004

The code above always returns the following error:

fatal: [master-1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'state'\n\nThe error appears to be in 'path': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: 'Linux | Adding groups'\n  ^ here\n"}

Any clue on what’s wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Version: ansible [core 2.13.6]

>Solution :

You are looking for the dict2items filter.
You also have the issue that your variable is using a reserved word groups.

So, if you rename your variable, for example, to linux_groups, your task becomes:

- name: 'Linux | Adding groups'
  ansible.builtin.group:
    name: "{{ item.key }}"
    state: "{{ item.value.state }}"
    gid: "{{ item.value.gid }}"
    system: False
  loop: "{{ linux_groups | dict2items }}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading