Question:
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:
1 2 3 4 5 6 7 8 |
if {{ existing_ansible_var }} == "string1" new_ansible_var = "a" else if {{ existing_ansible_var }} == "string2" new_ansible_var = "b" <...> else new_ansible_var = "" |
Is there a simpler way to do this?
Answer:
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 with existing_ansible_var
.
1 2 |
{{ {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") }} |
You can define a new variable the same way:
1 2 |
{% set new_ansible_var = {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") -%} |
In case existing_ansible_var
might not necessarily be defined, you need to catch this with a default()
which does not exist in your dict:
1 2 |
{"string1": "a", "string2": "b"}[existing_ansible_var | default("this key does not exist in the dict")] | default("") |
You as well can define it in the playbook and later then use new_ansible_var
in the template:
1 2 3 4 5 6 |
vars: myDict: string1: a string2: b new_ansible_var: '{{myDict[existing_ansible_var | default("this key does not exist in the dict")] | default("") }}' |