Logical operators in jinja template

Question:

Been pulling my hair out trying to use the "or" logical operator in a cloud-init jinja template.

When I use:
{% if distro == 'centos' or 'redhat' %} {% set group = 'wheel' %}

cloud-init just ignores the directive.

If I use separate if statements, (see below) then I get the desired result.

I have tried with {% "value" or "value" %} and {% value or value %}, and the line is always ignored.

Example snippet of the code:

    ## template: jinja
    #cloud-config
    {% set u1 = 'myuser' %}
    {% set u1pass = 'strong-passwd' %}
    {% set u1key = 'key1' %}
    {% set u2 = 'example' %}
    {% set u2pass = 'passwd2' %}
    {% set u2key = 'key2' %}
    .............
    {% if distro == 'centos' %}
    {% set group = 'wheel' %}
    {% elif distro == 'rocky' %}
    {% set group = 'wheel' %}
    {% elif distro == 'ubuntu' or 'debian' %}
    {% set group = 'sudo' %}
    {%- endif %}
    distro: {{distro}}
    user1: {{u1}}
    user2: {{u2}}
    group: {{group}}
## Add users
  - name: {{ u1 }}
    groups: {{ group }}
    lock_passwd: false
    passwd: {{ u1pass }}
    ssh_authorized_keys:
      - {{ u1key }}
    shell: /bin/bash
  - name: {{ u2 }}
    groups: {{ group }}
    lock_passwd: false
    passwd: {{ u2pass }}
    ssh_authorized_keys:
      - {{ u2key }}
    shell: /bin/bash`

`

I am trying to set jinja variables based on metadata values passed in from the datasource (LXD in my case) to dynamically build the user-data configuration, but can’t seem to get the or logical operator to play well. Am I just stuck using separate if statements per metadata value? Thanks

{% if distro == 'centos' or 'redhat' %} {% set group = 'wheel' %}

Expecting:
distro: redhat
user1: myuser
user2: example
group: wheel

Asked By: dj423

||

Answers:

Have you tried

{% if distro == 'centos' or distro == 'redhat' %}
Answered By: Eleno
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.