Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

Today I Learned - 2026-06-05

今日学んだことを雑多に書く。

Lambda関数をCloudFormationでデプロイする

Lambda 関数を CloudFormation でデプロイしたい。

2026-06-02のTIL で作成した関数をデプロイするテンプレートはこちら。

AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy Lambda for Step Functions start workflow.

Parameters:
  StateMachineArn:
    Type: String
    Description: ARN of the Step Functions state machine to start.

Resources:
  StartStepFunctionLambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: StartStepFunctionPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - states:StartExecution
                Resource: !Ref StateMachineArn

  StartStepFunctionLambda:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: StartStepFunctionLambda
      Runtime: python3.14
      Handler: index.lambda_handler
      Role: !GetAtt StartStepFunctionLambdaExecutionRole.Arn
      Timeout: 60
      Environment:
        Variables:
          STATE_MACHINE_ARN: !Ref StateMachineArn
      Code:
        ZipFile: |
          import boto3
          import json
          import os

          sfn = boto3.client('stepfunctions')

          STATE_MACHINE_ARN = os.environ['STATE_MACHINE_ARN']

          def lambda_handler(event, context):
              input_payload = {
                  "instanceType": event['instanceType'],
                  "clusterId": event['clusterId'],
              }

              response = sfn.start_execution(
                  stateMachineArn=STATE_MACHINE_ARN,
                  input=json.dumps(input_payload)
              )

              return {
                  'statusCode': 200,
                  'executionArn': response['executionArn']
              }

Outputs:
  StartStepFunctionLambdaArn:
    Description: ARN of the Step Functions start Lambda function
    Value: !GetAtt StartStepFunctionLambda.Arn

  StartStepFunctionLambdaName:
    Description: Name of the Step Functions start Lambda function
    Value: !Ref StartStepFunctionLambda