How to iterate over a list in a condition

Viewed 68

I have two hosts: One in production, another one in test.
test and prod are defined in a fact file available on target hosts (nodes).

[node]
type= prod 

or

[node]
type= test

I have the following variables defined:

users:
  - username: A
    password: password_A
    update_password: always
    home: /home/A
    state: present
    nodes: ['test', 'prod']


  - username: B 
    password: passwd_B
    update_password: always
    home: /home/B
    state: present
    nodes: ['test']

My A user shall be installed on production and test hosts.
B user only on test host.

Hereafter a role that works fine if i use a single value for nodes definition.

- name: create users
  ansible.builtin.user:
    name: "{{ item.username }}"
    password: "{{ item.password }}"
    uid: "{{ item.uid }}"
    home: "{{ item.home }}"
    create_home: yes
    group : "{{ item.group }}"
    shell: /bin/bash
    state: present
    expires: -1
  with_items:
      - "{{ users }}"
  when:  item.nodes  ==  ansible_local['myfact']['node"']['type']

I don't know how to loop on each value of the item.nodes list and compare them with the local fact value. item.nodes[0], item.nodes[1], ... I might have other type of host, not only prod and test.
I tried subelements without success.

2 Answers

You don't need to iterate anything in your condition, you can assert that an element is in a list with the in test.

So your condition needs to be

when: ansible_local.myfact.node.type in item.nodes

Q: "A user shall be installed on production and test hosts. B user only on test host."

A: Condition is not needed. Use filter selectattr and test if a list contains a value. For example, given the inventory for testing

shell> cat hosts
prod type=prod
test type=test

The task

shell> cat pb.yml
- hosts: all
  tasks:
    - debug:
        msg: "Create user {{ item.username }}"
      loop: "{{ users|selectattr('nodes', 'contains', type) }}"
      loop_control:
        label: "{{ item.username }}"

iterates selected users only

TASK [debug] ******************************************************
ok: [prod] => (item=A) => 
  msg: Create user A
ok: [test] => (item=A) => 
  msg: Create user A
ok: [test] => (item=B) => 
  msg: Create user B
Related