티스토리 뷰

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

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함