Created
January 29, 2022 15:20
-
-
Save OksanaH/2b7f6b0aa9e6f2c33a90c82cc83854c6 to your computer and use it in GitHub Desktop.
lambda.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def imagesInASGs(region): | |
amis = [] | |
autoscaling = boto3.client('autoscaling', region_name=region) | |
print(f'Checking autoscaling groups in region {region}...') | |
paginator = autoscaling.get_paginator('describe_auto_scaling_groups') | |
page_iterator = paginator.paginate( | |
PaginationConfig = {'PageSize': 10} | |
) | |
filtered_asgs = page_iterator.search(f"AutoScalingGroups[*].[Instances[?LifecycleState == 'InService'].[InstanceId, LaunchTemplate.LaunchTemplateId,LaunchTemplate.Version]]") | |
for key_data in filtered_asgs: | |
matches = re.findall(r"'(.+?)'",str(key_data)) | |
instance_id = matches[0] | |
template = matches[1] | |
version = matches[2] | |
print(f"Template found: {template} version {version}") | |
if (template == ""): | |
send_alert(f"AMI cleaner failure", f"Failed to find launch template that was used for instance {instance_id}") | |
return | |
ec2 = boto3.client('ec2', region_name = region) | |
launch_template_versions = ec2.describe_launch_template_versions( | |
LaunchTemplateId=template, | |
Versions=[version] | |
); | |
used_ami_id = launch_template_versions["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"] | |
if not used_ami_id: | |
send_alert(f"AMI cleaner failure", f"Failed to find AMI for launch template {template} version {version}") | |
return | |
amis.append(used_ami_id) | |
return amis |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment