Ansible: 在数学运算期间,变量类型从int更改为字符串

创建于 2016-12-22  ·  1评论  ·  资料来源: ansible/ansible

问题类型

  • 错误报告
组件名称
可用版本
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
配置
操作系统/环境


Ubuntu 14.04
Ubuntu 16.04

概括

在操作过程中,int变量更改为字符串

重现步骤

- hosts: localhost
  vars:
    a: 1
    b: "{{ a }}"
    c: "{{ a+1 }}"
  tasks:
    - debug: msg="{{ a + 0 }}"
    - debug: msg="{{ b + 0 }}"
    - debug: msg="{{ c + 0 }}"
      ignore_errors: yes
    - debug: msg="{{ c + '0' }}"
预期成绩


第三个任务应该返回int 2,而第四个任务很可能会失败

实际结果


第三项任务失败

$ ansible-playbook a.yml -vvvvv
Using /etc/ansible/ansible.cfg as config file
 [WARNING]: provided hosts list is empty, only localhost is available

Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/__init__.pyc

PLAYBOOK: a.yml ****************************************************************
1 plays in a.yml

PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/core/system/setup.py
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: yurii
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python && sleep 0'
ok: [localhost]

TASK [debug] *******************************************************************
task path: /home/yurii/sandbox/ans/a.yml:7
ok: [localhost] => {
    "msg": "1"
}

TASK [debug] *******************************************************************
task path: /home/yurii/sandbox/ans/a.yml:8
ok: [localhost] => {
    "msg": "1"
}

TASK [debug] *******************************************************************
task path: /home/yurii/sandbox/ans/a.yml:9
fatal: [localhost]: FAILED! => {
    "failed": true, 
    "msg": "Unexpected templating type error occurred on ({{ c + 0 }}): coercing to Unicode: need string or buffer, int found"
}
...ignoring

TASK [debug] *******************************************************************
task path: /home/yurii/sandbox/ans/a.yml:11
ok: [localhost] => {
    "msg": "20"
}

PLAY RECAP *********************************************************************
localhost                  : ok=5    changed=0    unreachable=0    failed=0   
affects_2.2 bug

最有用的评论

这实际上只是Jinja的乐趣-因为您将不总是知道var的来源(例如,命令行-e var不会进行YAML类型推断,因此始终是字符串),因此需要断言/强制执行数学运算之前。 正确的方法是:

- debug: msg="{{ c | int + 0 }}"

>所有评论

这实际上只是Jinja的乐趣-因为您将不总是知道var的来源(例如,命令行-e var不会进行YAML类型推断,因此始终是字符串),因此需要断言/强制执行数学运算之前。 正确的方法是:

- debug: msg="{{ c | int + 0 }}"
此页面是否有帮助?
0 / 5 - 0 等级