when: state is present from variable dict hash list

28 views
Skip to first unread message

Chris Short

unread,
Mar 18, 2016, 8:59:36 AM3/18/16
to Ansible Project
I have the following defined in group_vars and I'm trying to run a task when the state is defined as present and the syntax is baffling me:

staff:
  - { netid: user001, uid: 12345, comment: "Chris Short", state: present }
  - { netid: user002, uid: 12346, comment: "Bob Jones", state: absent }

The play is like this:

- name: Do Something
  shell: script.sh
  with_items:
    - "{{ oristaff }}"
  when: ori_staff.state  == 'present'

I've tried several different ways to ascertain state and none of them have worked so far. 

Brian Coca

unread,
Mar 18, 2016, 9:48:22 AM3/18/16
to ansible...@googlegroups.com
you are referencing it incorrectly, staff is a list not a dictionary, also I think you want the "current item's state":

when: item.state == 'present'

assuming you want to execute the task only for those entries that have that state.


----------
Brian Coca

Chris Short

unread,
Mar 18, 2016, 9:57:29 AM3/18/16
to Ansible Project
Thank you, bcoca. Helpful as always!

Uditha Desilva

unread,
Mar 18, 2016, 4:00:12 PM3/18/16
to Ansible Project
You may have a typo or 2 in your sample case. This works fine for me:

$ cat tst.yml
---
- hosts: localhost
  vars:
        staff:
          - { netid: user001, uid: 12345, comment: "Chris Short", state: present }
          - { netid: user002, uid: 12346, comment: "Bob Jones", state: absent }

  tasks:

    - name: Do Something
      shell: "echo 'present: {{ item.netid }}'"
      with_items:
        - "{{ staff }}"
      when: item.state == 'present'
$ ansible-playbook tst.yml

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [Do Something] ************************************************************
changed: [localhost] => (item={u'comment': u'Chris Short', u'state': u'present', u'uid': 12345, u'netid': u'user001'})
skipping: [localhost] => (item={u'comment': u'Bob Jones', u'state': u'absent', u'uid': 12346, u'netid': u'user002'})

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

Reply all
Reply to author
Forward
0 new messages