dzbeda
dzbeda

Reputation: 303

Ansible: Jinja2 template test both a variable is defined and not empty

I have a variable, let call it value1, and a Jinja2 template. The Jinja2 template includes the following line:

LINE=” This string must be included this string is optional= {{ value1}}”

What I need to implement: If value1 is defined with a string – let assume that the string is OK (Value1: OK), the file should be

LINE=” This string must be included this string is optional= OK”

If value1 is not defined (empty Value1: ), the file should be

LINE=” This string must be included”

So how the Jinja2 should be configured?

Upvotes: 1

Views: 5904

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

Q: "If value1 is not defined (empty Value1: ), the file should be LINE=” This string must be included”"

A: Test the variable is both defined and not empty, e.g.

shell> cat test.txt.j2
{% if value1 is defined and value1|d('')|length > 0 %}
LINE=” This string must be included this string is optional= {{ value1 }}”
{% else %}
LINE=” This string must be included”
{% endif %}
shell> cat playbook.yml
- hosts: localhost
  tasks:
    - template:
        dest: test.txt
        src: test.txt.j2

Running the playbook without value1 defined or with empty value1

shell> ansible-playbook playbook.yml
shell> ansible-playbook playbook.yml -e value1=''

gives

shell> cat test.txt
LINE=” This string must be included”

When the variable is both defined and not empty, e.g.

shell> ansible-playbook playbook.yml -e value1=OK

gives

shell> cat test.txt
LINE=” This string must be included this string is optional= OK”

Upvotes: 1

Related Questions