/
worker_scaling_event_dns.py
229 lines (169 loc) · 9.53 KB
/
worker_scaling_event_dns.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import argparse
import logging
import json
import configparser
import modules.route53
import modules.ec2
logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--event-type", nargs="?", default="autoscaling:EC2_INSTANCE_LAUNCH", dest="event_type",
help="The event type, launch or terminate. Defaults to autoscaling:EC2_INSTANCE_LAUNCH")
parser.add_argument("-e", "--ec2-instance-id", nargs="?", default="i-db11935b", dest="ec2_instance_id",
help="The ec2 instance to work on.")
return parser.parse_args()
def lambda_handler(event, context):
"""
Execute this on AWS Lambda. This is the entry point for Lambda and for it to pass in params.
:param event:
:param context:
:return:
"""
logging.getLogger().setLevel(logging.DEBUG)
logging.info('got event: {}'.format(event))
logging.info('got context: {}'.format(context))
# Location of the SNS message
logging.info("XXXXXX")
#logging.info(event['Records'][0]['Sns']['Message'])
sns_message_dict = json.loads(event['Records'][0]['Sns']['Message'])
logging.info(json.loads(event['Records'][0]['Sns']['Message']))
logging.info("EC2 Instance: "+sns_message_dict['EC2InstanceId'])
event_type = sns_message_dict['Event']
main(event_type, sns_message_dict['EC2InstanceId'])
return False
def main(event_type, ec2_instance_id):
"""
Main function for this worker no matter what the entry point is (Lambda, CLI)
:return:
"""
if event_type == "autoscaling:EC2_INSTANCE_LAUNCH":
ec2_launch_event(ec2_instance_id)
if event_type == "autoscaling:EC2_INSTANCE_TERMINATE":
ec2_terminate_event(ec2_instance_id)
def ec2_launch_event(ec2_instance_id):
"""
When an ec2 instance launches it will add the health checks and dns records for the node
"""
# config
settings = configparser.ConfigParser()
settings.read('config.ini')
logging.info("Event: ec2_launch_event")
logging.info("Working on ec2-instance id: "+ec2_instance_id)
logging.info("Using route53 hosted zone id: "+settings.get('route53', 'hosted_zone'))
logging.info("Domain name: "+settings.get('route53', 'domain_name'))
# Get instance information
ec2 = modules.ec2.Ec2()
response_ec2_describe = ec2.describe_instances(ec2_instance_id)
logging.debug(response_ec2_describe)
logging.info("Instance public dns: "+response_ec2_describe['Reservations'][0]['Instances'][0]['PublicDnsName'])
logging.info("Instance public IP: "+response_ec2_describe['Reservations'][0]['Instances'][0]['PublicIpAddress'])
# Filter on the machine_filter config value to determine if we want to add this machine into the DNS
machine_tag_value = ec2.get_tag_from_describe_instance_response(response_ec2_describe,
settings.get('machine_filter', 'ec2_tag_key'))
if settings.get('machine_filter', 'ec2_tag_value') == machine_tag_value:
logging.info("This machine passes the machine_filter. Add to DNS. "+machine_tag_value)
# init route53 object
route53 = modules.route53.Route53()
health_check_config_dict = {
'Port': int(settings.get('health_check', 'port')),
'Type': settings.get('health_check', 'protocol_type'),
'ResourcePath': settings.get('health_check', 'ResourcePath'),
'FullyQualifiedDomainName': response_ec2_describe['Reservations'][0]['Instances'][0]['PublicDnsName'],
'RequestInterval': int(settings.get('health_check', 'RequestInterval')),
'FailureThreshold': int(settings.get('health_check', 'FailureThreshold')),
}
response_create_health_check = route53.create_health_check(health_check_config_dict)
logging.debug(response_create_health_check)
logging.info("Health check id: "+response_create_health_check['HealthCheck']['Id'])
# Add tag for health check, and also adding additional tags so that we can find the DNS record later.
# We can only delete the DNS A Record if we have all of this information.
response = route53.change_tags_for_resource_health_check(response_create_health_check['HealthCheck']['Id'],
'Name', settings.get('health_check', 'name'))
response = route53.change_tags_for_resource_health_check(response_create_health_check['HealthCheck']['Id'],
'instance-id', ec2_instance_id)
response = route53.change_tags_for_resource_health_check(response_create_health_check['HealthCheck']['Id'],
'instance-public-ip', response_ec2_describe['Reservations'][0]['Instances'][0]['PublicIpAddress'])
# Create DNS record object
route53.set_hosted_zone_id(settings.get('route53', 'hosted_zone'))
# Get the DNS name to a simple or weighted
dns_name = ''
if settings.get('dns_record_type', 'type') == 'simple':
dns_name = ec2_instance_id+'.'+settings.get('route53', 'domain_name')
elif settings.get('dns_record_type', 'type') == 'weighted':
dns_name = settings.get('dns_record_type', 'dns_name')+'.'+settings.get('route53', 'domain_name')
# Add DNS record
resource_record_set_dict = {
'Name': dns_name,
'Type': settings.get('dns_record_set', 'type'),
'SetIdentifier': ec2_instance_id,
'Weight': int(settings.get('dns_record_set', 'Weight')),
'TTL': int(settings.get('dns_record_set', 'TTL')),
'ResourceRecords': [
{
'Value': response_ec2_describe['Reservations'][0]['Instances'][0]['PublicIpAddress']
},
],
'HealthCheckId': response_create_health_check['HealthCheck']['Id']
}
response_create_resource_record_sets = route53.create_resource_record_sets('UPSERT',
resource_record_set_dict,
settings.get('dns_record_set', 'comment'))
logging.debug(response_create_resource_record_sets)
else:
logging.info("This machine is not part of the machine_filter. Not adding to DNS. "+machine_tag_value)
def ec2_terminate_event(ec2_instance_id):
"""
When an ec2 instance is terminated, the DNS record and health check for this server is removed
"""
# config
settings = configparser.ConfigParser()
settings.read('config.ini')
logging.info("Event: ec2_termination_event")
logging.info("Working on ec2-instance id: "+ec2_instance_id)
logging.info("Using route53 hosted zone id: "+settings.get('route53', 'hosted_zone'))
logging.info("Domain name: "+settings.get('route53', 'domain_name'))
# Get the DNS name to a simple or weighted
dns_name = ''
if settings.get('dns_record_type', 'type') == 'simple':
dns_name = ec2_instance_id+'.'+settings.get('route53', 'domain_name')
elif settings.get('dns_record_type', 'type') == 'weighted':
dns_name = settings.get('dns_record_type', 'dns_name')+'.'+settings.get('route53', 'domain_name')
# init route53 object
route53 = modules.route53.Route53()
route53.set_hosted_zone_id(settings.get('route53', 'hosted_zone'))
health_check_id = route53.get_health_check_by_tag('instance-id', ec2_instance_id)
instance_public_ip = route53.get_health_check_tag_value(ec2_instance_id, 'instance-public-ip')
# Delete DNS record
resource_record_set_dict = {
'Name': dns_name,
'Type': settings.get('dns_record_set', 'type'),
'SetIdentifier': ec2_instance_id,
'Weight': int(settings.get('dns_record_set', 'Weight')),
'TTL': int(settings.get('dns_record_set', 'TTL')),
'ResourceRecords': [
{
'Value': instance_public_ip
},
],
'HealthCheckId': health_check_id
}
logging.debug(resource_record_set_dict)
try:
response_delete_resource_record_sets = route53.create_resource_record_sets('DELETE', resource_record_set_dict, '')
logging.debug(response_delete_resource_record_sets)
except:
logging.info("Unable to delete the record set")
logging.info(resource_record_set_dict)
# Search for health check via tag
searched_health_check_id = route53.get_health_check_by_tag('instance-id', ec2_instance_id)
# Delete health check
try:
delete_response = route53.delete_health_check(searched_health_check_id)
except:
logging.info("Unable to delete the health check")
if __name__ == "__main__":
"""
Mainly for running from the CLI.
"""
args = parseArgs()
main(args.event_type, args.ec2_instance_id)