2

I would like to get names of all the aws load balancers which has a particular instance.

I can list the instances in the ELB's using the following command

aws elb describe-load-balancers --query "LoadBalancerDescriptions[*].{ID:LoadBalancerName,InstanceId:Instances[*].InstanceId}[*]. {ELB:ID,InstanceId:InstanceId[*]}" --output=json

Sample Output:

[
{
    "ELB": "my_name",
    "InstanceId": [
        "instance-id-A",
        "instance-id-B",
    ]
},
{
    "ELB": "my_name2",
    "InstanceId": [
        "instance-id-B",
        "instance-id-C"
    ]
},
{
    "ELB": "my_name3",
    "InstanceId": [
        "instance-id-A",
        "instance-id-C"
    ]
}

]

How do I filter this output to only return the ELB names which has instance id A?

Jeetendra Pujari
  • 1,286
  • 2
  • 17
  • 31

2 Answers2

3

The contains command will give you what you're looking for

aws elb describe-load-balancers --query "LoadBalancerDescriptions[*].{ID:LoadBalancerName,InstanceId:Instances[*].InstanceId}[?contains(to_string(@),'instance-id-A')]"

Provides output:

[
    {
        "ID": "lb_name",
        "InstanceId": [
            "i-1234567890"
        ]
    }
]

References

http://jmespath.org/specification.html#contains

kenlukas
  • 3,616
  • 9
  • 25
  • 36
2

Another approach, which I like better as I think is more easy to use, is to use jq for filtering:

aws elb describe-load-balancers | jq -r '.LoadBalancerDescriptions[] | select (.Instances[].InstanceId == "instance-id-A") | .LoadBalancerName'

Output:

SampleLBName1
SampleLBName2

kenlukas
  • 3,616
  • 9
  • 25
  • 36
Eran Ben-Natan
  • 2,515
  • 2
  • 16
  • 19