Using with_dict but skipping certain items

13 views
Skip to first unread message

David Stewart

unread,
Dec 7, 2015, 11:15:04 AM12/7/15
to Ansible Project
Hi,

I am new to Ansible and am having difficulty in understanding how a loop created with a 'with_dict' directive can be filtered based upon values within the dictionary.

For instance, I want a dictionary of users that need to be put into a specific state, e.g.:

users:
  testuser1: {state: absent,  public_key_file: "../keys/dev-env.pub"}
  testuser2: {state: present, public_key_file: "../keys/dev-env.pub"}

I then have a task that loops over this map:

- name: Manage Users
  user:
    name={{ item.key }}
    state={{ item.value.state }}
    remove=yes
  with_dict: users | default({})

This will add or remove users depending on the 'users' dictionary (e.g. testuser1 will be removed and testuser2 created)

I now want to use the same data definition to loop over users and put any authorized keys in place:

- name: Deploy User Keys
  sudo: yes
  authorized_key:
    user={{ item.key }}
    key="{{ lookup('file', item.value.public_key_file) }}"
  with_dict: users | default({})

this would work apart from the fact that the 'testuser1' home dir no longer exists.

What I would like to do is to skip users with a 'state' of 'absent'. Is there a way to do this or am I going about this in completely the wrong way? 

Thanks,
Dave.  
Reply all
Reply to author
Forward
0 new messages