Thibault Richard
Thibault Richard

Reputation: 382

Define variable in Ansible according complex condition

I need to define a variable in ansible according several conditions

I know the syntax

VARtodefined: "{{ 'Value1' if condition1 else 'Value2' }}"

I know I have the same result with the following other syntax

VARtodefined: "{% if condition1 %}'Value1'{% else %}'Value2'{% endif %}"

but I don't find the correct syntax for multiple condition (if-elsif-elsif-else)

I have for instance tried this without success

VARtodefined: "{% if condition1 %}'Value1'{% elsif condition2 %}'Value2'{% else %}'Value3'{% endif %}"

If have tried variant with elif, elseif but also without success

In my specific case condition1 is OtherVar==XXX and condition2 OtherVar==YYY (so in both case it depends the value of OtherVar)

So I'm looking for a working solution for this

VARtodefined: "{% if OtherVar==XXX %}'Value1'{% elsif  OtherVar==YYY%}'Value2'{% else %}'Value3'{% endif %}"

If have found a workaround to achieve my goal but I'm interested to know the correct syntax for future projects

Upvotes: 0

Views: 1105

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68004

The example of the correct syntax is below. The task

    - debug:
        msg: "{% if item=='XXX' %}Value1
              {% elif  item=='YYY' %}Value2
              {% else %}Value3
              {% endif %}"
      loop: [XXX, ZZZ]

gives

  msg: 'Value1 '
  msg: 'Value3 '

A simpler solution is putting the logic into a dictionary. For example

conditions:
  XXX: Value1
  YYY: Value2
  default: Value3

Then, use it

  - set_fact:
      VARtodefined: "{{ conditions[OtherVar]|
                        default(conditions.default) }}"

Upvotes: 2

ilias-sp
ilias-sp

Reputation: 6685

this is the expected syntax: if - elif/else - endif

please see and try example PB below:

---
- hosts: localhost
  gather_facts: false
  vars:
    X: 2

  tasks:
  - set_fact:
      VARtodefined: "{% if X == 1 %}Value1{% elif X == 2 %}Value2{% else %}Value3{% endif %}"
    
  - debug:
      var: VARtodefined

Upvotes: 1

Related Questions