Skip to content

Instantly share code, notes, and snippets.

@brysontyrrell
Created November 30, 2019 21:04
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 brysontyrrell/c6a5c545e8cdd17a4eb52bb28729f108 to your computer and use it in GitHub Desktop.
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.
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
@brysontyrrell
Copy link
Author

@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