forked from awslabs/ecs-refarch-service-discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecs-register-service-dns-lambda.py
100 lines (82 loc) · 2.18 KB
/
ecs-register-service-dns-lambda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from __future__ import print_function
import json
import boto3
def lambda_handler(event, context):
# spit out event data
print("Received event: " + json.dumps(event, indent=2))
# private hosted zone domain name and id
privatezone = 'ecs.internal'
zoneid = 'Route53PrivateHostedZoneID'
cluster = 'ECSClusterName'
# grab load balancer and service names
lb = event['detail']['responseElements']['service']['loadBalancers'][0]['loadBalancerName']
service = event['detail']['responseElements']['service']['serviceName']
# check we are working against the appropriate ecs cluster
if cluster != event['detail']['requestParameters']['cluster']:
print("This event does not apply to us. No action taken.")
return 0
# grab DNS name for load balancer
elbclient = boto3.client('elb')
describelb = elbclient.describe_load_balancers(
LoadBalancerNames=[
lb
]
)
lbcanonical = describelb['LoadBalancerDescriptions'][0]['DNSName']
servicerecord = service + "." + privatezone + "."
# grab type of event
eventname = event['detail']['eventName']
# boto connect to route53
route53client = boto3.client('route53')
# create/update record
if eventname == 'CreateService':
response = route53client.change_resource_record_sets(
HostedZoneId=zoneid,
ChangeBatch={
'Comment' : 'ECS service registered',
'Changes' : [
{
'Action' : 'UPSERT',
'ResourceRecordSet' : {
'Name' : servicerecord,
'Type' : 'CNAME',
'TTL' : 60,
'ResourceRecords' : [
{
'Value' : lbcanonical
}
]
}
}
]
}
)
print(response)
# delete record
elif eventname == 'DeleteService':
response = route53client.change_resource_record_sets(
HostedZoneId=zoneid,
ChangeBatch={
'Comment' : 'ECS service deregistered',
'Changes' : [
{
'Action' : 'DELETE',
'ResourceRecordSet' : {
'Name' : servicerecord,
'Type' : 'CNAME',
'TTL' : 60,
'ResourceRecords' : [
{
'Value' : lbcanonical
}
]
}
}
]
}
)
print(response)
return response
else:
print("This event does not apply to us. No action taken.")
return 0