Skip to content

Instantly share code, notes, and snippets.

@mvanbaak
Created September 5, 2017 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvanbaak/7035721e8c4d46ebe61398770925d906 to your computer and use it in GitHub Desktop.
Save mvanbaak/7035721e8c4d46ebe61398770925d906 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import boto3
# SNS Config
sns_topic_arn = "arn:aws:sns:eu-west-1:AWS-ACCOUNT-ID:SNS-TOPIC"
sns_subject = "ASGs Missing AMIs"
def lambda_handler(event, context):
failures = collect_launch_configs(get_regions())
if bool(failures):
send_sns_message(failures)
def get_regions():
regions = {}
for region in boto3.client('ec2').describe_regions()['Regions']:
regions[region['RegionName']] = []
return regions
def message(content):
return "This is a report of regions that have Auto Scaling groups "\
"deployed that include a launch configuration that points to an "\
"AMI that is not available:\n\n%s" % (json.dumps(content, indent=4))
def send_sns_message(failures):
client = boto3.client('sns')
client.publish(
TopicArn=sns_topic_arn,
Message=message(failures),
Subject=sns_subject
)
def collect_launch_configs(regions):
# launch_configs = regions
failures = {}
for region in regions:
asg_client = boto3.client('autoscaling', region_name=region)
ec2_client = boto3.client('ec2', region_name=region)
# We get all images here because we dont want to do a single
# api call for every launch configuration
res = ec2_client.describe_images(
Filters=[
{
'Name': 'state',
'Values': ['available']
}
],
Owners=['self']
)['Images']
our_images = [x['ImageId'] for x in res]
paginator = asg_client.get_paginator('describe_launch_configurations')
lcs = paginator.paginate().build_full_result()
for lc in lcs['LaunchConfigurations']:
if not lc['ImageId'] in our_images:
if region in failures:
failures[region].append({"LaunchConfigurationName":
lc['LaunchConfigurationName'],
"ImageId": lc['ImageId']})
else:
failures[region] = [{"LaunchConfigurationName":
lc['LaunchConfigurationName'],
"ImageId": lc['ImageId']}]
return failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment