如何通过AWS EC2命令格式化展示安全组防火墙规则?
如何将AWS EC2安全组规则的指定字段展示在同一行
需求
使用aws ec2 describe-security-groups查询特定安全组的防火墙规则,需要将FromPort、ToPort、Description、CidrIp、IpProtocol字段展示在同一行,避免嵌套层级导致信息分散。
解决方案命令
直接使用带嵌套路径的--query参数,并配合表格输出格式,即可实现需求:
aws ec2 describe-security-groups --group-ids sg-xxxxxxx --region us-east-2 \ --query 'SecurityGroups[*].IpPermissions[*].IpRanges[*].{FromPort:../../FromPort || "All", ToPort:../../ToPort || "All", IpProtocol:../../IpProtocol, Description:Description, CidrIp:CidrIp}' \ --output table
命令解释
- 层级展开:
SecurityGroups[*].IpPermissions[*].IpRanges[*]逐层遍历安全组、入站权限规则、每个规则下的IP范围条目,确保每个IP范围都能单独成为一条记录。 - 字段关联:通过相对路径
../../从IpPermissions层级提取FromPort、ToPort、IpProtocol字段,同时直接获取当前IpRanges层级的Description和CidrIp,实现跨层级字段合并。 - 特殊值处理:
|| "All"用于处理IpProtocol="-1"(所有协议)的场景,此时FromPort和ToPort不存在,自动替换为"All",避免输出空值。 - 表格输出:
--output table将结果格式化为整齐的表格,每条规则占一行,字段清晰对齐。
示例输出
| FromPort | ToPort | IpProtocol | Description | CidrIp | |----------|--------|------------|---------------------------------|-------------------| | 80 | 80 | tcp | port 80 traffic from ar-router01| 172.31.6.60/32 | | 0 | 65535 | tcp | this policy is pending | 172.16.0.0/16 | | 5432 | 5432 | tcp | psql access internally | 172.31.0.0/16 | | 5432 | 5432 | tcp | psql access from comcast vpn | xxx.xxx.xxx.xxx/32| | All | All | -1 | this policy is pending | 172.31.0.0/16 | | 22 | 22 | tcp | ssh access from comcast vpn | xxx.xxx.xxx.xxx/32|
为什么之前的命令无效
之前的--query 'SecurityGroups[*].IpPermissions[*]'仅展开了入站权限层级,但每个权限下的IpRanges是数组结构,导致端口、协议与IP描述、地址不在同一层级,无法直接在一行展示。必须通过嵌套遍历IpRanges并关联上层字段,才能实现所有目标字段在同一行的效果。
内容的提问来源于stack exchange,提问作者BioRod
相关产品推荐
相关产品推荐

