我有一个我不拥有的任务(实际上是一个角色,但在这里使用任务是为了使示例更容易),它对变量进行一些操作。它假设变量是整数。我需要以某种方式向它传递一个变量并将其作为 int 传递,但我没有任何运气。
这是我不拥有的任务的超级简化版本:
frob.yml
- name: Validate that frob_count is <= 100
fail: msg="{{frob_count}} is greater than 100"
when: frob_count > 100
- name: Do real work
debug: msg="We frobbed {{frob_count}} times!"
我的剧本是:
- name: Frob some things
hosts: localhost
vars:
things:
- parameter: 1
- parameter: 2
- parameter: 45
tasks:
- with_items: "{{things}}"
include: frob.yml
vars:
frob_count: "{{item.parameter}}"
无论如何,我都会收到“1 大于 100”之类的错误frob.yml
。看起来它正在将 var 作为字符串而不是整数获取。
我尝试过类似的东西frob_count: "{{item.parameter | int}}"
没有运气。如果我可以改变frob.yml
这很容易,但就像我说的,这是我无法控制的。有什么想法吗?
这是 Ansible 2.6.4 上的
Solution
升级到 Ansible 2.7(目前可用stable-2.7 https://github.com/ansible/ansible/tree/stable-2.7分支,计划于 2018 年 10 月 4 日举行大会 https://docs.ansible.com/ansible/devel/roadmap/ROADMAP_2_7.html#release-schedule).
Add jinja2_native=True
to the [defaults]
的部分ansible.cfg
(或者设置一个环境变量ANSIBLE_JINJA2_NATIVE=True
.
保留问题中的代码(即frob_count: "{{item.parameter}}"
).
结果:
TASK [Do real work] **********************************************************************************************************************
ok: [localhost] => {
"msg": "We frobbed 1 times!"
}
TASK [Validate that frob_count is <= 100] ************************************************************************************************
skipping: [localhost]
TASK [Do real work] **********************************************************************************************************************
ok: [localhost] => {
"msg": "We frobbed 2 times!"
}
TASK [Validate that frob_count is <= 100] ************************************************************************************************
skipping: [localhost]
TASK [Do real work] **********************************************************************************************************************
ok: [localhost] => {
"msg": "We frobbed 45 times!"
}
解释
目前 Jinja2 模板返回的任何值都是字符串,所以即使您使用int
内部过滤器(如{{item.parameter | int}}
)输出始终由 Ansible 呈现为字符串。
Ansible 2.7 将使用 https://github.com/ansible/ansible/pull/32738(使用上述参数)Jinja 2.10 的一个功能称为原生 Python 类型 http://jinja.pocoo.org/docs/2.10/nativetypes/并保留数据类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)