如何遍历Ansible任务输出并提取{{ item }}对应RPM包的path路径
解决方案
核心问题原因
原Playbook的debug任务直接循环整个found_pkgs注册变量,没有正确深入到嵌套的results→files层级提取path字段,同时find任务的with_items写法存在冗余嵌套问题。
修改后的完整Playbook片段
- name: Get the inventory file printout. command: tail "{{ build_dir }}{{ inventory_file }}" register: command_output - debug: msg: "{{ command_output.stdout_lines }}" - name : Find the RPMs in "{{ build_dir }}" find: paths: "{{ build_dir }}" patterns: "{{ item }}.rpm" recurse: yes with_items: "{{ command_output.stdout_lines }}" register: found_pkgs # 方式1:循环打印每个RPM的path路径 - name: Just the Path for each Found Pkgs. debug: msg: "{{ item.1.path }}" loop: "{{ found_pkgs.results | subelements('files', skip_missing=True) }}" loop_control: label: "{{ item.0.item }}" # 可选:控制循环输出的标签,避免打印大量冗余信息 # 方式2:一次性提取所有path到列表,供后续任务直接使用 - name: Collect all RPM paths to a list set_fact: rpm_path_list: "{{ found_pkgs.results | map(attribute='files') | flatten | map(attribute='path') | list }}" - debug: msg: "{{ rpm_path_list }}"
用法说明
- 如果你需要后续基于路径创建目录,直接使用
rpm_path_list变量循环操作即可,不需要额外提取字段 skip_missing=True参数会自动跳过没有找到对应RPM的条目,避免任务报错
内容的提问来源于stack exchange,提问作者phildup808
相关产品推荐
相关产品推荐

