You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible Playbook中循环处理注册结果生成待清理卷列表

合并Ansible任务实现动态循环处理阵列卷信息

可以通过直接遍历array_info.results列表,结合列表过滤与属性提取,将两个重复任务合并为一个动态循环任务,无需手动指定结果索引。

修改后的Playbook任务代码

- name: Gather volume and hosts info from array
  purestorage.flasharray.purefa_info:
    gather_subset:
      - hosts
    fa_url: "{{ item.fa_url }}"
    api_token: "{{ item.api_token }}"
  register: array_info
  with_items:
    - { fa_url: "{{ src_fa_url }}" , api_token: "{{ src_fa_api_token }}" }
    - { fa_url: "{{ tgt_fa_url }}" , api_token: "{{ tgt_fa_api_token }}" }

# 合并后的单任务循环处理所有阵列结果
- name: Retrieve list of volumes to eradicate from all arrays
  set_fact:
    volumes_list: "{{ volumes_list | default([]) + (item.purefa_info.hosts | dict2items | selectattr('key', 'in', src_host_name) | map(attribute='value.volumes') | flatten | map(attribute='volume') | list) }}"
  loop: "{{ array_info.results }}"

代码说明

  • loop: "{{ array_info.results }}":自动遍历所有purefa_info任务返回的结果,不管结果数量多少都能适配
  • dict2items:将hosts字典转换为键值对列表,方便后续筛选
  • selectattr('key', 'in', src_host_name):只保留src_host_name中定义的主机,替代原任务中的when判断
  • map(attribute='value.volumes') | flatten:提取主机对应的卷列表并展平为一维数组
  • map(attribute='volume'):最终提取卷名称,合并到总列表volumes_list中

如果需要保留原逻辑中分别存储不同阵列的卷列表(比如volumes_list和volumes_list2),可以通过循环索引命名变量:

- name: Retrieve list of volumes to eradicate per array
  set_fact:
    "volumes_list_{{ loop.index0 }}": "{{ item.purefa_info.hosts | dict2items | selectattr('key', 'in', src_host_name) | map(attribute='value.volumes') | flatten | map(attribute='volume') | list }}"
  loop: "{{ array_info.results }}"

这样会生成volumes_list_0、volumes_list_1等变量,对应每个阵列的卷列表。

内容的提问来源于stack exchange,提问作者Philippe B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:35:24