I'm using Ansible with Jinja2 templates, and this is a scenario that I can't find a solution for in Ansible's documentation or googling around for Jinja2 examples. Here's the logic that I want to achieve in Ansible:
if {{ existing_ansible_var }} == "string1"
new_ansible_var = "a"
else if {{ existing_ansible_var }} == "string2"
new_ansible_var = "b"
<...>
else
new_ansible_var = ""
I could probably do this by combining several techniques, the variable assignment from here: Set variable in jinja, the conditional comparison here: http://jinja.pocoo.org/docs/dev/templates/#if-expression, and the defaulting filter here: https://docs.ansible.com/playbooks_filters.html#defaulting-undefined-variables ,
...but I feel like that's overkill. Is there a simpler way to do this?
you don't need to set var, because I'm guessing that you trying to set var for some condition later. Just make condition there like
and get a profit
Something like this would work, but it's ugly. And as @podarok mentioned in his answer, it's likely unnecessary depending on exactly what you're attempting to do:
etc.
If you just want to output a value in your template depending on the value of
existing_ansible_var
you simply could use a dict and feed it withexisting_ansible_var
.You can define a new variable the same way:
In case
existing_ansible_var
might not necessarily be defined, you need to catch this with adefault()
which does not exist in your dict:You as well can define it in the playbook and later then use
new_ansible_var
in the template: