For 2.0 How to test if variable set to null in when clause

125 views
Skip to first unread message

Michael Baydoun

unread,
Jan 19, 2016, 9:43:51 AM1/19/16
to Ansible Project
pre 2.0

set_fact:
  uberHost: "{{ ansible_ssh_host }}"
when: ansible_ssh_host is defined

set fact:
  uberHost: "{{ inventory_hostname }}"
when: ansible_ssh_host is not defined


Post 2.0, changed to use ansible_host
uberHost is always getting set to null
ansible_host is defined and set to null even when it's not present in the inventory file
I haven't figured out how to test to see if ansible_host is null in a when clause.


Matt Martz

unread,
Jan 19, 2016, 9:56:29 AM1/19/16
to ansible...@googlegroups.com
It should be enough to just check:

when: ansible_ssh_host

However it may be good to come at it from a little different direction and use something like:

set_fact:
    uberHost: "{{ ansible_ssh_host|default(inventory_hostname, True) }}"

The True in default() will tell jinja2 to use pythons truthyness checks, so an empty string evaluates as false as well.

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/ce3c97d5-f321-4ab6-868f-e83a11aa863f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
Matt Martz
@sivel
sivel.net

Brian Coca

unread,
Jan 19, 2016, 10:03:52 AM1/19/16
to Ansible Project
you can even chain them and make it future proof
set_fact:
uberHost: "{{
ansible_host|default(ansible_ssh_host|default(inventory_hostname,
True), True) }}"
> https://groups.google.com/d/msgid/ansible-project/CAD8N0v8bGu5GQSjKHJfKpXeir8vBnxoR0jhH6f6%2Bgkp3qAOOYw%40mail.gmail.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
Brian Coca

Michael Baydoun

unread,
Jan 19, 2016, 11:38:18 AM1/19/16
to Ansible Project
when: ansible_host still caused the set_fact to execute when it was not present / null

However, the other suggestions worked great, thanks!


Reply all
Reply to author
Forward
0 new messages