///<summary>/// Delete a TargetGroup by its specified name.///</summary>///<param name="groupName">Name of the group to delete.</param>///<returns>Async task.</returns>publicasync Task DeleteTargetGroupByName(string groupName){var done = false;
while (!done)
{try{var groupResponse =
await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
new DescribeTargetGroupsRequest()
{
Names = new List<string>() { groupName }
});
var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
Console.WriteLine($"Deleted load balancing target group {groupName}.");
done = true;
}
catch (TargetGroupNotFoundException)
{
Console.WriteLine(
$"Target group {groupName} not found, could not delete.");
done = true;
}
catch (ResourceInUseException)
{
Console.WriteLine("Target group not yet released, waiting...");
Thread.Sleep(10000);
}
}
}
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2TargetGroup (DeleteTargetGroup)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): y
有关 API 的详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考DeleteTargetGroup中的。
classElasticLoadBalancerWrapper:"""Encapsulates Elastic Load Balancing (ELB) actions."""def__init__(self, elb_client: boto3.client):"""
Initializes the LoadBalancer class with the necessary parameters.
"""
self.elb_client = elb_client
defdelete_target_group(self, target_group_name) -> None:"""
Deletes the target group.
"""try:
# Describe the target group to get its ARN
response = self.elb_client.describe_target_groups(Names=[target_group_name])
tg_arn = response["TargetGroups"][0]["TargetGroupArn"]
# Delete the target group
self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
log.info("Deleted load balancing target group %s.", target_group_name)
# Use a custom waiter to wait until the target group is no longer available
self.wait_for_target_group_deletion(self.elb_client, tg_arn)
log.info("Target group %s successfully deleted.", target_group_name)
except ClientError as err:
error_code = err.response["Error"]["Code"]
log.error(f"Failed to delete target group '{target_group_name}'.")
if error_code == "TargetGroupNotFound":
log.error(
"Load balancer target group either already deleted or never existed. ""Verify the name and check that the resource exists in the AWS Console."
)
elif error_code == "ResourceInUseException":
log.error(
"Target group still in use by another resource. ""Ensure that the target group is no longer associated with any load balancers or resources.",
)
log.error(f"Full error:\n\t{err}")
defwait_for_target_group_deletion(
self, elb_client, target_group_arn, max_attempts=10, delay=30):for attempt inrange(max_attempts):
try:
elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
print(
f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
)
except ClientError as e:
if e.response["Error"]["Code"] == "TargetGroupNotFound":
print(
f"Target group {target_group_arn} has been successfully deleted."
)
returnelse:
raise
time.sleep(delay)
raise TimeoutError(
f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
)
有关 API 的详细信息,请参阅适用DeleteTargetGroup于 Python 的AWS SDK (Boto3) API 参考。
///<summary>/// Delete a TargetGroup by its specified name.///</summary>///<param name="groupName">Name of the group to delete.</param>///<returns>Async task.</returns>publicasync Task DeleteTargetGroupByName(string groupName){var done = false;
while (!done)
{try{var groupResponse =
await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
new DescribeTargetGroupsRequest()
{
Names = new List<string>() { groupName }
});
var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
Console.WriteLine($"Deleted load balancing target group {groupName}.");
done = true;
}
catch (TargetGroupNotFoundException)
{
Console.WriteLine(
$"Target group {groupName} not found, could not delete.");
done = true;
}
catch (ResourceInUseException)
{
Console.WriteLine("Target group not yet released, waiting...");
Thread.Sleep(10000);
}
}
}