I want to conditionally define a variable in an Ansible playbook like this:
my_var: "{{ 'foo' if my_condition}}"
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:
fatal: [foo.local] => {'msg': 'AnsibleUndefinedVariable: One or more undefined
variables: the inline if-expression on line 1 evaluated
to false and no else section was defined.', 'failed': True}
Why is this an error anyway?
The complete case looks like this:
{role: foo, my_var: "foo"}
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?
This code may help you to define a variable with condition.
So here the
exists
will display only if the condition istrue
.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.
My example, after https://stackoverflow.com/a/43403229/5025060:
Because of the different sudo conventions used by Ubuntu versus other platforms, here I am telling Ansible to set a variable named
sudoGroup
tosudo
if the platform is Ubuntu, otherwise set it towheel
.Later in my playbook, I combine the variable with Ansible's
user
module to add eithersudo
orwheel
to an account's secondary groups depending on the OS Ansible is running on:NOTES:
{{ variable }}
are required in theuser: groups:
definition above.sudoGroup
as above in my playbook's globalvars:
section, Ansible configures it at run time (based onansible_distribution
) for each target I define in myhosts:
section.I believe you're after the
default(omit)
filter. (Reference).As per the example,
mode
will behave like it wasn't set at all for the first two items in the loop.