SSM Automation
auto stop EC2 instances using AWS System Manager and Cloudwath Events
auto stop ec2 instances with instance id
stop specified ec2 instances
jq . parameters.json
[
{
"ParameterKey": "KeyWord",
"ParameterValue": "SomeKeyword"
},
{
"ParameterKey": "InstanceIds",
"ParameterValue": "[¥"i-xxxx¥",¥"i-yyyy¥"]"
}
]
RoleAutoStop:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sts:AssumeRole
RoleName: !Sub ${KeyWord}_Role_AutoStop
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole
Tags:
- Key: Name
Value: !Sub ${KeyWord}_Role_AutoStop
EvnetRuleAutoStop:
Type: AWS::Events::Rule
Properties:
Description: Event rule to stop instances automatically
Name: !Sub ${KeyWord}-AutoStopInstances
ScheduleExpression: cron(0 11 * * ? *)
#RoleArn: !GetAtt RoleAutoStop.Arn
State: ENABLED
Targets:
- Arn: 'arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StopEC2Instance:$DEFAULT'
Id: StopEc2
RoleArn: !GetAtt RoleAutoStop.Arn
Input: !Sub '{"InstanceId": ${InstanceIds}}'
auto stop ec2 instances with tag
stop ec2 instances with StopTime tag
AllowTagGetResources:
Type: AWS::IAM::Policy
Properties:
PolicyName: !Sub ${KeyWord}_allow_tag_getresources
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- tag:GetResources
Resource: '*'
Roles:
- !Ref RoleAutoStop
StopEC2InstancesWithTag:
Type: AWS::SSM::Document
Properties:
DocumentFormat: YAML
DocumentType: Automation
Tags:
- Key: Name
Value: !Sub ${KeyWord}_StopEC2InstancesWithTag
Content:
description: StopEC2Instances Using Tags:StopTime
schemaVersion: "0.3"
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
StopTime:
type: String
default: 6pm
description: (Required) 6pm,7pm,8pm
allowedValues:
- 6pm
- 7pm
- 8pm
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:StopTime
Values:
- "{{ StopTime }}"
EvnetRuleAutoStopWithTag:
Type: AWS::Events::Rule
Properties:
Description: Event rule to stop instances automatically with tag
Name: !Sub ${KeyWord}-AutoStopInstances-with-tag
ScheduleExpression: cron(0 10 * * ? *)
State: ENABLED
Targets:
- Arn: !Sub arn:aws:ssm:ap-northeast-1::automation-definition/${StopEC2InstancesWithTag}:$DEFAULT
Id: StopEc2
RoleArn: !GetAtt RoleAutoStop.Arn
Input: !Sub '{"StopTime": ["7pm"]}'