如何在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.
相关产品推荐
相关产品推荐

