Q: "How can I change value.1 to an integer?"
A: Use json_query function to_number. For example
- debug:
var: getent_passwd|
dict2items|
json_query('[?to_number(value[1]) >= `1000`].key')
Q: "How can I change 1000 into a variable?"
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"
Q: "How can I add more conditions into json_query function? Like selectattr('value.5', 'ne', '/sbin/nologin')."
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
give
"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.
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]}"