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

如何在Ansible中搜索匹配模式提取指定存储的容量信息?

问题描述

我的变量info存储了大量类似如下的内容:

XYZ_data_001         file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB      2         0      6       0  8388607
XYZ_data_002         file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB      2         0     13       0  8388607

我需要搜索特定条目XYZ_data_001,提取physical disk,之后的容量信息(即16384.00 MB)。尝试了以下Ansible Playbook代码:

- name: Print size
  ansible.builtin.debug:
    msg: "{{ info | regex_search('XYZ_data_001(.+)') | split('physical disk,') | last }}"

执行后得到的输出包含多余内容:

ok: [testhost] => {
    "msg": " 16384.00 MB, Free: 0.00 MB      2         0      6       0  8388607 "
}

希望得到更精准的提取方法。

解决方案

方法1:正则捕获组直接提取目标内容

利用正则的捕获组特性,直接定位并提取目标容量:

- name: Print exact size
  ansible.builtin.debug:
    msg: "{{ info | regex_search('XYZ_data_001.*physical disk,\\s*(\\d+\\.\\d+ MB)', '\\1') | first }}"

说明:

  • XYZ_data_001.*physical disk,:定位到目标条目并匹配到physical disk,位置
  • \\s*:匹配后续任意空白字符
  • (\\d+\\.\\d+ MB):精准捕获带小数点和单位的容量字符串
  • '\\1':指定仅返回第一个捕获组的内容
  • | first:取出regex_search返回列表中的唯一结果

执行后会得到精准输出:16384.00 MB

方法2:拆分字符串筛选目标字段

如果数据格式固定,可通过拆分字符串逐步筛选:

- name: Print exact size via split
  ansible.builtin.debug:
    msg: "{{ (info.splitlines() | select('search', 'XYZ_data_001') | first).split(', ') | select('search', '^\\d+\\.\\d+ MB') | first }}"

说明:

  • info.splitlines():将多行内容拆分为单行列表
  • select('search', 'XYZ_data_001'):筛选出目标条目行
  • .split(', '):按, 拆分该行的各个字段
  • select('search', '^\\d+\\.\\d+ MB'):筛选出符合容量格式的字段

方法3:兼容多格式的正则匹配

如果容量存在整数格式(如16384 MB),可调整正则兼容多种情况:

- name: Print size with flexible regex
  ansible.builtin.debug:
    msg: "{{ info | regex_search('XYZ_data_001.*physical disk,\\s*(\\d+(?:\\.\\d+)? MB)', '\\1') | first }}"

说明:(?:\\.\\d+)?表示小数点和小数部分为可选,同时支持整数和小数格式的容量。

内容的提问来源于stack exchange,提问作者Chand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:50:33