らんだむな記憶

blogというものを体験してみようか!的なー

CDK (7)

Step Functions のスタックを作って cdklocal deploy する。VS CodeAWS Toolkit を使ってステートマシンのプレビューをしながらだと大分やりやすい・・・。cdklocal synth して CloudFormation のテンプレートを作成した後に、VS Code のコマンドパレットから AWS: Render state machine graph from CDK application を実行すれば良い。

f:id:derwind:20220308005936p:plain

デプロイ後は以下のようにして確認できる。

$ aws stepfunctions list-state-machines
{
    "stateMachines": [
        {
            "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:FibonacciStateMachine",
            "name": "FibonacciStateMachine",
            ...

現状の実装は Lambda を 1 つ呼ぶ Step Functions になっていて、その内容は

def lambda_handler(event, context):
    n_terms = 5
    if 'n_terms' in event:
        n_terms = event['n_terms']

    return {
        'fibonacci': fibonacci(n_terms),
        'statusCode': 200,
    }

とした。スタックの定義は

export class StepFunctionsTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    this.newStateMachine();
  }

  private newStateMachine(): sfn.StateMachine {
    const submitLambda = new lambda.Function(this, 'Fibonacci', {
      functionName: 'Fibonacci',
      runtime: lambda.Runtime.PYTHON_3_9,
      architecture: lambda.Architecture.X86_64,
      handler: 'index.lambda_handler',
      code: lambda.Code.fromAsset('./lambda/fibonacci'),
      timeout: Duration.seconds(30)
    });

    const submitJob = new tasks.LambdaInvoke(this, 'Submit Job', {
      lambdaFunction: submitLambda,
      outputPath: '$.Payload',
    });

    const stateMachine = new sfn.StateMachine(this, 'FibonacciStateMachine', {
      stateMachineName: 'FibonacciStateMachine',
        definition: submitJob
    });

    return stateMachine;
  }
}

としておく。いかにも無駄な実装だが、後で拡張するのでとりあえずこれで良い。

start-execution — AWS CLI 2.4.23 Command Reference を参考に CLI から呼んでみよう。

aws stepfunctions start-execution --state-machine-arn "arn:aws:states:us-east-1:000000000000:stateMachine:FibonacciStateMachine"

ARN で指定するので少し煩雑だ。状態は以下で確認できる。

$ aws stepfunctions describe-execution --execution-arn "arn:aws:states:us-east-1:000000000000:execution:FibonacciStateMachine:07070145-dd61-45cf-86e1-57086e75a74a"
{
    ...
    "status": "SUCCEEDED",
    ...
    "output": "{\"fibonacci\":[1,1,2,3,5],\"statusCode\":200}",
    ...
}

期待する結果が得られていそうだ。