简体   繁体   English

在Ansible剧本中创建和访问字典

[英]Create and access dict in Ansible playbook

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. 我正在尝试根据现有变量的值在Ansible剧本中设置一个变量,该变量可能是许多不同的字符串之一。 It's basically a case/switch statement and this is the logic (with incorrect syntax): 这基本上是一个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 = ""

I can use a pretty slick technique with a dictionary that looks like this in Jinja: 我可以在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? 我可以使用类似的字典构造在剧本中设置变量( set_fact )吗?

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("") }}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM