EC2 describe-instances按PrivateIpAddress排序失败问题咨询
AWS EC2 describe-instances排序命令执行失败
我尝试运行ec2 describe-instances命令,将结果以表格形式输出并按PrivateIpAddress排序,使用的命令如下:
aws ec2 describe-instances \ --instance-id $instances --region us-west-2 --output table --query 'Reservations[].Instances[].{LaunchTime:LaunchTime,InstanceId:InstanceId,PrivateIpAddress:PrivateIpAddress,Name:Tags[?Key==`Name`] | [0].Value, Status:State.Name} | sort_by(@, &[2])'
执行后报错:
In function sort_by(), invalid type for value: {'LaunchTime': '2023-05-04T08:10:46+00:00', 'InstanceId': 'i-23424242424234234aef', 'PrivateIpAddress': 'xx.xxx.xx.xxx', 'Name': 'sdkjsdfk', 'Status': 'running'}, expected one of: ['string', 'number'], received: "null"
问题分析与解决
核心错误原因
你的sort_by参数用了&[2],这是数组索引引用方式,但你在查询中已经将EC2实例数据转换成了键值对对象(每个实例是包含LaunchTime、InstanceId等键的对象),而非数组,所以&[2]无法找到对应的值,返回了null,导致排序函数报错。
修正后的命令
将排序逻辑改为直接引用对象的PrivateIpAddress属性即可:
aws ec2 describe-instances \ --instance-ids $instances \ --region us-west-2 \ --output table \ --query 'Reservations[].Instances[].{LaunchTime:LaunchTime,InstanceId:InstanceId,PrivateIpAddress:PrivateIpAddress,Name:Tags[?Key==`Name`] | [0].Value, Status:State.Name} | sort_by(@, &PrivateIpAddress)'
额外注意点
- 如果
$instances是多个实例ID的集合,建议使用--instance-ids(复数形式),这是AWS CLI的标准参数格式,避免潜在的参数解析问题。 - 若存在实例没有PrivateIpAddress的极端情况,可以添加空值处理,比如
sort_by(@, &(PrivateIpAddress || '0.0.0.0')),确保排序不会因为空值中断。
内容的提问来源于stack exchange,提问作者thej
相关产品推荐
相关产品推荐

