- 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"更改为整数?
Q:">如何将value.1
更改为整数">
A: 使用json_query函数进行编号。例如
- debug:
var: getent_passwd|
dict2items|
json_query('[?to_number(value[1]) >= `1000`].key')
Q:">如何将1000
更改为变量">
A: 替换也应该转换为数字。最好单独声明query
。例如
- set_fact:
myusers: "{{ getent_passwd|dict2items|json_query(query) }}"
vars:
myuid: 1000
query: "[?to_number(value[1]) >= to_number('{{ myuid }}')].key"
Q:">如何在json_query函数中添加更多条件?像selectattr('value.5', 'ne', '/sbin/nologin')
">
A: 使用管道或和表达式。例如
- 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"
}
]
根据您的需要调整变量和比较运算符。
json_query中的管道可能被认为是反模式。因此,应该使用和表达式而不是管道。例如
query: "[?(to_number(value[1]) >= to_number('{{ myuid }}')) &&
(value[5] == '{{ myshell }}')].{user: key, uid: value[1], shell: value[5]}"