Case statement for setting var in Ansible/Jinja2

前端 未结 3 1554
眼角桃花
眼角桃花 2020-12-30 04:02

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\'

相关标签:
3条回答
  • 2020-12-30 04:11

    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.

    {{ {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") }}
    

    You can define a new variable the same way:

    {% 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:

    {"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:

    vars: 
       myDict:
         string1: a
         string2: b
       new_ansible_var: '{{myDict[existing_ansible_var | default("this key does not exist in the dict")] | default("") }}'
    
    0 讨论(0)
  • 2020-12-30 04:27

    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

    - name: Later task
      shell: "command is here"
      when: {{ existing_ansible_var }} == "string1"
    

    and get a profit

    0 讨论(0)
  • 2020-12-30 04:35

    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:

    - name: set default
      set_fact: new_ansible_var= ""
    
    - name: set to 'a'
      set_fact: new_ansible_var= "a"
      when: "{{ existing_ansible_var }} == string1"
    
    - name: set to 'b'
      set_fact: new_ansible_var= "b"
      when: "{{ existing_ansible_var }} == string2"
    

    etc.

    0 讨论(0)
提交回复
热议问题