Ansible: Conditionally define variables in vars file if a certain condition is met

ansibleautomationjinja

Depending on the value(True/False) of a variable defined into the group_vars I am trying to define some variables in a vars file. Their value depends on the group var's value.

My current var file looks like this:

{% if my_group_var %}
test:
   var1: value
   var2: value
   ...
   varn: value
{% else %}
test:
   var1: other_value
   var2: other_value
   ...
   varn: other_value
{% endif %}

For each one of my roles I'm using a variable defined into this file.

My test playbook looks like below:

- name: blabla
  hosts: blabla
  vars_files:
     - <path>/test_vars.yml
  roles: blabla 

The error I'm receiving after running the playbook is:

{% if my_group_var %}
 ^ here

exception type: <class 'yaml.scanner.ScannerError'>
exception: while scanning for the next token
found character that cannot start any token
  in "<unicode string>"

Am I doing something stupid here or this is not even supported? I've tried to find another way for defining these vars(I have a lot of them) but I didn't managed to get something functional here. Any suggestions?

Best Answer

Ansible allows one of following forms to define variable conditionally:

    test:
      var1: "{% if my_group_var %}value{% else %}other_value{% endif %}"
      var2: "{{'value' if (my_group_var) else 'other_value'}}"

Combining above syntax with vars lookup we can load complex vars (map in this case):

test_value_when_my_group_var_is_true:
   var1: value
   var2: value

test_value_when_my_group_var_is_false:
   var1: other_value
   var2: other_value

test: "{{ lookup('vars','test_value_when_my_group_var_is_true') if (my_group_var) else lookup('vars','test_value_when_my_group_var_is_false')}}"

There is another way of doing conditional tree loading with vars lookup. This way is handy when you need implement case logic (i.e. condition variable has more than two possible values):

test_value_when_my_group_var_is_foo:
   var1: value
   var2: value

test_value_when_my_group_var_is_bar:
   var1: other_value
   var2: other_value

test_value_when_my_group_var_is_baz:
   var1: yet_another_value
   var2: yet_another_value

test: "{{ lookup('vars','test_value_when_my_group_var_is_' + my_group_var) }}"