Selecting a subset from within with_items

I have a task file to create users, add them to sudoers, enable ssh public key
login. A minimal version looks like this

How I solve this is by definig users in several list:

❦ Serge van Ginderachter <serge@vanginderachter.be>:

Then depending on the task I do
with_flattened:
- users_dev
- users_admin
- ..

Where can I read about with_flattened?

But maybe this will not work for me. If I have users who are admins and devs I have to
duplicate their definition?

I’m not sure why Serge is showing with_flattened here, when you wanted to iterate across ssh keys per user, rather than walk across two lists.

I’ve got a ticket open to create a lookup plugin more appropriate to making this easier, when there is a data structure of users.

https://github.com/ansible/ansible/issues/3752

We also have a ticket to make sure all the with_* features have examples in the 1.3 release.

❦ Michael DeHaan <michael@ansibleworks.com>:

I've got a ticket open to create a lookup plugin more appropriate to making
this easier, when there is a data structure of users.

with_subelements sounds like a nice addition.

But what I want is having a list of all users in a vars file and then for
a certain host to only create this and that user.

users:
   foo:
      name: "Foo Bar"
      ssh_key: "ssh-rsa ..."
   bar:
      name: "Bar Foo"
      ssh_key: "ssh-rsa ..."
   foobar:
      name: "Barbara Foo"
      ssh_key: "ssh-rsa ..."

On host alpha

- authorized_key: name={{ item.name }} key={{ item.ssh_key }}
   with_items:
      - users.foo
      - users.bar

On host beta

- authorized_key: name={{ item.name }} key={{ item.ssh_key }}
   with_items:
      - users.foo
      - users.foobar

Would this help

  • hosts: localhost
    vars:
    users:
  • name: benno
    last: joy
    host: abc
  • name: jj
    last: jb
    host: bcd
  • name: benz
    last: joy
    host: abc

tasks:

  • user: name=item.name
    with_items: users
    when: item.host == inventory_hostname

Instead of host maybe use a group