-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalb_instance_exchange.py
More file actions
97 lines (85 loc) · 3.01 KB
/
alb_instance_exchange.py
File metadata and controls
97 lines (85 loc) · 3.01 KB
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
import boto3
import json
import time
elbv2_client = boto3.client('elbv2')
ec2_client = boto3.client('ec2')
instance_id1 = '1台目のインスタンスID'
instance_id2 = '2台目のインスタンスID'
target_group_arn = 'ターゲットグループのARN'
def lambda_handler(event, context):
Message = json.loads(event['Records'][0]['Sns']['Message'])
deregister_instance_id = Message['Trigger']['Dimensions'][0]['value']
# アラートになったのが1台目のEC2の場合の処理
if deregister_instance_id == instance_id1:
elbv2_client.deregister_targets(
TargetGroupArn=target_group_arn,
Targets=[
{
'Id': deregister_instance_id,
},
]
)
# 2台目のインスタンスを起動
ec2_client.start_instances(
InstanceIds=[instance_id2]
)
# 2台目のインスタンスが起動するまで無限ループさせる
while True:
time.sleep(3)
response = ec2_client.describe_instance_status(
InstanceIds=[instance_id2]
)
if len(response['InstanceStatuses']) > 0:
instance_status = response['InstanceStatuses'][0]['InstanceState']['Name']
if instance_status == 'running':
break
# ターゲットグループへアタッチ
elbv2_client.register_targets(
TargetGroupArn=target_group_arn,
Targets=[
{
'Id': instance_id2,
},
]
)
# 1台目のインスタンスを停止
ec2_client.stop_instances(
InstanceIds=[deregister_instance_id]
)
# アラートになったのが2台目のEC2の場合の処理
else:
elbv2_client.deregister_targets(
TargetGroupArn=target_group_arn,
Targets=[
{
'Id': deregister_instance_id,
},
]
)
# 1台目のインスタンスを起動
ec2_client.start_instances(
InstanceIds=[instance_id1]
)
# 2台目のインスタンスが起動するまで無限ループさせる
while True:
time.sleep(3)
response = ec2_client.describe_instance_status(
InstanceIds=[instance_id1]
)
if len(response['InstanceStatuses']) > 0:
instance_status = response['InstanceStatuses'][0]['InstanceState']['Name']
if instance_status == 'running':
break
# ターゲットグループへアタッチ
elbv2_client.register_targets(
TargetGroupArn=target_group_arn,
Targets=[
{
'Id': instance_id1,
},
]
)
# 2台目のインスタンスを停止
ec2_client.stop_instances(
InstanceIds=[deregister_instance_id]
)