AWS: EC2インスタンスの自動起動と自動停止
EC2インスタンスのタグを参照してスケジュールで自動起動と自動停止を行えるような設定を行いたい。
- 自動起動
- [Tag] EC2AutoStart = true
- [AWS Systems Manager ドキュメント] StartEC2Instances
- 自動停止
- [Tag] EC2AutoStop = true
- [AWS Systems Manager ドキュメント] StopEC2Instances
まずはSystems ManagerのドキュメントでStartEC2InstancesとStopEC2Instancesを作成する。作成は東京リージョンで行う。
description: |-
Start EC2 instances.
schemaVersion: '0.3'
parameters:
TagName:
type: String
description: ''
default: EC2AutoStart
mainSteps:
- name: StartEC2Instances
action: 'aws:executeAwsApi'
inputs:
Service: ssm
Api: StartAutomationExecution
DocumentName: AWS-StartEC2Instance
TargetParameterName: InstanceId
Targets:
- Key: 'tag:{{ TagName }}'
Values:
- 'true'
description: |-
Stop EC2 Instances.
schemaVersion: '0.3'
parameters:
TagName:
type: String
description: ''
default: EC2AutoStop
mainSteps:
- name: StopEC2Instances
action: 'aws:executeAwsApi'
inputs:
Service: ssm
Api: StartAutomationExecution
DocumentName: AWS-StopEC2Instance
TargetParameterName: InstanceId
Targets:
- Key: 'tag:{{ TagName }}'
Values:
- 'true'
自動起動、自動停止はEvent Bridgeで行うので、Event Bridge用のIAMロールを作成する。
- [Role] EventBridge_EC2ControlRole
- [Policy(AWS)] AmazonSSMAutomationRole
- [Policy(Customer)] EventBridge_EC2ControlPolicy
- [Principal]
- [Service] ssm.amazonaws.com
- [Service] events.amazonaws.com
EventBridge_EC2ControlPolicyではEC2の起動と停止を許可するポリシーとする。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:StopInstances",
"ec2:StartInstances"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "tag:GetResources",
"Resource": "*"
}
]
}
EventBridgeの設定は次のように進める。(Systems Managerのドキュメントを使用するので同じリージョン、今回は東京リージョンでイベントを作成する)



自動停止のイベントも同様に作成する。
テスト構築時などは手動起動するので自動起動が不要などの場合はイベントを無効化して置くかEC2インスタンスのタグを変更して置く。
