Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally define variable in Ansible

Tags:

ansible

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?

like image 700
Christian Avatar asked Jul 09 '15 07:07

Christian


People also ask

Can we define multiple conditions in Ansible?

Defining multiple when conditions in Ansible I want to reboot Debian or Ubuntu Linux system after kernel update, and the inventory hostname must be aws-proxy-server . If both conditions are true, then issue the reboot command using the Ansible reboot module. Otherwise, skip the reboot option.

When Ansible variable is defined?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. tasks: - shell: echo "I've got '{{ foo }}' and am not afraid to use it!" when: foo is defined - fail: msg="Bailing out. this play requires 'bar'" when: bar is undefined.


Video Answer


1 Answers

You could use something like this:

my_var: "{{ 'foo' if my_condition else '' }}" 

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.

like image 65
mhalano Avatar answered Oct 04 '22 11:10

mhalano