Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
get-target-health-AWS-Lambda
import sys
import urllib.request, urllib.error, urllib.parse
import boto3

def lambda_handler(event, context):
    print('## Iniciando health check demo')
    client = boto3.client('elbv2')
    targetResponse = client.describe_target_health(
    TargetGroupArn='arn:aws:elasticloadbalancing:us-east-1:123456789:targetgroup/target-group/123456qwerty',
    )
    print (targetResponse)

RESPONSE

   {
	"TargetHealthDescriptions": [
		{
			"Target": {
				"Id": "i-fgergregerg",
				"Port": 80
			},
			"HealthCheckPort": "80",
			"TargetHealth": {
				"State": "healthy"
			}
		},
		{
			"Target": {
				"Id": "i-uu45y5g55w",
				"Port": 80
			},
			"HealthCheckPort": "80",
			"TargetHealth": {
				"State": "healthy"
			}
		},
		{
			"Target": {
				"Id": "i-rty5y54n6e",
				"Port": 80
			},
			"HealthCheckPort": "80",
			"TargetHealth": {
				"State": "healthy"
			}
		}
	],
	"ResponseMetadata": {
		
		
	}
}
import sys
import urllib.request, urllib.error, urllib.parse
import boto3
region = 'us-east-1'

def lambda_handler(event, context):
    print('## Iniciando health check demo')
    client = boto3.client('elbv2')
    targetResponse = client.describe_target_health(
    TargetGroupArn='arn:aws:elasticloadbalancing:us-east-1:123456789:targetgroup/target-group/123456qwerty',
    )
    
    for details in targetResponse['TargetHealthDescriptions']:
        print(details['Target']['Id'])
        instances = [details['Target']['Id']]
        print(details['TargetHealth']['State'])
        if details['TargetHealth']['State'] != "healthy":
            ec2 = boto3.client('ec2', region_name=region)
            ec2.reboot_instances(InstanceIds=instances)
            print(('Reboot your instances: ' + str(instances)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment