将整数变量传递给任务而不会丢失整数类型

时间:2018-09-24 21:08:16

标签: ansible

我不拥有一个任务(实际上是一个角色,但是在这里使用一个任务使示例更加容易),它对变量执行一些操作。假定变量是整数。我需要以某种方式将其传递给变量,并将其作为整数传递,而我没有任何运气。

这是我不拥有的任务的超级简化版本:

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}}"

无论如何,我从frob.yml中收到类似“ 1大于100”的错误。看起来它把var作为字符串而不是整数。

我尝试过frob_count: "{{item.parameter | int}}"之类的事情,但是没有运气。如果我可以更改frob.yml,那很容易,但是就像我说的那样,这是我无法控制的。有什么想法吗?

这是在Ansible 2.6.4上

3 个答案:

答案 0 :(得分:3)

解决方案

  1. 升级到Ansible 2.7(当前可作为stable-2.7分支,scheduled for GA on Oct. 4th, 2018)。

  2. jinja2_native=True添加到[defaults]的{​​{1}}部分中(或设置环境变量ansible.cfg

  3. 将您的代码保留在问题中(即ANSIBLE_JINJA2_NATIVE=True)。

结果:

frob_count: "{{item.parameter}}"

说明

当前,Jinja2模板返回的任何值都是字符串,因此,即使您在内部使用了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!" } 过滤器(如int),Ansible也始终将输出呈现为字符串。

Ansible 2.7 will use(具有上述参数)是Jinja 2.10的一项名为Native Python Types的功能,并保留了数据类型。

答案 1 :(得分:0)

通过该include任务发送变量时,它甚至变成 int 在您的剧本上成为 unicode 。因此,您需要像这样在frob.yml上使用 int 过滤器:

frob.yml

- name: Validate that frob_count is <= 100
  fail: msg="{{frob_count}} is greater than 100"
  when: frob_count|int > 100

答案 2 :(得分:0)

我找到了一个似乎有效的解决方案,它不需要 ANSIBLE_JINJA2_NATIVE=True 环境变量

如果不是

initialDelaySeconds: "{{ _initialDelaySeconds }}"

你愿意

initialDelaySeconds: |
    {{ _initialDelaySeconds }}

jinja 模板中可以省略 " 并且不会将值转换为字符串!