FreeKB - ansible-playbook command - when (if else statement)
ansible-playbook command - when (if else statement)

Home > Search


This assumes you have installed Ansible Tower and are familiar with the ansible-playbook command.

A "when" statement (which is just like an if statement) can be used to do something when a condition evaluates to true or false.

when: <some condition>

 

For example, print "Hello World" when foo equals bar.

debug: msg="Hello World"
when: "foo == bar"

 

debug or fail can be used to print output to the console when a condition evaluates to true or false, 

 

do something when the foo variable is defined or undefined

when: "foo is defined"

when: "foo is undefined"

do something when the foo variable does or does not equal bar

when: "foo == 'bar'"

when: "foo != 'bar'"

do something when the foo variable does or does not contain bar

when: "foo is search('bar')"

when: "foo is not search('bar')"

 

When file exists / does not exist

The play will fail when the example.txt file does not exist.

- name: determine if example.txt exists
  stat:
    path: "/path/to/example.txt"
  register: foo

- fail: msg="example.txt does not exist"
  when: "foo.stat.exists == false"

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 4a9d1 in the box below so that we can be sure you are a human.




Comments