Lookup if a value is in a dictionary then perform a task (using when/conditional)

52 views
Skip to first unread message

Cody Robertson

unread,
Dec 19, 2014, 6:46:35 PM12/19/14
to ansible...@googlegroups.com
Hello,

Hopefully I'm not overlooking this but is there a way to lookup if a value is in a dictionary - if it is perform a task using the "when" keyword? For example I want to have a certain task only run if the {{ ansible_fqdn }} is in the dictionary.

licensed_hosts:
  - test001.example.com
  - test002.example.com

tasks:
  - debug: msg="This should only run on test002.example.com"
    when: <somehow lookup {{ ansible_fqdn }} in licensed_hosts>

Thanks!

Brian Coca

unread,
Dec 19, 2014, 7:35:43 PM12/19/14
to ansible...@googlegroups.com
First, licensed_hosts is actually a list, not a dictionary, the dash
(-) signifies 'list item'

Second, you don't need to lookup ansible_fqdn as that should be part
of fact gathering which isnormally automatic, so this should "just
work":

tasks:
- debug: msg="This should only run on test002.example.com"
when: "{{ ansible_fqdn in licensed_hosts}}"

--
Brian Coca

Cody Robertson

unread,
Dec 19, 2014, 7:46:36 PM12/19/14
to ansible...@googlegroups.com
Hi Brian,

My verbiage is pretty poor when it comes to YAML - thanks for clarifying!

Since ansible_fqdn is automatically gathered I was referring to looking to see if that variable / fact was in a list. Your example worked perfectly! I'll make sure to try to look into the Jinja2 expressions a bit further in the future.

Thanks a ton!
Reply all
Reply to author
Forward
0 new messages