如何用jq查询从Ansible字典提取含fence-agents的包列表?
提取包含特定字符串的Ansible包列表
要快速从ansible_facts.packages字典中筛选出名称包含fence-agents的包,避免全量遍历影响性能,可以用以下两种方案:
方案一:Ansible原生过滤(推荐,无额外依赖)
直接利用Ansible内置过滤器完成筛选,所有操作在控制节点完成,不会在远程主机产生额外开销。
修改后的Playbook任务如下:
- name: gather package facts package_facts: - name: send packages containing 'fence-agents' to a file lineinfile: path: /etc/leapp/transaction/to_remove line: "{{ item }}" loop: "{{ ansible_facts.packages | dict2items | selectattr('key', 'search', 'fence-agents') | map(attribute='key') | list }}" become: true
过滤器说明:
dict2items:将包信息字典转换为{key: 包名, value: 包详情}格式的列表selectattr('key', 'search', 'fence-agents'):筛选出key(包名)中包含fence-agents的条目map(attribute='key'):提取筛选结果中的包名字段list:将最终结果转换为可用于loop的列表
方案二:使用jq过滤(需额外依赖)
如果依赖community.general集合(可通过ansible-galaxy collection install community.general安装),可以用jq语法完成筛选:
- name: gather package facts package_facts: - name: send packages containing 'fence-agents' to a file lineinfile: path: /etc/leapp/transaction/to_remove line: "{{ item }}" loop: "{{ ansible_facts.packages | community.general.jq('keys[] | select(. | contains(\"fence-agents\"))') }}" become: true
jq语法说明:
keys[]:取出字典的所有键(即包名)select(. | contains("fence-agents")):筛选出包含指定字符串的键
内容的提问来源于stack exchange,提问作者jstar100x
相关产品推荐
相关产品推荐

