【发布时间】:2020-09-08 00:02:49
【问题描述】:
我在 Python 3.8.4 上使用 Ansible 2.9.13
在 Ansible 剧本中,我有一个字典列表,我想只循环 pct_used 值大于 90 的项目子集。
这是一个说明它的剧本:
---
- hosts: localhost
gather_facts: False
vars:
usage_records: [{mount: "/abc", pct_used: "50"}, {mount: "/def", pct_used: "75"}, {mount: "/ghi", pct_used: "95"}]
tasks:
- name: process just records with more than 90 percent usage
debug:
msg: "{{ item }}"
loop: "{{ usage_records|selectattr('pct_used','ge', 90)|list }}"
但如果我运行它,它会抱怨 pct_used 值是 AnsibleUnicode 字符串而不是整数:
TASK [process just records with more than 90 percent usage] ************************************************************
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ usage_records|selectattr('pct_used','ge', 90)|list }}): '>=' not supported between instances of 'AnsibleUnicode' and 'int'"}
现在,我意识到问题在于字典中的 pct_used 值是字符串而不是 int。如果我重写了usage_records 定义行,而数字周围没有引号:
usage_records: [{mount: "/abc", pct_used: 50}, {mount: "/def", pct_used: 75}, {mount: "/ghi", pct_used: 95}]
它确实按预期工作:
ok: [localhost] => (item={'mount': '/ghi', 'pct_used': 95}) => {
"msg": {
"mount": "/ghi",
"pct_used": 95
}
}
问题是,在我的实际用例中,数据是从文件中读取的,默认都是字符串,所以我无法从源头更改。
我觉得必须有一种方法可以在循环中的过滤器表达式中进行强制转换,但我就是想不通。
如果这不可能,那么更新列表本身以将值转换为整数的最佳方法是什么?
【问题讨论】: