ゴール
特定のタグがついたEC2インスタンスを自動停止する。
参考
基本は以下ページを参考にさせていただき実施しました。
が、ハマりポイントもあったので、ハマりポイントだけ忘れないために残しておきたいと思います。
構成
構成はシンプルに以下の通りです。
なお、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 から実行結果を確認してみます。
失敗しました。
上記の「ステップID」をクリックしてみます。
tag:GetResources のIAMポリシーが足りないようです。
IAMポリシーの追加
tag:GetResources のIAMポリシーを作成し、IAMロールにアタッチします。
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
実行2
次の通り、正常に特定のタグがついたEC2インスタンスが停止されたことが確認できました。