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

Joe*_*Joe 3 ansible

我有一个我不拥有的任务(实际上是一个角色,但是在这里使用一个任务使示例变得容易),它对变量执行一些操作。假定变量是整数。我需要以某种方式将其传递给变量,并将其作为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!"
Run Code Online (Sandbox Code Playgroud)

我的剧本是:

- 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}}"
Run Code Online (Sandbox Code Playgroud)

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

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

这是在Ansible 2.6.4上

tec*_*raf 5

  1. 升级到Ansible 2.7(当前可作为stable-2.7分支机构使用,计划于2018年10月4日在Google Analytics(分析)中使用)。

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

  3. 将代码保留在问题中(例如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!"
}
Run Code Online (Sandbox Code Playgroud)

说明

当前,Jinja2模板返回的任何值都是字符串,因此,即使您在int内部使用了过滤器(如所示{{item.parameter | int}}),Ansible也始终将输出呈现为字符串。

Ansible 2.7将(通过上面的参数使用)Jinja 2.10的一个名为Native Python Types的功能并保留数据类型。