テスト用の、または重要度の低い AWS Elastic Beanstalk 環境を、スケジュールされた時間に停止して再起動するにはどうすればよいですか?

所要時間3分
0

テスト環境、または重要ではない AWS Elastic Beanstalk 環境を、スケジュールされた時間に終了して再構築したいと考えています。

簡単な説明

API コール terminate-environment および rebuild-environment を使用して、Elastic Beanstalk 環境を停止して再起動できます。終了した環境は、終了から 6 週間 (42 日) 以内に限り再構築できます。

スケジュールに従いこれらの呼び出しを実行するには、Amazon CloudWatch Events でイベントを設定して、毎日特定の時間に AWS Lambda 関数を起動します。その後、これらの Lambda 関数を設定して Elastic Beanstalk API コールを行います。

重要: Elastic Beanstalk 環境またはそのインスタンスに加えたオフバンドの変更は、環境終了後は保持されません。終了時間をメモし、その時間より前にインスタンスを使用する作業をすべて完了してください。ユーザーがそのインスタンスに接続していなくても、インスタンスはスケジュールされた時間に終了します。

次の解決方法のすべてのアクションを実行するには、AWS CloudFormation テンプレートを作成および設定します。テンプレートで、Lambda 用の AWS Identity and Access Management (IAM) ロールを作成する必要があります。その後、テンプレート使用して Lambda 関数を起動し、Lambda 関数を停止して、最後に CloudWatch イベントを開始します。

解決策

前提条件

Elastic Beanstalk 環境の ID (EnvironmentId) を書き留めておいてください。

重要: 次の解決方法では、サービスによって生成されたすべてのタグを Elastic Beanstalk 環境およびリソースから削除できます。

Lambda 関数用の IAM ロールを作成する

1.    Lambda 関数の IAM ロール用に次のようなインラインポリシー (Lambda.json など) を作成します。

$ cat Lambda.json {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com"
        ]
      },
      "Action": [
        "sts:AssumeRole"
      ]
    }
  ]
}

2.    ポリシーを使用して IAM ロールを作成します。

aws iam create-role --role-name elasticbeanstalk-lambda-role --assume-role-policy-document file://Lambda.json

3.    IAM ロールの Amazon リソースネーム (ARN) に注意してください。

4.    次の管理ポリシーを IAM ロールにアタッチします。

aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk --role-name elasticbeanstalk-lambda-role

Lambda 関数のデプロイパッケージを作成する

1.    Elastic Beanstalk 環境を再起動するには、次のコードをテキストエディターに貼り付けます。

import boto3envid=['e-awsenvidid']
client = boto3.client('elasticbeanstalk')
def handler(event, context):
    try:
         for appid in range(len(envid)):
             response = client.rebuild_environment(EnvironmentId=str(envid[appid].strip()))
             if response:
                 print('Restore environment %s' %str(envid[appid]))
             else:
                 print('Failed to Restore environment %s' %str(envid[appid]))

    except Exception as e:
        print(e)

重要: e-awsenvidid を Elastic Beanstalk 環境の ID に置き換えてください。上記のコードの例は Python 3.9 ランタイムに準拠しています。

2.    コードを Python ファイルとして保存します。例: StartElasticBeanstalk.py

3.    Python ファイルを ZIP ファイルとして圧縮します。例: StartElasticBeanstalk.zip

4.    Elastic Beanstalk 環境を終了するには、次のコードをテキストエディターに貼り付けます。

import boto3envid=['e-awsenvidid']
client = boto3.client('elasticbeanstalk')
def handler(event, context):
    try:
         for appid in range(len(envid)):
             response = client.terminate_environment(EnvironmentId=str(envid[appid].strip()))
             if response:
                 print('Terminating environment %s' %str(envid[appid]))
             else:
                 print('Failed to Terminate environment %s' %str(envid[appid]))

    except Exception as e:
        print(e)

重要: e-awsenvidid を Elastic Beanstalk 環境の ID に置き換えてください。

5.    コードを Python ファイルとして保存します。例: StopElasticBeanstalk.py

6.    Python ファイルを ZIP ファイルとして圧縮します。例: StopElasticBeanstalk.zip

Lambda 関数を作成する

注: AWS コマンドラインインターフェイス (AWS CLI) コマンドの実行中にエラーが発生した場合は、「AWS CLI エラーのトラブルシューティング」を参照してください。また、AWS CLI の最新バージョンを使用していることを確認してください。

Elastic Beanstalk 環境を停止して再起動する Lambda 関数を作成するには、AWS CLI で次のコマンドを実行します。

aws lambda create-function \
--function-name StartElasticBeanstalk \
--zip-file fileb://file-path/StartElasticBeanstalk.zip \
--role arn:aws:iam::012345678912:role/elasticbeanstalk-lambda-role \
--handler StartElasticBeanstalk.handler \
--runtime python3.9 --region us-west-2

aws lambda create-function \
--function-name StopElasticBeanstalk \
--zip-file fileb://file-path/StopElasticBeanstalk.zip \
--role arn:aws:iam::012345678912:role/elasticbeanstalk-lambda-role \
--handler StopElasticBeanstalk.handler \
--runtime python3.9 --region us-west-2

重要: us-west-2 を、Elastic Beanstalk 環境が配置されている AWS リージョンに置き換えてください。また、デプロイパッケージ (StartElasticBeanstalk.zip または StopElasticBeanstalk.zip) と IAM ロールの ARN を各コマンドのパラメータとして指定してください。

CloudWatch イベントルールを作成して Lambda 関数を開始する

1.    Lambda 関数を起動および停止するには、次のコマンドを実行します。

aws events put-rule --name "StartLambdaFunction" --schedule-expression "cron(0 8 * * ? *)" --region us-west-2aws events put-rule --name "StopLambdaFunction" --schedule-expression "cron(0 18 * * ? *)" --region us-west-2

注: --schedule-expression プロパティには cron 構文が必要です。必要に応じて --schedule-expression プロパティの値を更新します。us-west-2 を、Elastic Beanstalk 環境が配置されている AWS リージョンに置き換えてください。

2.    CloudWatch イベントのサービスプリンシパル (events.amazonaws.com) を信頼し、アクセス許可の範囲をルールにまで拡大するには、次のコマンドを実行します。

aws lambda add-permission \
--function-name StartElasticBeanstalk \
--statement-id StartLambdaFunction \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-west-2:012345678912:rule/StartLambdaFunction --region us-west-2

aws lambda add-permission \
--function-name StopElasticBeanstalk \
--statement-id StopLambdaFunction \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-west-2:012345678912:rule/StopLambdaFunction --region us-west-2

注: us-west-2 を、Elastic Beanstalk 環境が配置されている AWS リージョンに置き換えてください。

3.    作成した Lambda 関数をこのルールに追加してルールがスケジュールどおりに実行されるようにするには、次の put-targets コマンドを実行します。

aws events put-targets --rule StartLambdaFunction --targets "Id"="1","Arn"="arn:aws:lambda:us-west-2:012345678912:function:StartElasticBeanstalk" --region us-west-2
aws events put-targets --rule StopLambdaFunction --targets "Id"="2","Arn"="arn:aws:lambda:us-west-2:012345678912:function:StopElasticBeanstalk" --region us-west-2

**重要:**各コマンドの ARN を IAM ロールの ARN に置き換えてください。us-west-2 を、Elastic Beanstalk 環境が配置されている AWS リージョンに置き換えてください。

関連情報

Elastic Beanstalk テンプレートスニペット

Lambda デプロイパッケージ

AWS公式
AWS公式更新しました 7ヶ月前
コメントはありません

関連するコンテンツ