ansible 提供额外变量作为嵌套 json [英] ansible supply extra-vars as nested json
问题描述
我正在尝试将 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.
Image、Version等可以直接指定,但是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
环境变量是在运行时选择的,因此无法直接在提供的额外变量中定义它们.剧本目前看起来是这样的:
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/ansible playbook 中使用 dict 的正确结构是使用 --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 提供额外变量作为嵌套 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!