无法将属性与数字进行比较.错误:“'AnsibleUnsafeText' 和 'int' 的实例之间不支持"; [英] Can't compare attribute to a number. Error: "not supported between instances of 'AnsibleUnsafeText' and 'int'"
问题描述
- getent:
database: passwd
- debug:
var: getent_passwd | dict2items | selectattr('value.1', '>=', 1000) | map(attribute='key') | list
输出是
TASK [debug] ******************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on
({{getent_passwd | dict2items | selectattr('value.1', '>=', 1000) | map(attribute='key') | list}}):
'>=' not supported between instances of 'AnsibleUnsafeText' and 'int'"}
如何将value.1"更改为整数?
How can I change 'value.1' to integer?
推荐答案
问:"如何将 value.1
更改为整数?"
A:使用 json_query 函数to_number.例如
A: Use json_query function to_number. For example
- debug:
var: getent_passwd|
dict2items|
json_query('[?to_number(value[1]) >= `1000`].key')
<小时>
问:"如何将1000
改成一个变量?"
A:替换也应该转换为数字.单独声明 query
是个好主意.例如
A: The substitution should be converted to a number too. It's a good idea to declare the query
separately. For example
- set_fact:
myusers: "{{ getent_passwd|dict2items|json_query(query) }}"
vars:
myuid: 1000
query: "[?to_number(value[1]) >= to_number('{{ myuid }}')].key"
<小时>
问:"如何在 json_query 函数中添加更多条件?比如selectattr('value.5', 'ne', '/sbin/nologin')
."
A:使用 pipe 或 and-expression.例如
A: Use pipe or and-expression. For example
- getent:
database: passwd
- set_fact:
myusers: "{{ getent_passwd|dict2items|json_query(query) }}"
vars:
myuid: 1000
myshell: /usr/sbin/nologin
query: "[?to_number(value[1]) >= to_number('{{ myuid }}')] |
[?value[5] == '{{ myshell }}'].{user: key, uid: value[1], shell: value[5]}"
- debug:
var: myusers
给予
"myusers": [
{
"user": "libvirt-qemu",
"shell": "/usr/sbin/nologin",
"uid": "64055"
},
{
"user": "nobody",
"shell": "/usr/sbin/nologin",
"uid": "65534"
}
]
根据您的需要调整变量和比较运算符.
Fit the variables and the Comparison Operator to your needs.
json_query 中的管道可能被认为是一种反模式.因此,应该使用 and-expression 而不是管道.例如
The pipe in json_query might be considered an anti-pattern. Therefore and-expression should be used instead of the pipe. For example
query: "[?(to_number(value[1]) >= to_number('{{ myuid }}')) &&
(value[5] == '{{ myshell }}')].{user: key, uid: value[1], shell: value[5]}"
这篇关于无法将属性与数字进行比较.错误:“'AnsibleUnsafeText' 和 'int' 的实例之间不支持";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!