[英]Ansible - Filter Dictionary Values
我已經使用getent_module收集了所有用戶的列表:
- name: Get user info
getent:
database: passed
這會將這個變量作為 getent_passwd 返回,一個像這樣的字典:
{
"uuidd": [
"x",
"107",
"112",
"",
"/run/uuidd",
"/usr/sbin/nologin"
],
"www-data": [
"x",
"33",
"33",
"www-data",
"/var/www",
"/usr/sbin/nologin"
]
}
我試圖返回一組用戶,包括一些特定的用戶,找到 item.value 的鍵,其中“/home”是值數組項之一的一部分,而“nologin”不是。 這是我到目前為止寫的代碼,但它不正確。
- name: style the user list
set_fact:
my_users: "{{ item.key | default([]) }}"
when:
- "'nologin' not in (item.value)"
- "'/home' search in (item.value)"
loop: "{{ lookup('dict', getent_passwd) }}"
我應該如何改變我的條件以獲得預期的結果?
正如您正確理解的那樣,由於模式/正則表達式匹配適用於字符串而不適用於列表項when
因此條件不起作用。 在匹配列表中的項目時,我們需要匹配完整的項目,即
when:
- "'/home/someuser' in item.value"
- "'/usr/sbin/nologin' not in item.value"
通常,Linux 中的$HOME
路徑是/home/$USER
。 生成的getent_passwd
包含item.key
中的用戶名。 這意味着我們可以使用/home/{{ item.key }}
來匹配item.value
。
像下面這樣的任務應該可以完成這項工作:
- name: save users with actual login
set_fact:
my_users: "{{ my_users | default([]) + [ item.key ] }}"
when:
- "'/home/' ~ item.key in item.value"
- "'/usr/sbin/nologin' not in item.value"
loop: "{{ lookup('dict', getent_passwd) }}"
另一種方法可能是實際join
item.value
以獲取與/etc/passwd
中的字符串相似的字符串,以便我們可以進行文本搜索,例如: '/home' search in (item.value)
。
例子:
# item.value | join(':') is the same as each line of '/etc/passwd'
- name: save users with actual login
set_fact:
my_users: "{{ my_users | default([]) + [ item.key ] }}"
when:
- "'/home' in item.value | join(':')"
- "'nologin' not in item.value | join(':')"
loop: "{{ lookup('dict', getent_passwd) }}"
通過附加檢查擴展其他答案以排除系統用戶:
- name: save users with actual login
set_fact:
actual_users: "{{ actual_users | default([]) + [ item.key ] }}"
when:
- "item.value[1] | int >= 1000"
- "'/home' in item.value[4]"
- "'nologin' not in item.value[5]"
loop: "{{ lookup('dict', getent_passwd) }}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.