Jed's Journal

Yes. I'm blogging straight from a terminal.

Get AWS ECS target group instance IPs using Python

April 05, 2018 — Jed Mallen

Some routine job we do at work requires a recycle of instances which will be replaced by ASG.

Imagine logging on to your AWS console, going to ECS, then services then tasks, then each task has its list of several instances that you need to ssh to and stop the service. Multiply that by several clusters and you got your hands full. And you have to do this inside a short time.

Because I'm lazy I will script this. Run the script below and you get a list of all the instance IPs under each target-group. That script can also ssh automatically but nah. Maybe some other time for that.

import boto3
import pprint

cluster = "your-webapp-ecs-cluster"
targetgroup1 = "arn:aws:elasticloadbalancing:us-east-1:666666666666:targetgroup/tg1/0f3864e3bf78aaa5"
targetgroup2 = "arn:aws:elasticloadbalancing:us-east-1:666666666666:targetgroup/tg2/4ea77bce7c612c33"
targetgroup3 = "arn:aws:elasticloadbalancing:us-east-1:666666666666:targetgroup/tg3/0f3864e3bf78aaa5"
targetgroup4 = "arn:aws:elasticloadbalancing:us-east-1:666666666666:targetgroup/tg4/db4f648a0ebb7d8a"
targetgroup5 = "arn:aws:elasticloadbalancing:us-east-1:666666666666:targetgroup/tg5/a3d7aaade00c1967"
tgs = [ targetgroup1, targetgroup2, targetgroup3, targetgroup4, targetgroup5 ]

session = boto3.Session(profile_name='your_aws_profile')
ec2_client = session.client('ec2',region_name='us-east-1')
elbv2_client = session.client('elbv2',region_name="us-east-1")
pp = pprint.PrettyPrinter()

for tg in tgs:
    target_group_health = elbv2_client.describe_target_health(TargetGroupArn = tg)
    tg_name = tg.split('/')
    target_len = len(target_group_health['TargetHealthDescriptions'])
    print("=============================")
    for i in range(0, target_len):
        instance_id = target_group_health['TargetHealthDescriptions'][i]['Target']['Id']
        instance_info = ec2_client.describe_instances(InstanceIds=[instance_id])
        instance_ip = instance_info['Reservations'][0]['Instances'][0]['PrivateIpAddress']
        instance_port = target_group_health['TargetHealthDescriptions'][i]['Target']['Port']
        print(tg_name[1], instance_id, instance_ip)

Tags: python3, boto3, aws-cli, elastic-container-service