代码之家  ›  专栏  ›  技术社区  ›  Joe

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

  •  1
  • Joe  · 技术社区  · 6 年前

    我有一个我没有的任务(实际上是一个角色,但是在这里使用一个任务来简化示例),它对一个变量执行一些操作。它假定变量是整数。我需要以某种方式给它传递一个变量,让它以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公司

    2 回复  |  直到 6 年前
        1
  •  16
  •   techraf    6 年前

    1. 升级至Ansible 2.7(目前作为 stable-2.7 scheduled for GA on Oct. 4th, 2018 ).

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

    解释

    int {{item.parameter | int}} )输出总是由Ansible呈现为字符串。

    Ansible 2.7 will use (使用上述参数)调用了jinja2.10的一个特性 Native Python Types 并保留数据类型。

        2
  •  0
  •   Kelson Silva    6 年前

    当你发送变量的时候 include 任务,它变成 甚至强迫 在你的剧本上。所以你需要使用 内景

    frob.yml公司

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