Skip to content

Instantly share code, notes, and snippets.

@mikestankavich
Created February 24, 2017 14:31
Show Gist options
  • Select an option

  • Save mikestankavich/37030769deee90da0b08134ac72c9ac0 to your computer and use it in GitHub Desktop.

Select an option

Save mikestankavich/37030769deee90da0b08134ac72c9ac0 to your computer and use it in GitHub Desktop.
Ansible non-empty string conditional variants
---
# test scenario for task when conditional test for non-empty string
# example command line: ansible-playbook -i "localhost," is_not_empty.yml
- hosts: all
gather_facts: false
tasks:
# at this point foo is not defined, so we expect task to skip
# skips as expected
- name: Display value of foo with condition foo is defined and foo != ''
debug: var=foo
when: foo is defined and foo != ''
# skips as expected
- name: Display value of foo with condition foo | default(false)
debug: var=foo
when: foo | default(false)
# will return 'foo is not defined' error
- name: Display value of foo with condition foo
debug: var=foo
ignore_errors: true
when: foo
# will return 'foo is not defined' error
- name: Display value of foo with condition "{ {foo} }"
debug: var=foo
ignore_errors: true
when: "{{foo}}"
- set_fact: foo=''
# when foo contains empty string we expect task to be skipped
# skips as expected
- name: Display value of foo with condition foo is defined and foo != ''
debug: var=foo
when: foo is defined and foo != ''
# skips as expected
- name: Display value of foo with condition foo | default(false)
debug: var=foo
when: foo | default(false)
# skips as expected
- name: Display value of foo with condition foo
debug: var=foo
ignore_errors: true
when: foo
# skips as expected
- name: Display value of foo with condition "{ {foo} }"
debug: var=foo
ignore_errors: true
when: "{{foo}}"
- set_fact: foo='bar'
# when foo contains a string value we expect task to run
# runs as expected
- name: Display value of foo with condition foo is defined and foo != ''
debug: var=foo
when: foo is defined and foo != ''
# runs as expected
- name: Display value of foo with condition foo | default(false)
debug: var=foo
when: foo | default(false)
# curiously this when condition evaluates foo down to bar, then returns a 'bar is not defined' error
- name: Display value of foo with condition foo
debug: var=foo
ignore_errors: true
when: foo
# curiously this when condition evaluates foo down to bar, then returns a 'bar is not defined' error
- name: Display value of foo with condition "{ {foo} }"
debug: var=foo
ignore_errors: true
when: "{{foo}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment