working with multiple lists.. one defining the other?

I already have tasks for creating users, groups, authorized_keys, etc. from the existing lists of users, by setting a variable that’s linked to each of those.

What I want to do is have group_vars for an inventory that lists which groups I want added to servers. And then another inventory might have other group_vars where the groups are different. I want to define all users and what groups they’re in in users.yml, and then simply specify which groups get different access to servers in my inventory by creating my user_groups list in a group_var.

in group_vars/users.yml:

devs:

  • “{{ ronda }}”
  • “{{ abe }}”
  • “{{ kathy }}”

sysadmins:

  • “{{ york }}”
  • “{{ kathy }}”
  • “{{ george }}”

managers:

  • “{{ brown }}”
  • “{{ lee }}”

ronda:

  • { name: “ronda”, fullname: “Ronda”, uid: “1001”, gid: “1001”, state: “present”, remove: “no”, ssh_key: “…/ssh_keys/ronda.pub” }
    etc…

in inventory/group_vars/single-environment.yml:

user_groups:

  • devs
  • sysadmins
  • managers

There could be another file in inventory/group_vars/second-environment.yml that defines user_groups differently:

user_groups:

  • sysadmins

Is this possible, at all? I feel like I should be able to reference this doing something like user_groups[item.name], user_groups[item.fullname], user_groups[uid], etc. I know that method isn’t possible, but, there’s gotta’ be a way?

I’m actually using this very way of defining users and groups myself.

What you want to do is possible if you flatten the lists in user_groups using the flattened lookup.

Until now, you could only do that in a with_flattened lookup construct, but thanks to Brian’s recent patch, you can now also do it (in latet devel) in a templating lookup():

https://github.com/ansible/ansible/pull/10298

See also https://github.com/ansible/ansible/issues/10291 and https://github.com/ansible/ansible/issues/10291

Serge

Thank you for the response. Can you provide a quick example of how you use the flattening lookup to accomplish this.. particularly showing the structure of the data you're using?

Given your example, pretty simple:

with_flattened: user_groups

But that only works to feed a task. The new feature I referred to, is brand new, I didn’t use it yet, but that would roughly translate to

{{ lookup(‘flattened’, user_groups, want_list=True) }}