• Home
  • Recent Q&A
  • Java
  • Cloud
  • JavaScript
  • Python
  • SQL
  • PHP
  • HTML
  • C++
  • Data Science
  • DBMS
  • Devops
  • Hadoop
  • Machine Learning
in Ansible by
Q:
Ansible when

1 Answer

0 votes
by
Ansible ‘When’ Statement: Check If Variable Is…

Check if Ansible variable is defined (exists):

tasks:

- shell: echo "The variable 'foo' is defined: '{{ foo }}'"

  when: foo is defined

- fail: msg="The variable 'bar' is not defined"

  when: bar is undefined

Check if Ansible variable is empty:

tasks:

- fail: msg="The variable 'bar' is empty"

  when: bar|length == 0

- shell: echo "The variable 'foo' is not empty: '{{ foo }}'"

  when: foo|length > 0

Check if Ansible variable is defined and not empty:

tasks:

- shell: echo "The variable 'foo' is defined and not empty"

  when: (foo is defined) and (foo|length > 0)

- fail: msg="The variable 'bar' is not defined or empty"

  when: (bar is not defined) or (bar|length == 0)

Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →

Check if Ansible variable is True or False:

tasks:

- shell: echo "The variable 'foo' is 'True'"

  when: foo|bool == True

- shell: echo "The variable 'bar' is 'False'"

  when: bar|bool == False

Related questions

0 votes
0 votes
asked Aug 24, 2019 in Ansible by rahulsharma
0 votes
asked Aug 24, 2019 in Ansible by rahulsharma
...