티스토리 뷰
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Resource Id
Parameters:
- EC2TagKey
- EC2TagValue
- Label:
default: Start/Stop Time
Parameters:
- StartTimeInGMT
- StopTimeInGMT
Parameters:
EC2TagKey:
Description: EC2TagKey
Type: String
Default: Service
EC2TagValue:
Description: EC2TagValue
Type: String
Default: test
StartTimeInGMT:
Description: Start hour in GMT
Default: 0
Type: Number
StopTimeInGMT:
Description: Stop hour in GMT
Default: 9
Type: Number
Resources:
AutomationServiceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- ssm.amazonaws.com
- ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole
Path: "/"
EC2OnOffLambdaExeRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "ssm:*"
- "tag:*"
Resource: "*"
- Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- "iam:PassRole"
Resource: !Sub
- "${AutomationServiceRoleArn}"
- AutomationServiceRoleArn:
Fn::GetAtt:
- "AutomationServiceRole"
- "Arn"
StopStartEC2Lambda:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Role:
Fn::GetAtt:
- "EC2OnOffLambdaExeRole"
- "Arn"
Runtime: "nodejs12.x"
# we give the function a large timeout
# so we can wait for the bucket to be empty
Timeout: 600
Code:
ZipFile: |
var AWS = require("aws-sdk");
AWS.config.update({
region: "ap-northeast-2"
});
exports.handler = async function (event, context) {
console.log("event:",event);
var ssm = new AWS.SSM();
var params = {
DocumentName: (event.action=="stop")?'AWS-StopEC2Instance':'AWS-StartEC2Instance',
Parameters: {
'AutomationAssumeRole': [event.rolearn ],
},
MaxConcurrency: '10' ,
MaxErrors: '25%',
TargetParameterName:"InstanceId",
Targets: [
{
Key: `tag:${event.key}`,
Values: [event.value]
},
]
};
try
{
const result=await ssm.startAutomationExecution(params).promise();
console.log(result);
}
catch(e)
{
console.log(e);
}
};
CloudWatchEventStartRule:
Type: AWS::Events::Rule
Properties:
Description: startrule
ScheduleExpression: !Sub
- "cron(0 ${StartTimeInGMT} ? * 1-5 *)"
- StartTimeInGMT: !Ref StartTimeInGMT
Targets:
- Arn: !GetAtt StopStartEC2Lambda.Arn
Id: start-ec2
Input: !Sub
- '{"key":"${EC2TagKey}","value":"${EC2TagValue}","rolearn":"${AutomationServiceRoleArn}","action":"start"}'
- AutomationServiceRoleArn:
Fn::GetAtt:
- "AutomationServiceRole"
- "Arn"
CloudWatchEventStopRule:
Type: AWS::Events::Rule
Properties:
Description: stoprule
ScheduleExpression: !Sub
- "cron(0 ${StopTimeInGMT} ? * 1-5 *)" #오전 9시 이전일 경우, 0 ${StopTimeInGMT} ? * 2-6 *
- StopTimeInGMT: !Ref StopTimeInGMT
Targets:
- Arn: !GetAtt StopStartEC2Lambda.Arn
Id: stop-ec2
Input: !Sub
- '{"key":"${EC2TagKey}","value":"${EC2TagValue}","rolearn":"${AutomationServiceRoleArn}","action":"stop"}'
- AutomationServiceRoleArn:
Fn::GetAtt:
- "AutomationServiceRole"
- "Arn"
PermissionForEventsCallStartLambda:
Type: AWS::Lambda::Permission
DependsOn: CloudWatchEventStartRule
Properties:
FunctionName:
Ref: StopStartEC2Lambda
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn:
Fn::GetAtt:
- "CloudWatchEventStartRule"
- "Arn"
PermissionForEventsCallStopLambda:
Type: AWS::Lambda::Permission
DependsOn: CloudWatchEventStopRule
Properties:
FunctionName:
Ref: StopStartEC2Lambda
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn:
Fn::GetAtt:
- "CloudWatchEventStopRule"
- "Arn"
**SOURCE : https://www.youtube.com/watch?v=mRq0VvXA-j8
'AWS > EC2' 카테고리의 다른 글
EC2 키 페어 분실 또는 없을 시 해결 방법 (0) | 2022.07.08 |
---|---|
서비스 enable 방법 (feat. pm2) (0) | 2021.10.14 |
AWS AMI 생성 후 AutoScaling 그룹 시작 템플릿에 적용 (0) | 2021.07.02 |
AWS Cloudwatch Agent 설치 및 wizard 설정 (1) | 2021.07.02 |
AWS AMI 생성 후 AutoScaling 그룹 시작 템플릿에 적용 (0) | 2021.07.01 |