Created
November 30, 2019 21:04
-
-
Save brysontyrrell/c6a5c545e8cdd17a4eb52bb28729f108 to your computer and use it in GitHub Desktop.
A CloudFormation custom resource to perform the lookup of the latest NAT instance AMI ID for the region.
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
AWSTemplateFormatVersion: 2010-09-09 | |
Transform: AWS::Serverless-2016-10-31 | |
Resources: | |
NatInstaceAmi: | |
Type: AWS::CloudFormation::CustomResource | |
Properties: | |
ServiceToken: !GetAtt NatInstanceAmiLookup.Arn | |
NatInstanceAmiLookup: | |
Type: AWS::Serverless::Function | |
Properties: | |
Runtime: python3.7 | |
Handler: index.lambda_handler | |
InlineCode: | | |
import json | |
from operator import itemgetter | |
import boto3 | |
import cfnresponse | |
client = boto3.client('ec2') | |
def lambda_handler(event, context): | |
try: | |
response = client.describe_images( | |
Filters=[ | |
{'Name': 'name', 'Values': ['amzn-ami-vpc-nat-*']}, | |
{'Name': 'state', 'Values': ['available']}, | |
{'Name': 'architecture', 'Values': ['x86_64']} | |
] | |
) | |
image_id = sorted( | |
response['Images'], key=itemgetter('CreationDate'), reverse=True | |
)[0]['ImageId'] | |
cfnresponse.send( | |
event, context, cfnresponse.SUCCESS, | |
{ | |
'ImageId': image_id | |
} | |
) | |
except Exception as error: | |
cfnresponse.send( | |
event, context, cfnresponse.FAILED, | |
{ | |
'Error': type(error).__name__, | |
'Message': str(error) | |
} | |
) | |
Policies: | |
Statement: | |
Effect: Allow | |
Action: ec2:DescribeImages | |
Resource: '*' | |
Outputs: | |
AmiId: | |
Value: !GetAtt NatInstaceAmi.ImageId |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@njsaunders Could you elaborate? I deployed this and the custom resource ran giving me an AMI ID in the outputs.