Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martin-garbe/57234836e23c5d53ebfdd157756cc3aa to your computer and use it in GitHub Desktop.
Save martin-garbe/57234836e23c5d53ebfdd157756cc3aa to your computer and use it in GitHub Desktop.
Fetch IPv6 address of EC2 instance for creating AAAA DNS record
# large parts taken from https://aws.amazon.com/blogs/mt/four-ways-to-retrieve-any-aws-service-property-using-aws-cloudformation-part-1/
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
ExampleServiceInstanceName:
Default: Example
Description: Instance and Host Name
Type: String
Resources:
ExampleService:
Properties:
ImageId: ami-09e0d6fdf60750e33 # Ubuntu Server 20.04 LTS (HVM), SSD Volume Type, (64-bit Arm)
InstanceType: t4g.small
KeyName: example.key
SubnetId: subnet-123456789 # <- insert your subnet here
Type: AWS::EC2::Instance
ExampleDnsRecordAAAA:
Properties:
Comment: A record for the Example server.
HostedZoneId: Z1234567890 # <- insert your hosted zone id here
Name:
Fn::Join:
- .
- - !Ref ExampleServiceInstanceName
- Z1234567890 # <- insert your hosted zone id here
ResourceRecords:
- Fn::GetAtt: CustomIpv6Resource.Ipv6Address
TTL: 900
Type: AAAA
Type: AWS::Route53::RecordSet
#
# CustomResource for fetching IPv6 address
#
LambdaBasicExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: CustomLambdaEC2DescribePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- ec2:DescribeNetworkInterfaces
Resource: '*'
CustomIpv6Resource:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt 'CustomFunction.Arn'
ResourceRef: !Ref ExampleService
CustomFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Description: "Retrieves IPv6 address of EC2 instance"
Timeout: 30
Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
Runtime: python3.7
Code:
ZipFile: |
import json
import logging
import cfnresponse
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info('got event {}'.format(event))
try:
responseData = {}
if event['RequestType'] == 'Delete':
logger.info('Incoming RequestType: Delete operation')
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
if event['RequestType'] in ["Create", "Update"]:
# 1. retrieve resource reference ID or Name
ResourceRef=event['ResourceProperties']['ResourceRef']
# 2. retrieve boto3 client
client = boto3.client('ec2')
# 3. Invoke describe/retrieve function using ResourceRef
response = response=client.describe_network_interfaces(Filters=[{'Name':'attachment.instance-id', 'Values':[ResourceRef] }])
# 4. Parse and return required attributes
responseData = {}
responseData['Ipv6Address'] = response.get('NetworkInterfaces')[0]['Ipv6Addresses'][0]['Ipv6Address']
logger.info('Retrieved IPv6 address!')
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
else:
logger.info('Unexpected RequestType!')
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as err:
logger.error(err)
responseData = {"Data": str(err)}
cfnresponse.send(event,context,cfnresponse.FAILED,responseData)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment