with_items... in groups[item.hostgroups]

Hello,

I’m trying to create new users but I’ve encountered a problem with the when statement which doesn’t allows me to move forward.

users.yml

`

  • fullname: Full Name Here1
    username: sshusernamehere1
    userkey: …/files/ssh-keys/sshusernamehere1/authorized_keys
    access:
    state: present
    groups:

  • wheel

  • sftpusers
    hosts:

  • all-management-servers

  • all-jenkins-servers

  • fullname: Full Name Here2
    username: sshusernamehere2
    userkey: …/files/ssh-keys/sshusernamehere2/authorized_keys
    access:
    state: present
    groups:

  • agroup

  • sftpusers
    hosts:

  • all-servers

  • all-web-servers

`

main.yml

`

  • name: USERS | SSH USERS | Checking user(s) presence within the group…
    user: name=“{{ item.username }}” groups=“{{ item.access.groups }}” append=yes createhome=yes state=“{{ item.access.state }}”
    when:

  • item.access.state == “present”

  • item.access.hosts is defined

  • inventory_hostname in groups[‘item.access.hosts’]
    with_items: “{{ users }}”

  • name: USERS | SSH USERS | Deploying SSH Key(s) for our user(s)…
    authorized_key: user=“{{ item.username }}” state=“{{ item.access.state }}” key=“{{ lookup(‘file’, item.userkey)}}”
    when:

  • item.access.state == “present”

  • item.access.hosts is defined

  • inventory_hostname in groups[‘item.access.hosts’]
    with_items: “{{ users }}”

`

What’s wrong with this or how may I change my main.yml code in order to deploy the users only if that inventory_hostname is part of the hosts: group (which is defined on ansible hosts file).

Thanks you!

Can you post your error(s) you are getting? Also assuming that your with_items: “{{ users }}” is defined in users.yml? Such as,

users.yml

users:
- fullname: Full Name Here1
username: sshusernamehere1
userkey: ../files/ssh-keys/sshusernamehere1/authorized_keys
access:
state: present
groups:
- wheel
- sftpusers
hosts:
- all-management-servers
- all-jenkins-servers

- fullname: Full Name Here2
username: sshusernamehere2
userkey: ../files/ssh-keys/sshusernamehere2/authorized_keys
access:
state: present
groups:
- agroup
- sftpusers
hosts:
- all-servers

- all-web-servers