Skip to content

Instantly share code, notes, and snippets.

@mjsc1409
Last active September 16, 2021 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mjsc1409/2eaf3a7014dbadb0a6243b6e813be33c to your computer and use it in GitHub Desktop.
Save mjsc1409/2eaf3a7014dbadb0a6243b6e813be33c to your computer and use it in GitHub Desktop.
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