list 如何在ansible清单文件中将列表值指定为变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18572092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How specify a list value as variable in ansible inventory file?
提问by rmuller
I need something like (ansible inventory file):
我需要类似的东西(ansible库存文件):
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL"
However, ansible does not recognize 'locales' as a list.
但是,ansible 不会将“语言环境”识别为列表。
回答by Ryler Hockenbury
You can pass a list or object like this:
您可以像这样传递列表或对象:
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales='["en_US", "nl_NL"]'
回答by Lorin Hochstein
With complex variables, it's best to define them in a host_vars file rather than in the inventory file, since host_vars files support YAML syntax.
对于复杂变量,最好在 host_vars 文件中而不是在清单文件中定义它们,因为 host_vars 文件支持 YAML 语法。
Try creating a host_vars/127.0.0.1
file with the following content:
尝试创建一个host_vars/127.0.0.1
包含以下内容的文件:
timezone: Europe/Amsterdam
locales:
- en_US
- nl_NL
回答by Sparky
Ryler's answer is good in this specific case but I ran into problems using other variations with the template module.
在这种特定情况下,Ryler 的回答很好,但我在使用模板模块的其他变体时遇到了问题。
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales='["en_US", "nl_NL"]'
Is his original example and works fine.
是他的原始示例并且工作正常。
The following variations work with template. Basically if it's a string you must remember to use the internal double quotes or the entire structure is parsed as a single string. If it's only numbers or "True" or "False" (not "yes") then you're fine. In this variation I couldn't make it work with template if it had external quotes.
以下变体适用于模板。基本上,如果它是一个字符串,您必须记住使用内部双引号或整个结构被解析为单个字符串。如果它只是数字或“真”或“假”(不是“是”),那么你没问题。在这个变体中,如果它有外部引号,我就不能让它与模板一起工作。
I haven't done an exhaustive check of which internal use cases they do and do not break other than the template module.
除了模板模块之外,我还没有对它们执行哪些内部用例并且不破坏哪些内部用例进行详尽的检查。
I am using Ansible 2.2.1.
我正在使用 Ansible 2.2.1。
[example:vars]
# these work
myvar1=["foo", "bar"]
myvar2=[1,2]
myvar3=[True,False]
# These fail, they get interpreted as a single string.
myvar4=[yes, no]
myvar5=[foo,bar]
myvar6='["foo", "bar"]'
回答by jollychang
you can try split
你可以尝试拆分
#inventory file
[example]
127.0.0.1 timezone="Europe/Amsterdam" locales="en_US","nl_NL"
#role file
---
- debug: msg="{{ item }}"
with_items: locales.split(',')
回答by linbo
You can custom a filter, to split string to list
您可以自定义过滤器,将字符串拆分为列表
Github ansible exampleshow how to create custom filter.
Github ansible 示例展示了如何创建自定义过滤器。