Case statement for setting var in Ansible/Jinja2 -
i'm using ansible jinja2 templates, , scenario can't find solution in ansible's documentation or googling around jinja2 examples. here's logic want 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 combining several techniques, variable assignment here: set variable in jinja, conditional comparison here: http://jinja.pocoo.org/docs/dev/templates/#if-expression, , defaulting filter here: https://docs.ansible.com/playbooks_filters.html#defaulting-undefined-variables ,
...but feel that's overkill. there simpler way this?
if want output value in template depending on value of existing_ansible_var
use dict , feed existing_ansible_var
.
{{ {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") }}
you can define new variable same way:
{% set new_ansible_var = {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") -%}
in case existing_ansible_var
might not defined, need catch default()
not exist in dict:
{"string1": "a", "string2": "b"}[existing_ansible_var | default("this key not exist in dict")] | default("")
you can define in playbook , later use new_ansible_var
in template:
vars: mydict: {"string1": "a", "string2": "b"} new_ansible_var: '{{mydict[existing_ansible_var | default("this key not exist in dict")] | default("") }}'
Comments
Post a Comment