Case statement for setting var in Ansible/Jinja2

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:

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.

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 a default() 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:

Leave a Reply