cdkv2を使ってStep Functionsをデプロイしてみたメモ

## 概要

StepFunctionsを作成したサンプル

[ソースコード](https://github.com/hibohiboo/aws-cdk-v2/blob/58b6664a2c4526e3be3f69b75310c0c3e97ba7ab/cdk/lib/step-functions-stack.ts)

## コード

```ts

export class StepFunctionSampleStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: StepFunctionSampleStackProps) {
    super(scope, id, props);

    const lambdaParamsDefault = {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: 'index.handler',
      timeout: cdk.Duration.seconds(10),
    }

    // Lambda samples
    const firstFunction = new lambda.Function(this, 'FirstFunction', {
      ...lambdaParamsDefault,
      code: lambda.Code.fromInline(`
        exports.handler = (event, context, callback) => {
          console.log(event);
          callback(null, {"Payload": {"Message": "hello", firstEvent: event}});
        };
      `),
    });
    const secondFunction = new lambda.Function(this, 'SecondFunction', {
      ...lambdaParamsDefault,
      code: lambda.Code.fromInline(`
      exports.handler = (event, context, callback) => {
        console.log(event);
        callback(null, {});
      };
      `),
    });

    // definite state machine
    const upstreamJob = new tasks.LambdaInvoke(this, 'UpstreamTask', {
      lambdaFunction: firstFunction,
      outputPath: '$.Payload',
    });
    const mainJob = new tasks.LambdaInvoke(this, 'MainFunctionTask', {
      lambdaFunction: secondFunction,
      payload: stepfunc.TaskInput.fromJsonPathAt('$.Payload'),
    });


    // StateMachine
    const definition = upstreamJob.next(mainJob).next(new stepfunc.Succeed(this, 'Queued'));
    const stateMachine = new stepfunc.StateMachine(this, 'StepFunctionSampleStateMachine', {
      definition,
    });

    // EventBridge Rule1（毎時40〜50分に起動）
    new aws_events.Rule(this, 'rule1', {
      ruleName: 'sampleRule1',
      schedule: aws_events.Schedule.cron({
        minute: '40-50',
      }),
      targets: [new aws_events_targets.SfnStateMachine(stateMachine)],
    });
  }
}
```

## 実行結果

1つめのlambdaログ

```js
{
  version: '0',
  id: 'a505cf29-8005-0bc2-361b-bdffb2af96b9',
  'detail-type': 'Scheduled Event',
  source: 'aws.events',
  account: 'xxxxxxx',
  time: '2023-02-07T23:46:00Z',
  region: 'ap-northeast-1',
  resources: [ 'arn:aws:events:ap-northeast-1:xxxxxxx:rule/sampleRule1' ],
  detail: {}
}
```

2つめのlambdaログ

```js
{
  Message: 'hello',
  firstEvent: {
    version: '0',
    id: 'a505cf29-8005-0bc2-361b-bdffb2af96b9',
    'detail-type': 'Scheduled Event',
    source: 'aws.events',
    account: 'xxxxxxx',
    time: '2023-02-07T23:46:00Z',
    region: 'ap-northeast-1',
    resources: [ 'arn:aws:events:ap-northeast-1:xxxxxxx:rule/sampleRule1' ],
    detail: {}
}
```

1つめのFunctionのPayloadを渡せていることが確認できた。

## 2024.02.01 追記　deprecatedになったdefinitionからdefinitionBodyに変更したメモ

```diff
    // StateMachine
    const definition = upstreamJob.next(mainJob).next(new stepfunc.Succeed(this, 'Queued'));
    const stateMachine = new stepfunc.StateMachine(this, 'StepFunctionSampleStateMachine', {
-      definition,
+      definitionBody: DefinitionBody.fromChainable(definition),
    });

```


[ソースコード](https://github.com/hibohiboo/aws-cdk-v2/blob/9df19a2f5406980b112649375399f6289bd33288/cdk/lib/step-functions-stack.ts)

## 参考

[Class Method - AWS Step Functionsで起動ソースのEventBridge Ruleに応じて処理を分岐させる（AWS CDK v2）](https://dev.classmethod.jp/articles/using-aws-step-functions-to-branch-processing-according-to-the-eventbridge-rule-of-the-launch-source-aws-cdk-v2/)
[ENGENEERING - StepFunctions を CDK + Typescript で構築するサンプル集](https://tech.raksul.com/2021/12/21/stepfunctions-%E3%82%92-cdk-typescript-%E3%81%A7%E6%A7%8B%E7%AF%89%E3%81%99%E3%82%8B%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E9%9B%86/)

[AWS CDK v2.85.0 で AWS Step Functions ステートマシンを ASL JSON から作成可能になりました](https://dev.classmethod.jp/articles/aws-step-functions-state-machines-can-now-be-created-from-asl-json-in-aws-cdk-v2850/)

## 余談

NotionAIに起動プログラム依頼してみた。
なかなかやるじゃん。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/99876/92227dae-4b3a-4bf5-79dc-142fc70be915.png)