Ansible-playbook does not working with dictionary and with_items loop!

No, it is not correct. Below, I’ve commented out the broken lines of your code, and inserted the correct lines below each of them.

- name: user management set global groups macOS
  tags:
    - user_mgmt
    - admin_accounts
  group:
    name: "{{ item.key }}"
  # gid: "{{ item.gid }}"        # Broken: "item" has no "gid" at the top level.
    gid: "{{ item.value.gid }}"  # Fixed!
  # state: "{{ item.state | default('present') }}"  # Broken: if "state" exists,
  #   it would be inside the "item.value" dict.
    state: "{{ item.value.state | default('present') }}"
  loop: "{{ test_global_groups | dict2items }}"
  when:
  # - (test_global_groups[item].state|default('present')) == 'present' # Broken:
  #     "item" is a dict, not a string that you can use as an index into "test_global_groups".
    - (test_global_groups[item.key].state | default('present')) == 'present'
  # - item not in skip_groups  # Broken: "item" is a dict. It will never be "in skip_groups".
    - item.key not in skip_groups # Maybe fixed: is "skip_groups" a list?

You must fix all four of these problems or your task will continue to fail.

[Technically, the syntax is “correct”. It’s that the expressions are invalid; they don’t match the structure of the data, and therefore the task won’t run as it is.]

Please do ask any questions you still have, and post whatever YAML inputs and resulting errors that aren’t clear to you. But repeatedly posting that there’s nothing wrong with your code when experienced users have repeatedly said otherwise has cost you many unproductive days, so you may want to reconsider that strategy; it hasn’t worked yet.

1 Like