Conditionally define variable in Ansible


I want to conditionally define a variable in an Ansible playbook like this:

I would like the variable to remain undefined if the condition does not resolve to true.

Ansible gives the following error if I try to execute the code:

Why is this an error anyway?

The complete case looks like this:

If my_var is defined, the role does something special. In some cases, I don’t want the role to do this. I could use when: condition, but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the “interface” to the role.

Any ideas?


You could use something like this:

The ‘else’ will happen if condition not match, and in this case will set a empty value for the variable. I think this is a short, readable and elegant solution.

Leave a Reply