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

如何在Ansible中移除lvm.lvs字典的lvthinpool并求和size_g

解决Ansible中过滤LVM逻辑卷字典并求和的问题

一、保留过滤后的完整字典结构

要移除lvthinpool条目并保留原字典结构,需先将字典转为键值对列表,过滤后再转回字典:

- name: 过滤并保留目标LVM字典
  set_fact:
    filtered_lvs: "{{ ansible_facts.lvm.lvs | dict2items | rejectattr('key', 'search', 'thinpool') | items2dict }}"

执行后,filtered_lvs就是移除了lvthinpool的完整字典,结构与原ansible_facts.lvm.lvs一致,仅缺失lvthinpool条目。

二、对剩余条目的size_g求和

基于上述filtered_lvs,提取所有size_g值并转换为数值类型后求和:

- name: 计算剩余逻辑卷总容量
  set_fact:
    total_size_g: "{{ filtered_lvs | dict2items | map(attribute='value.size_g') | map('float') | sum | round(2) }}"

操作逻辑:

  1. 将过滤后的字典重新转为键值对列表
  2. 提取每个条目的value.size_g字段
  3. 将字符串格式的容量值转为浮点型
  4. 求和后保留两位小数(可根据需求调整精度)

完整示例Playbook

- hosts: your_host
  gather_facts: yes
  tasks:
    - name: 过滤移除lvthinpool后的LVM字典
      set_fact:
        filtered_lvs: "{{ ansible_facts.lvm.lvs | dict2items | rejectattr('key', 'search', 'thinpool') | items2dict }}"

    - name: 计算剩余逻辑卷总容量
      set_fact:
        total_size_g: "{{ filtered_lvs | dict2items | map(attribute='value.size_g') | map('float') | sum | round(2) }}"

    - name: 打印结果
      debug:
        msg:
          - "过滤后的LVM字典: {{ filtered_lvs }}"
          - "总容量(GB): {{ total_size_g }}"

为什么之前的方法只得到条目名称?

直接对字典使用reject('search', 'thinpool')时,Ansible默认遍历字典的键而非键值对,因此返回的是符合过滤条件的键列表,而非完整字典结构。通过dict2items将字典转为[{key: 'xxx', value: {...}}]格式的列表后,才能用rejectattr针对键进行过滤,再通过items2dict转回字典。

内容的提问来源于stack exchange,提问作者Matheus de Oliveira Morozetti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:55:19