/
ec2_term_handler.py
230 lines (185 loc) · 6.85 KB
/
ec2_term_handler.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
228
229
230
from __future__ import print_function
import time
import json
import boto3
from pyzabbix import ZabbixAPI
zabbix_api = 'http://myzabbixserver.com/zabbix'
zabbix_user = 'ec2manager'
zabbix_pass = 'mypass'
dns_zone_id = 'ID-OF-THE-ZONE-ON-ROUTE53'
print('Loading function')
def init_session():
s = boto3.session.Session()
return s
def init_ec2():
s = init_session()
return s.resource('ec2')
def init_route53():
return boto3.client('route53')
def get_dns_zone_name(zone_id):
try:
route53 = init_route53()
response = route53.get_hosted_zone(Id=zone_id)
return response['HostedZone']['Name']
except Exception as e:
print("route53_zone_name ERROR: %s" % str(e))
return None
dns_zone = get_dns_zone_name(dns_zone_id)
def get_instance_name(instance):
try:
for itag in instance.tags:
if itag['Key'] == 'Name':
return itag['Value']
except Exception as e:
print("get_instance_name ERROR: %s" % str(e))
return None
def find_instance(instance_id):
print("Looking for instance: %s" % instance_id)
try:
count = 0
while(count < 20):
ec2 = init_ec2()
for i in ec2.instances.all():
if i.id == instance_id:
print(i)
instance_name = get_instance_name(i)
instance_ip = i.private_ip_address
if instance_name:
print("Found instance %s with ip %s" %
(instance_name, instance_ip))
return (instance_name, instance_ip)
time.sleep(30)
count += 1
except Exception as e:
print("find_instance ERROR: %s" % str(e))
print("There is no instance %s" % instance_id)
return (None, None)
def get_ip_address_from_dns(fqdn):
try:
route53 = init_route53()
response = route53.list_resource_record_sets(HostedZoneId=dns_zone_id)
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
for rrset in response['ResourceRecordSets']:
if rrset['Name'].lower() == fqdn.lower():
return rrset['ResourceRecords'][0]['Value']
except Exception as e:
print("Error getting ip address: %s" % str(e))
return None
def add_dns_record(instance_name, instance_ip):
fqdn = instance_name + '.' + dns_zone
current_ip = get_ip_address_from_dns(fqdn)
if current_ip:
if current_ip == instance_ip:
return None
else:
remove_dns_record(instance_name)
print("Adding DNS record for: [%s] [%s]" % (fqdn, instance_ip))
response = None
try:
route53 = init_route53()
response = route53.change_resource_record_sets(
HostedZoneId=dns_zone_id,
ChangeBatch={
'Comment': 'comment',
'Changes': [
{
'Action': 'CREATE',
'ResourceRecordSet': {
'Name': fqdn,
'Type': 'A',
'TTL': 60,
'ResourceRecords': [
{
'Value': instance_ip
},
],
}
},
]
}
)
except Exception as e:
print("Route53 error: %s" % str(e))
else:
print("RESPONSE:", response)
return response
def remove_dns_record(instance_name):
fqdn = instance_name + '.' + dns_zone
instance_ip = get_ip_address_from_dns(fqdn)
print("Removing DNS record for: [%s] [%s]" % (fqdn, instance_ip))
response = None
if not instance_ip:
print("Can't find ip address in DNS for %s, skipping." % fqdn)
return response
try:
route53 = init_route53()
response = route53.change_resource_record_sets(
HostedZoneId=dns_zone_id,
ChangeBatch={
'Comment': 'comment',
'Changes': [
{
'Action': 'DELETE',
'ResourceRecordSet': {
'Name': fqdn,
'Type': 'A',
'TTL': 60,
'ResourceRecords': [
{
'Value': instance_ip
},
],
}
},
]
}
)
except Exception as e:
print("Route53 error: %s" % str(e))
else:
print("RESPONSE:", response)
return response
def disable_on_zabbix(instance_name):
zapi = ZabbixAPI(zabbix_api)
zapi.login(zabbix_user, zabbix_pass)
hosts = zapi.host.get(filter={
"name": instance_name
})
if len(hosts) > 0 and 'hostid' in hosts[0]:
hostid = hosts[0]['hostid']
print("Disabling on Zabbix: %s %s" %
(instance_name, hostid))
zapi.host.update(hostid=hostid, status=1)
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
if 'region' in event and 'detail' in event:
detail = event['detail']
if 'state' in detail and 'instance-id' in detail:
instance_id = detail['instance-id']
if detail['state'] == 'terminated':
print("Termination of EC2 instance [%s] detected."
" Let's cleanup!" % instance_id)
instance_name, instance_ip = find_instance(instance_id)
if not instance_name:
print("Failed to figure out instance name")
else:
print("DETAILS - instance_id: [%s]"
" instance_name: [%s]"
" instance_ip: [%s]" %
(instance_id, instance_name, instance_ip))
disable_on_zabbix(instance_name)
remove_dns_record(instance_name)
elif detail['state'] == 'running':
print("Startup of EC2 instance [%s] detected."
" Let's go!" % instance_id)
instance_name, instance_ip = find_instance(instance_id)
if not instance_name:
print("Failed to figure out instance name")
elif not instance_ip:
print("Failed to figure out instance ip address")
else:
print("DETAILS - instance_id: [%s]"
" instance_name: [%s]"
" instance_ip: [%s]" %
(instance_id, instance_name, instance_ip))
add_dns_record(instance_name, instance_ip)