我需要使用 AWS CLI 查找给定 EC2 实例附加到的负载均衡器。 我有一个使用 jq 的工作解决方案,但是我想避免将 jq 安装为依赖项,并在可能的情况下在 JMESPath 中编写查询。我被困在JMESPath表达式的查询格式上。
我发现了这个问题:按 VPC ID 过滤负载均衡器,这正是我正在尝试做的,除了按实例 ID 而不是 VPC ID 过滤。 我认为问题是实例 ID 在数组中。
使用jq的工作解决方案:
aws elb describe-load-balancers | jq -r '.LoadBalancerDescriptions[] | select(.Instances[].InstanceId == "i-12345678") | .LoadBalancerName
我正在尝试使用JMESPath:
aws elb describe-load-balancers --query "LoadBalancerDescriptions[?Instances[].InstanceId=='i-12345678'] | [].LoadBalancerName"
我觉得我非常接近,但缺少一些基本的东西。
AWS 文档中描述负载均衡器命令的示例 JSON 输出:
{
"LoadBalancerDescriptions": [
{
"Subnets": [
"subnet-15aaab61"
],
"CanonicalHostedZoneNameID": "Z3DZXE0EXAMPLE",
"CanonicalHostedZoneName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
"ListenerDescriptions": [
{
"Listener": {
"InstancePort": 80,
"LoadBalancerPort": 80,
"Protocol": "HTTP",
"InstanceProtocol": "HTTP"
},
"PolicyNames": []
},
{
"Listener": {
"InstancePort": 443,
"SSLCertificateId": "arn:aws:iam::123456789012:server-certificate/my-server-cert",
"LoadBalancerPort": 443,
"Protocol": "HTTPS",
"InstanceProtocol": "HTTPS"
},
"PolicyNames": [
"ELBSecurityPolicy-2015-03"
]
}
],
"HealthCheck": {
"HealthyThreshold": 2,
"Interval": 30,
"Target": "HTTP:80/png",
"Timeout": 3,
"UnhealthyThreshold": 2
},
"VPCId": "vpc-a01106c2",
"BackendServerDescriptions": [
{
"InstancePort": 80,
"PolicyNames": [
"my-ProxyProtocol-policy"
]
}
],
"Instances": [
{
"InstanceId": "i-207d9717"
},
{
"InstanceId": "i-afefb49b"
}
],
"DNSName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
"SecurityGroups": [
"sg-a61988c3"
],
"Policies": {
"LBCookieStickinessPolicies": [
{
"PolicyName": "my-duration-cookie-policy",
"CookieExpirationPeriod": 60
}
],
"AppCookieStickinessPolicies": [],
"OtherPolicies": [
"my-PublicKey-policy",
"my-authentication-policy",
"my-SSLNegotiation-policy",
"my-ProxyProtocol-policy",
"ELBSecurityPolicy-2015-03"
]
},
"LoadBalancerName": "my-load-balancer",
"CreatedTime": "2015-03-19T03:24:02.650Z",
"AvailabilityZones": [
"us-west-2a"
],
"Scheme": "internet-facing",
"SourceSecurityGroup": {
"OwnerAlias": "123456789012",
"GroupName": "my-elb-sg"
}
}
]
}
aws elb describe-load-balancers --query LoadBalancerDescriptions[?Instances[0].InstanceId==`i-55555555`].LoadBalancerName
由于Instances
是一个数组,因此您应该使用 contains
函数来搜索您的实例 ID。
aws elb describe-load-balancers --query LoadBalancerDescriptions[?contains(Instances[*].InstanceId,`i-12345678`)].LoadBalancerName
使用 LoadBalancerDescriptions[?Instances[*].InstanceId==`i-55555555`]
遍历实例。
LoadBalancerDescriptions[?Instances[0].InstanceId==`i-55555555`]
将仅使用数组中的第一个元素。