LoginSignup
5
4

More than 5 years have passed since last update.

lambdaでAuroraを停止する

Posted at

やりたいこと

lambdaでAuroraを停止したい!

ただし前回同様の手順で行おうとすると、エラーが出ます。
エラーは以下の通り。

'RDS' object has no attribute 'stop_db_cluster'

調べると以下がひっかかります。
https://github.com/boto/boto3/issues/1723
lambdaがデフォルトで使用するboto3にはまだstop_db_clusterが実装されていないということですね。

というわけで基本的には前回と同様の手順を踏みますが、lambda関数をデプロイする部分だけ変更します。

準備

デプロイ用のディレクトリを作成します。

$ mkdir stop-aurora

上記ディレクトリに以下のpythonのファイルをおきます。

stop-aurora.py

import boto3


def lambda_handler(event, context):
    dbcluster = 'testdb'
    client = boto3.client('rds')
    response = client.stop_db_cluster(DBInstanceIdentifier=dbcluster)
    print(response)
    return 0                          

デプロイパッケージの作成

以下のドキュメントにしたがってパッケージを作成します。
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html

1.最新のboto3をダウンロードする

$ pip3 install boto3 -t ./stop-aurora

2.zip圧縮する

$ cd stop-aurora
$ zip -r stop-aurora .

ここで注意したいのは、ドキュメントにもある以下の内容です。

ディレクトリ自体ではなく、ディレクトリ内に含まれているディレクトリのコンテンツを圧縮します。ZIP ファイルの内容は、Lambda 関数の現在の作業ディレクトリとして利用できます (例: /project-dir/codefile.py/lib/yourlibraries)。この場合、/project-dir に含まれているコンテンツを圧縮します。

ディレクトリ自体を圧縮してしまうとlambda実行時に以下のエラーが出るので注意してください

"errorMessage": "Bad handler 'lambda_handler'"

3.aws cliで関数を作成する

以下のコマンドで作成できます。

$ aws lambda create-function \
--function-name stop-aurora \
--runtime python3.6 \
--role <lambda作成用ロール> \
--handler stop-aurora.lambda_handler \
--zip-file fileb://stop-aurora.zip

test-aurora.png

関数ができています!やったね!

あとは前回と同様の手順で実行できます。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4