如何用AWS CLI按特定标签查询并输出扁平结构结果?
解决AWS CLI查询FSx时Name标签的层级问题
你的问题出在JMESPath查询对Tags的处理上:Tags[?Key==\Name`].Value会返回一个数组(哪怕只有一个匹配的标签值),所以输出里name字段是数组格式。要扁平化这个字段,只需要在表达式末尾加上[0]`提取数组的第一个元素即可。
修改后的完整命令
aws fsx describe-file-systems \ --no-paginate --no-cli-pager --output yaml \ --query 'FileSystems[].{id:FileSystemId,netid:NetworkInterfaceIds[0],name:Tags[?Key==`Name`].Value[0]}'
或者用管道写法(效果完全一致):
aws fsx describe-file-systems \ --no-paginate --no-cli-pager --output yaml \ --query 'FileSystems[].{id:FileSystemId,netid:NetworkInterfaceIds[0],name:Tags[?Key==`Name`].Value|[0]}'
输出效果
- id: fs-1234abcd name: home netid: eni-1234abcde
额外优化(处理无Name标签的场景)
如果部分文件系统没设置Name标签,上面的写法会让name字段返回null。要是希望返回空字符串作为默认值,可以修改name的查询表达式:
aws fsx describe-file-systems \ --no-paginate --no-cli-pager --output yaml \ --query 'FileSystems[].{id:FileSystemId,netid:NetworkInterfaceIds[0],name:Tags[?Key==`Name`].Value|[0] || ''}'
内容的提问来源于stack exchange,提问作者cfi
相关产品推荐
相关产品推荐

