LoginSignup
1
1

More than 1 year has passed since last update.

特定のタグがついたEC2インスタンスを自動停止する

Last updated at Posted at 2022-11-23

ゴール

特定のタグがついたEC2インスタンスを自動停止する。

参考

基本は以下ページを参考にさせていただき実施しました。

が、ハマりポイントもあったので、ハマりポイントだけ忘れないために残しておきたいと思います。

構成

構成はシンプルに以下の通りです。

ssm.png

なお、EventBridge の新機能に、Amazon EventBridge Schedulerという機能も登場しましたが、今回は既存の Amazon EventBridge rules でも、SSM Automation は実行できるため、既存のものを利用しています。

Amazon EventBridge rules と Amazon EventBridge Scheduler の違いについては以下の記事が参考になります。

SSMドキュメント

SSMドキュメントの箇所は、パラメータとタグだけ修正して以下の通り作成しました。

description: StopEC2Instances Using Tags:StopTime
schemaVersion: "0.3"
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
  StopTime:
    type: String
    default: test
    description: (Required) test
    allowedValues:
    - test
  AutomationAssumeRole:
    type: String
    description: (Optional) The ARN of the role that allows Automation to perform the actions on your behalf.
    default: ""
mainSteps:
  - name: StopEC2Instances
    action: aws:executeAwsApi
    inputs:
      Service: ssm
      Api: StartAutomationExecution
      DocumentName: AWS-StopEC2Instance
      TargetParameterName: "InstanceId"
      Targets:
        -
           Key: tag:env
           Values: 
             - "{{ StopTime }}"

IAMロール

IAMロールには、AWS管理マネージドポリシーのAmazonSSMAutomationRoleを付与しました。

実行1

SSM Automation から実行結果を確認してみます。

失敗しました。

スクリーンショット 2022-11-23 17.59.39.png

上記の「ステップID」をクリックしてみます。

スクリーンショット 2022-11-23 17.59.49.png

tag:GetResources のIAMポリシーが足りないようです。

IAMポリシーの追加

tag:GetResources のIAMポリシーを作成し、IAMロールにアタッチします。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "tag:GetResources",
            "Resource": "*"
        }
    ]
}

実行2

次の通り、正常に特定のタグがついたEC2インスタンスが停止されたことが確認できました。

SSM Automation から。
スクリーンショット 2022-11-23 18.06.06.png

EC2 から。
スクリーンショット 2022-11-23 18.07.35.png

1
1
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
1
1