こんにちは。
先日、開発チームのコスト削減の一環で、開発環境のAuroraをDailyで確認し、起動されていたら、自動的に停止するスクリプトを書きました。
そんなに大したことではないのですが、なんかまたありそうなネタなので、自分のブログでまとめておこうかなと思います。
作るもの
今回作るものは、以下の仕様を満たしたものになります。
- CloudWatchEventから、日本時間の0:00にLambdaを起動する
- Lambdaが、AuroraのClusterが起動されているかを確認し、起動されていたら停止する処理を実行する
- CloudWathcEventとLambdaは、SAMから環境を構築する(コードで管理したい)
SAMでLambdaを作る
今回は、SAM(Serverless Application Model)を使って、Lambdaを作ります。
SAMとは
Serverless Application Modelの略で、サーバーレスアプリケーションを立ち上げるためのオープンソースのフレームワークです。以下が本家のサイトです。
DynamoDBやAPI Gatewayなど、よくある使われ方の紹介がされている入門としては、以下のチュートリアルがわかりやすかったです。
SAMの初期設定
まずはテンプレートとなる物を作ります。以下のコマンドを打ちます。
$ sam init -r python3.7 -n aurora-auto-stopper
すると、いくつかの選択をすると、以下のような感じになります。
Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git AWS quick start application templates: 1 - Hello World Example 2 - EventBridge Hello World 3 - EventBridge App from scratch (100+ Event Schemas) Template selection: 1 ----------------------- Generating application: ----------------------- Name: aurora-auto-stopper Runtime: python3.7 Dependency Manager: pip Application Template: hello-world Output Directory: . Next steps can be found in the README file at ./aurora-auto-stopper/README.md
作成されたフォルダ構成は以下の通りです。
$ cd aurora-auto-stopper $ tree . . ├── README.md ├── events │ └── event.json ├── hello_world │ ├── __init__.py │ ├── app.py │ └── requirements.txt ├── template.yaml └── tests └── unit ├── __init__.py └── test_handler.py
hello world
アプリを初期設定では作ったので、hello_world
というフォルダを src
というように変えます。
$ mv hello_world src
これで初期設定は完了です。
template.yaml
を編集する
template.yaml
を以下のように書き換えます。
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > aurora-auto-stopper Globals: Function: Timeout: 180 MemorySize: 256 Resources: AuroraAutoStopperFunction: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.lambda_handler Runtime: python3.7 Policies: AmazonRDSFullAccess Events: AuroraAutoStopEvent: Type: Schedule Properties: Schedule: cron(0 15 ? * * *)
timeoutとかはこんなにいらないんですが、まぁ一応長めに設定しました。
S3のバケットを作成する
SAMは、パッケージングという処理をするのですが、その過程で生成される中間成果物をS3におく必要があるので、その置き場をS3バケットに作成します。
$ aws s3 mb s3://sample-bucket
LambdaでAuroraを止める処理を書く
次に、LambdaでAuroraを止める処理を書いていきます。以下のように、Clusterごと止める処理を、 src/app.py
書きます。
import boto3 def lambda_handler(event, context): # cluster info db_cluster = 'clustor-name' region = 'ap-northeast-1' # stop cluster client = boto3.client('rds', region) rds_clusters = client.describe_db_clusters(DBClusterIdentifier=db_cluster) print(rds_clusters) rds_cluster = rds_clusters['DBClusters'][0] if rds_cluster['Status'] == 'available': response = client.stop_db_cluster(DBClusterIdentifier=db_cluster) print(response) print('Stop') else: print('Already Stop')
Deploy
ここまでできれば、deployをすることができます。deployは以下のコマンドで実行することができます。
$ sam build $ sam package \ --output-template-file ./packaged.yaml \ --s3-bucket aurora-auto-stopper $ sam deploy \ --template-file ./packaged.yaml \ --capabilities CAPABILITY_IAM \ --stack-name aurora-auto-stopper \ --region ap-northeast-1
以上でSAMを使って、LambdaでAuroraを自動停止させるプログラムがかけます。
説明端折りまくってますが、まぁ自分用のメモなので、ご勘弁を。それでは。