Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A CloudFormation custom resource to perform the lookup of the latest NAT instance AMI ID for the region.
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
@njsaunders
Copy link

njsaunders commented Dec 28, 2020

The Irony is that this won't work without a NAT Instance......

@brysontyrrell
Copy link
Author

brysontyrrell commented Dec 28, 2020

@njsaunders Could you elaborate? I deployed this and the custom resource ran giving me an AMI ID in the outputs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment