3

I'm trying to set a variable in an Ansible playbook based on an existing variable's value which could be one of many different strings. It's basically a case/switch statement and this is the logic (with incorrect syntax):

if {{ existing_ansible_var }} == "string1"
  new_ansible_var = "a"
else if {{ existing_ansible_var }} == "string2"
  new_ansible_var = "b"
<...>
else
  new_ansible_var = ""

I can use a pretty slick technique with a dictionary that looks like this in Jinja:

{% set new_ansible_var = {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") -%}

Can I use a similar dictionary construct to set a variable (set_fact) in a playbook?

s g
  • 5,289
  • 10
  • 49
  • 82
  • 1
    possible duplicate of [Case statement for setting var in Ansible/Jinja2](http://stackoverflow.com/questions/30637054/case-statement-for-setting-var-in-ansible-jinja2) – Bruce P Jun 08 '15 at 19:51
  • You already asked virtually the same question [here](http://stackoverflow.com/questions/30637054/case-statement-for-setting-var-in-ansible-jinja2/30642550#30642550) four days ago and got a number of responses to that question. – Bruce P Jun 08 '15 at 19:51

1 Answers1

3

As described in the other question/answer, you can do it like this:

vars: 
   myDict: {"string1": "a", "string2": "b"}
   new_ansible_var: '{{myDict[existing_ansible_var | default("this key does not exist in the dict")] | default("") }}'
Community
  • 1
  • 1
udondan
  • 57,263
  • 20
  • 190
  • 175