Find EC2 Instances behind an Application Load Balancer with AWS CLI

Ifrastructure as a Code (IaaC)

IaaC is the way to achieve automated, repeatable and consistent results for deployments. Here are some of the commonly used tools for IaaC:

  1. Terraform
  2. CloudFormation
  3. Ansible
  4. Chef
  5. Puppet
  6. Packer

Regardless of the tools utilized for automation, there is no way around writing scripts. You best bet is get in the habit of relying less and less on AWS Console and gradually adopt any command line interface you may have at your disposal.

So before running any commands, make sure you AWS CLI environment is set with login credentials, as such keys and token. Make sure to set your AWS CLI environment before running the script. You can take a look at the if needed environment setup steps. Following three environment variables must be set for the session:

$ export AWS_ACCESS_KEY_ID=ABCXYZ123LEDBHNDJOHN
$ export AWS_SECRET_ACCESS_KEY=abc123XYZOrYKEaXv/yzY7GqSh16FrtzL0EM2bD7
$ export AWS_SESSION_TOKEN=FQoABCdzXYZ//////////wEaXYZl/Yv6mzhCxyzfriKwAejFxV3vDdkHs73ucABCZVa4cOeoPjhkvcKXMAvQrNrxr31qyO4o39+kjCobUvEZDqsG0T6x6r/kz8b+PvVLK4gKst5zuQbFshc1eOa0sr9dXYZrw1jV/w1a8iVyCuDFKS/V9fHG/J9zx43vG4UMP9Rz6DJOHN6ehPT2/4jzSuFehjHufHcp1vDulw/cAh++gysckCT4CBJ+Abdul+Gill+LSpb2+14sZbX0y3b0lxi+Larry+IF

In case of classic load balancer, it’s easy to query EC2’s behind it with the following single command:

export ELB_Name=agill-classic-elb-internal
aws elb describe-load-balancers \
   --load-balancer-name $ELB_NAME \
   --query 'LoadBalancerDescriptions[].Instances[].InstanceId' \
   --output=text

But it gets a bit tricky to retrieve list of EC2 instances behind an application load balancer. There’s no single command to accomplish that. It can be done in multiple steps:

  1. Retrieve Load Balancer ARN for given name
  2. Retrieve Target Group ARN
  3. Retrieve Instances’ list

Let take a look at the AWS commands run in the same sequence. Please note that elbv2 command is used to work with application load balancer:

#!/bin/bash

ALB_Name=$1

echo "ALB_Name: $ALB_Name"

ALB_ARN=$(aws elbv2 describe-load-balancers --names $ALB_Name --query 'LoadBalancers[0].LoadBalancerArn' --output text)

TG_ARN=$(aws elbv2 describe-target-groups --load-balancer-arn $ALB_ARN --query 'TargetGroups[0].TargetGroupArn' --output text)

aws elbv2 describe-target-health --target-group-arn $TG_ARN --query 'TargetHealthDescriptions[*].Target.Id' --output text

For convenience, you can same these copmmands into a shell script and ram like this, passing load balancer name as an input parameter:

$ ./list_alb_ec2.sh my-load-balancer-name

Download Shell Script

EC2 Instances Behind a Load Balancer, Shell Script

Leave a Reply

Your email address will not be published. Required fields are marked *