Skip to content

Instantly share code, notes, and snippets.

@ajohnstone
Created April 24, 2016 22:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ajohnstone/8f8c6ecdbbc6980597d0807331b779f2 to your computer and use it in GitHub Desktop.
Save ajohnstone/8f8c6ecdbbc6980597d0807331b779f2 to your computer and use it in GitHub Desktop.
import boto3
r53_client = boto3.client('route53')
hosted_zone = 'alias.photobox.com.'
def lambda_handler(event = {}, context = {}):
aws_region = event['detail']['awsRegion']
elb_client = boto3.client('elb', region_name=aws_region)
request = event['detail']['requestParameters']
load_balancer = request['loadBalancerName'] if 'loadBalancerName' in request else request['loadBalancerNames'][0]
#event sent after a tag addition does not contain the full list of tags, but just the one created:
elb_tags = elb_client.describe_tags(LoadBalancerNames=[load_balancer])['TagDescriptions'] or []
reversed_tags = {x['Value']: x['Key'] for x in elb_tags[0]['Tags'] if elb_tags[0]['Tags'] }
tags = {v: k for k, v in reversed_tags.items()
cluster= tags.get('KubernetesCluster')
namespace, service_name = tags.get('kubernetes.io/service-name').split('/')
dns_endpoint = "%s-%s.%s" % (service_name, namespace, args.hosted_zone)
zone = ( filter(lambda x: x['Name'] == hosted_zone, r53_client.list_hosted_zones()['HostedZones'])[:1] or [None])[0]
if zone:
lb = elb_client.describe_load_balancers(LoadBalancerNames=[load_balancer])['LoadBalancerDescriptions'][0]
lb_zone_id = lb['CanonicalHostedZoneNameID']
elb_dns_name = lb['DNSName']
r53_client.change_resource_record_sets(
HostedZoneId = zone['Id'],
ChangeBatch={
'Comment': "Upserting %s for elb %s" % (dns_endpoint, elb_dns_name),
'Changes':
[
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': dns_endpoint,
'Type': 'A',
'AliasTarget': {
'HostedZoneId': lb['CanonicalHostedZoneNameID'],
'DNSName': lb['DNSName'],
'EvaluateTargetHealth': True,
}
}
}
]
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment