Created
April 23, 2021 04:15
-
-
Save testpilot031/fc477a8b885d5fa141849ae9597e0ff8 to your computer and use it in GitHub Desktop.
lambda_ec2_start_alb_rds_modify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
import sys | |
import boto3 | |
import time | |
import datetime | |
# import requests | |
# ログの時間出力用 | |
dt_now = datetime.datetime.now() | |
def now_string(dt_format="%Y/%m/%d %H:%M:%S"): | |
return datetime.datetime.now().strftime(dt_format) | |
# ログ出力用 | |
def output(s, fp=sys.stdout): | |
fp.write('[{}] '.format(now_string())) | |
fp.write(s) | |
fp.write('\n') | |
fp.flush() | |
output_fp = sys.stdout | |
# 定数 | |
# Lambdaの環境変数から取得するようにしたい | |
# example parameter | |
# REGION= 'ap-northeast-1' | |
# print(os.environ['EC2_INSTANCE_ID']) | |
REGION= 'us-east-2' | |
ALB_TARGET_GROUP_EXAMPLE_ARN = "xxx" | |
INSTANCE_EC2_ID = 'xxx' | |
INSTANCE_RDS_ID = 'xxx' | |
def lambda_handler(event, context): | |
""" | |
Sammary | |
1. EC2を起動 | |
2. ALBのリスナーグループへ追加 | |
3. RDSのスケールアップ | |
""" | |
""" | |
1. EC2を起動 | |
""" | |
message="" | |
ec2 = boto3.resource('ec2', REGION) | |
instance = ec2.Instance(INSTANCE_EC2_ID) | |
response_start = instance.start(DryRun=False) | |
print(response_start) | |
instance.wait_until_running() | |
""" | |
2. ALBのリスナーグループへ追加 | |
""" | |
elb = boto3.client('elbv2') | |
response_register_targets = elb.register_targets( | |
TargetGroupArn= ALB_TARGET_GROUP_EXAMPLE_ARN, | |
Targets=[ | |
{ | |
'Id': INSTANCE_EC2_ID, | |
'Port': 80, | |
}, | |
] | |
) | |
print(response_register_targets) | |
# | |
# Memo: | |
# response_register_targets の例 | |
# {'ResponseMetadata': {'RequestId': 'a5f21423-c856-458e-aa7a-535a87c8780a', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'a5f21423-c856-458e-aa7a-535a87c8780a', 'content-type': 'text/xml', 'content-length': '253', 'date': 'Thu, 22 Apr 2021 14:00:01 GMT'}, 'RetryAttempts': 0}} | |
# | |
""" | |
3. RDSのスケールアップ | |
""" | |
rds = boto3.client('rds') | |
# | |
# ToDo: 済 | |
# RDSのステータスがstartであることを確認後停止としたい→インスタンスタイプは起動中のみ変更可能 | |
# 停止する前にRDSのスナップショットとるか→上記の理由で対応しない | |
# 停止後にスケールアップしたい→インスタンスのタイプを変更する実装をした | |
# | |
response_describe_db_instances = rds.describe_db_instances( | |
DBInstanceIdentifier=INSTANCE_RDS_ID, | |
) | |
print(response_describe_db_instances) | |
# | |
# Memo: | |
# response_describe_db_instances の中身は以下を参照 | |
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances | |
# | |
db_instance_status = response_describe_db_instances['DBInstances'][0]['DBInstanceStatus'] | |
print(db_instance_status) | |
response_modify_db_instance = rds.modify_db_instance( | |
DBInstanceIdentifier = INSTANCE_RDS_ID, | |
DBInstanceClass = 'db.m5.xlarge', | |
ApplyImmediately=True | |
) | |
print(response_modify_db_instance) | |
output('modify wait', output_fp) | |
rds = boto3.client('rds') | |
response_describe_db_instances = rds.describe_db_instances( | |
DBInstanceIdentifier=INSTANCE_RDS_ID, | |
) | |
if not(response_describe_db_instances['DBInstances']): | |
exit | |
db_instance_info = response_describe_db_instances['DBInstances'][0] | |
# | |
# Memo: | |
# modifyが完了したタイミングを把握したい。 | |
# modifyのコマンドをApplyImmediately=Trueのオプションを付けて実行すると | |
# DBInstanceStatusの値は以下のように変化する | |
# 1. available | |
# 2. modifying | |
# 3. available | |
# modifyが完了したタイミングは3. availableとなる。 | |
# 3. availableを把握するために以下の対応を実施 | |
# while文は 1. available => 2. modifyingになるまで待つ処理 | |
# available_waiterは 2. modifying => 3. available になるまで待つ処理 | |
# 1. available => 2. modifyingになるまで待つ | |
# ToDo :済 | |
# PendingModifiedValues の値が入っていれば(True) | |
while db_instance_info['PendingModifiedValues']: | |
output('modify pending ...', output_fp) | |
print(db_instance_info['PendingModifiedValues']) | |
print(db_instance_info['DBInstanceStatus']) | |
print(db_instance_info['DBInstanceClass']) | |
if db_instance_info['DBInstanceStatus'] != 'available': | |
break | |
time.sleep(10) | |
rds = boto3.client('rds') | |
response_describe_db_instances = rds.describe_db_instances( | |
DBInstanceIdentifier=INSTANCE_RDS_ID, | |
) | |
if not(response_describe_db_instances['DBInstances']): | |
exit | |
db_instance_info = response_describe_db_instances['DBInstances'][0] | |
output('modifying', output_fp) | |
# 2. modifying => 3. available になるまで待つ | |
available_waiter = rds.get_waiter('db_instance_available') | |
available_waiter.wait( | |
DBInstanceIdentifier=INSTANCE_RDS_ID | |
) | |
output('modify end', output_fp) | |
if len(message) > 0: | |
topic = 'arn:aws:sns:us-east-1:xxxxx:send-mail' # 送付したいARNを入力 | |
subject = 'StatusRunningEC2 & RDS' | |
sns = boto3.client('sns') | |
response = sns.publish( | |
TopicArn=topic, | |
Message=message, | |
Subject=subject, | |
MessageStructure='raw' | |
) | |
return { | |
"statusCode": 200, | |
"body": json.dumps({ | |
"message": "hello world", | |
# "location": ip.text.replace("\n", "") | |
}), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment