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?
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 }}"