问题描述
我正在尝试将ansible用于参数化的docker部署.我希望能够通过命令行指定图像,版本和各种不同的环境变量.
I'm trying to use ansible for a parameterised docker deployment. I want to be able to specify image, version and various different environment variables via the command line.
图像,版本等可以直接指定,但是docker模块的env参数需要字典.这是一个简短的剧本示例:
Image, Version and so on can be specified directly but the env parameter of the docker module requires a dictionary. Here is a shortened playbook example:
-name: some deployment
docker:
[..]
name: myname
[..]
env:
FOO: bar
ANOTHERFOO: anotherbar
在运行时选择环境变量,因此无法在提供的额外var中直接定义它们.该剧本目前看起来像这样:
The environment variables are choosen during runtime, so it is not possible to define them directly in the supplied extra vars. The playbook looks like this at the moment:
-name: some deployment
docker:
[..]
name: "{{ name }}"
[..]
env: "{{ env }}"
由于env是嵌套字典,因此我们需要提供--extra-vars作为嵌套json.我希望以下方法能起作用:
Since env is a nested dictionary we need to supply the --extra-vars as nested json. I would expected the following to work:
./ansible-playbook [..] --extra-vars '{"name":"myname", "env":{"FOO":"bar", "ANOTHERFOO":"anotherbar"}}' [..]
容器运行后,env的值不存在.直接在剧本中提供json以进行测试是可行的.
After the container is running, the values of env are not there.Supplying the json directly in the playbook for testing purposes works.
我尝试了以下不同的json,但没有任何效果:
I tried the following different json with no working results:
{"name":"myname", "env":{"FOO":"bar", "ANOTHERFOO":"anotherbar"}}
{"name":"myname", "env":[{"FOO":"bar"}, {"ANOTHERFOO":"anotherbar"}]}
如何通过命令行提供和使用嵌套字典,或者这是Jinja2模板引擎的局限性.
How do you supply and use a nested dictionary via command line or is this a limitation of the Jinja2 template engine.
推荐答案
如果需要在YAML/可使用的剧本中使用字典,则使用的正确结构是--extra-vars提供的嵌套json,如问题示例中所示:
The right structure to use if you need a dict in your YAML/ansible playbook is a nested json supplied with --extra-vars like in the questions example:
./ansible-playbook [..] --extra-vars '{"name":"myname", "env":{"FOO":"bar", "ANOTHERFOO":"anotherbar"}}' [..]
和
-name: some deployment
docker:
[..]
name: "{{ name }}"
[..]
env: "{{ env }}"
出于测试目的,我确实在系统上使用了environment
,我将其简称为env
.问题是environment
是保留变量,并且始终会被覆盖.
For testing purposes I did use environment
on my system which I shortened to env
as an example. The problem is environment
is a reserved variable and always gets overridden.
这篇关于Ansible提供Extra-vars作为嵌套json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!