【问题标题】:Create and access dict in Ansible playbook在 Ansible playbook 中创建和访问 dict
【发布时间】:2015-08-23 10:13:30
【问题描述】:

我正在尝试根据现有变量的值在 Ansible 剧本中设置一个变量,该值可能是许多不同字符串之一。它基本上是一个 case/switch 语句,这是逻辑(语法不正确):

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

我可以在 Jinja 中使用一种非常巧妙的技术和一个看起来像这样的字典:

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

我可以使用类似的字典结构在剧本中设置变量 (set_fact) 吗?

【问题讨论】:

标签: ansible ansible-playbook


【解决方案1】:

如其他question/answer中所述,您可以这样做:

vars: 
   myDict: {"string1": "a", "string2": "b"}
   new_ansible_var: '{{myDict[existing_ansible_var | default("this key does not exist in the dict")] | default("") }}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多