2025/09/06

EventBridge

## EventBridgeの動作概要
### EC2とRDSインスタンスを停止・起動する例
Update: [Amazon EventBridge が IAM 実行ロールのサポートをすべてのターゲットに拡大](https://aws.amazon.com/jp/about-aws/whats-new/2025/03/amazon-eventbridge-iam-execution-role-all-targets/)

現在は、ターゲット側のリソースベースポリシーによる制御( AWS::Lambda::Permission )でなく、イベントソース側のロール指定で制御可能となっている。

```
AWSTemplateFormatVersion: 2010-09-09
Description: The template for creating EventBridge Schedule.
# -------------------------
# Metadata 
# -------------------------
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: Schedule Configuration
        Parameters:
          - EC2InstanceId
          - RDSInstanceId
          - ScheduleExpressionForStop
          - ScheduleExpressionForStart

# -------------------------
# <<< Parameters 
# -------------------------
Parameters:
  EC2InstanceId:
    Type: String

  RDSInstanceId:
    Type: String

  ScheduleExpressionForStop:
    Type: String
    Default: cron(0 13 * * ? *)  # UTC 0時 → JST 22時
    
  ScheduleExpressionForStart:
    Type: String
    Default: cron(0 23 * * ? *)  # UTC 23時 → JST 8時

Resources:
  #==========================
  # IAM Role for Lambda
  #==========================
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: LambdaSchedulerRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - arn:aws:iam::aws:policy/AmazonEC2FullAccess
        - arn:aws:iam::aws:policy/AmazonRDSFullAccess
      PermissionsBoundary: !Sub 'arn:aws:iam::${AWS::AccountId}:policy/DevelopUserBoundary'

  #==========================
  # Lambda Function
  #==========================
  SchedulerFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: EC2RDS-Scheduler
      Runtime: python3.9
      Handler: index.lambda_handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Timeout: 90
      Code:
        ZipFile: |
          import boto3
          import os

          def lambda_handler(event, context):
              ec2_id = os.environ['EC2_ID']
              rds_id = os.environ['RDS_ID']
              action = event.get('action', 'start') # 初期値(EventBridgeで上書き)

              ec2 = boto3.client('ec2')
              rds = boto3.client('rds')

              if action == 'start':
                  ec2.start_instances(InstanceIds=[ec2_id])
                  rds.start_db_instance(DBInstanceIdentifier=rds_id)
              elif action == 'stop':
                  ec2.stop_instances(InstanceIds=[ec2_id])
                  rds.stop_db_instance(DBInstanceIdentifier=rds_id)

      Environment:
        Variables:
          EC2_ID: !Ref EC2InstanceId
          RDS_ID: !Ref RDSInstanceId

  #==========================
  # EventBridge
  #==========================
  # for Start
  StartSchedule:
    Type: AWS::Events::Rule
    Properties:
      Name: EC2RDSStartSchedule
      ScheduleExpression: !Ref ScheduleExpressionForStart
      State: ENABLED
      Targets:
        - Arn: !GetAtt SchedulerFunction.Arn
          Id: StartTarget
          Input: '{ "action": "start" }'

  # for Stop
  StopSchedule:
    Type: AWS::Events::Rule
    Properties:
      Name: EC2RDSStopSchedule
      ScheduleExpression: !Ref ScheduleExpressionForStop
      State: ENABLED
      Targets:
        - Arn: !GetAtt SchedulerFunction.Arn
          Id: StopTarget
          Input: '{ "action": "stop" }'

  #==========================
  # Lambda Permissions
  #==========================
  # for Start
  PermissionForEventsToInvokeLambda:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref SchedulerFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt StartSchedule.Arn

  # for Stop
  PermissionForEventsToInvokeLambdaStop:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref SchedulerFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt StopSchedule.Arn
```

0 件のコメント:

コメントを投稿

人気の投稿