TBD

仕事の事・日常の事

CloudFormationでEC2自動起動・停止

よく忘れるので備忘録。

AWSTemplateFormatVersion: 2010-09-09

Resources:
  #########################
  # IAM
  #########################
  CloudWatchEventsRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - 
            Effect: Allow
            Principal:
              Service:
                - events.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMFullAccess

  #########################
  # Stop
  #########################
  EventRuleEc2Stop:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0 18 ? * 1-5 *)
      State: ENABLED
      Targets:
        - Arn: arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StopEC2Instance:$LATEST
          Id: SshStop
          RoleArn: !GetAttCloudWatchEventsRoleArn
          Input: !Sub '{"InstanceId":["${Ec2Instance}"]}'

  #########################
  # Start
  #########################
  EventRuleEc2Start:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0 23 ? * 1-5 *)
      State: ENABLED
      Targets:
        - Arn: "arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartEC2Instance:$LATEST
          Id: SshStart
          RoleArn: !GetAttCloudWatchEventsRoleArn
          Input: !Sub '{"InstanceId":["${Ec2Instance}"]}'