可以使用 AWS SDK 或 AWS CLI 来描述目标组和健康检查程序,并根据健康状况自动停止和重新启动不健康的实例。以下是一个示例 Python 代码,可以使用 AWS boto3 库来执行此操作:
import boto3
# define the target group arn
target_group_arn = 'arn:aws:elasticloadbalancing:ap-southeast-1:1234567890:targetgroup/mytargetgroup/abcdef123456789'
# create ElasticLoadBalancingv2 client
elbv2 = boto3.client('elbv2')
# get all targets in target group
response = elbv2.describe_target_health(TargetGroupArn=target_group_arn)
for target in response['TargetHealthDescriptions']:
if target['TargetHealth']['State'] == 'unhealthy':
# stop instance
ec2 = boto3.resource('ec2')
instance = ec2.Instance(target['Target']['Id'])
instance.stop()