mcpField
S
step-functions

step-functions

github.com/itsmostafaクラウド・DevOps1.2k119 回インストール2 日前に更新
リポジトリ

step-functions について

AWS Step Functionsでワークフローを構築する開発者向けのリファレンススキルです。ステートマシンの設計、CLIとboto3による操作、エラー処理、実行時の調査方法を説明します。

主な機能

  1. 01StandardとExpressのワークフロー
  2. 02ASLによるステートマシンのパターン
  3. 03分岐、並列、Mapステート
  4. 04AWS CLIとboto3の例
  5. 05リトライとエラー処理
  6. 06実行時のトラブルシューティング

活用シーン

  1. 01AWSサービスのタスクをオーケストレーション
  2. 02条件分岐や並列処理のステップを追加
  3. 03Mapステートで配列を処理
  4. 04失敗または停止した実行を調査

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/itsmostafa/aws-agent-skills --skill step-functions

インストール後、Claude Code で/step-functionsを入力して読み込まれたか確認します。

同梱ファイルworkflow-patterns.md

詳細

AWS Step Functions

AWS Step Functions は、ステートマシンを使用してワークフローを構築、実行できるサーバーレスオーケストレーションサービスです。複数の AWS サービスを連携させ、ビジネスに不可欠なアプリケーションを構築できます。

目次

コアコンセプト

ワークフローの種類
種類説明料金
Standard長時間実行可能で耐久性があり、厳密に1回だけ実行状態遷移ごと
Express高ボリューム、短時間実行ごと(時間+メモリ)
状態の種類
状態説明
Task処理を実行します(Lambda、API 呼び出し)
Choice条件分岐
Parallel分岐を同時に実行します
Map配列を反復処理します
Wait実行を遅延させます
Pass入力を出力に渡します
Succeed正常に終了します
Fail失敗して終了します
Amazon States Language(ASL)

ステートマシンを定義するための JSON ベースの言語です。

一般的なパターン

シンプルな Lambda ワークフロー
{
  "Comment": "Process order workflow",
  "StartAt": "ValidateOrder",
  "States": {
    "ValidateOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateOrder",
      "Next": "ProcessPayment"
    },
    "ProcessPayment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessPayment",
      "Next": "FulfillOrder"
    },
    "FulfillOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:FulfillOrder",
      "End": true
    }
  }
}
ステートマシンの作成

AWS CLI:

aws stepfunctions create-state-machine \
  --name OrderWorkflow \
  --definition file://workflow.json \
  --role-arn arn:aws:iam::123456789012:role/StepFunctionsRole \
  --type STANDARD

boto3:

import boto3
import json

sfn = boto3.client('stepfunctions')

definition = {
    "Comment": "Order workflow",
    "StartAt": "ProcessOrder",
    "States": {
        "ProcessOrder": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:...",
            "End": True
        }
    }
}

response = sfn.create_state_machine(
    name='OrderWorkflow',
    definition=json.dumps(definition),
    roleArn='arn:aws:iam::123456789012:role/StepFunctionsRole',
    type='STANDARD'
)
実行の開始
import boto3
import json

sfn = boto3.client('stepfunctions')

response = sfn.start_execution(
    stateMachineArn='arn:aws:states:us-east-1:123456789012:stateMachine:OrderWorkflow',
    name='order-12345',
    input=json.dumps({
        'order_id': '12345',
        'customer_id': 'cust-789',
        'items': [{'product_id': 'prod-1', 'quantity': 2}]
    })
)

execution_arn = response['executionArn']
Choice 状態(条件ロジック)
{
  "StartAt": "CheckOrderValue",
  "States": {
    "CheckOrderValue": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.total",
          "NumericGreaterThan": 1000,
          "Next": "HighValueOrder"
        },
        {
          "Variable": "$.priority",
          "StringEquals": "rush",
          "Next": "RushOrder"
        }
      ],
      "Default": "StandardOrder"
    },
    "HighValueOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:function:ProcessHighValue",
      "End": true
    },
    "RushOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:function:ProcessRush",
      "End": true
    },
    "StandardOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:function:ProcessStandard",
      "End": true
    }
  }
}
並列実行
{
  "StartAt": "ProcessInParallel",
  "States": {
    "ProcessInParallel": {
      "Type": "Parallel",
      "Branches": [
        {
          "StartAt": "UpdateInventory",
          "States": {
            "UpdateInventory": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:...:function:UpdateInventory",
              "End": true
            }
          }
        },
        {
          "StartAt": "SendNotification",
          "States": {
            "SendNotification": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:...:function:SendNotification",
              "End": true
            }
          }
        },
        {
          "StartAt": "UpdateAnalytics",
          "States": {
            "UpdateAnalytics": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:...:function:UpdateAnalytics",
              "End": true
            }
          }
        }
      ],
      "Next": "Complete"
    },
    "Complete": {
      "Type": "Succeed"
    }
  }
}
Map 状態(反復処理)
{
  "StartAt": "ProcessItems",
  "States": {
    "ProcessItems": {
      "Type": "Map",
      "ItemsPath": "$.items",
      "MaxConcurrency": 10,
      "Iterator": {
        "StartAt": "ProcessItem",
        "States": {
          "ProcessItem": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:...:function:ProcessItem",
            "End": true
          }
        }
      },
      "ResultPath": "$.processedItems",
      "End": true
    }
  }
}
エラー処理
{
  "StartAt": "ProcessWithRetry",
  "States": {
    "ProcessWithRetry": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:function:Process",
      "Retry": [
        {
          "ErrorEquals": ["Lambda.ServiceException", "Lambda.TooManyRequestsException"],
          "IntervalSeconds": 2,
          "MaxAttempts": 6,
          "BackoffRate": 2
        },
        {
          "ErrorEquals": ["States.Timeout"],
          "IntervalSeconds": 5,
          "MaxAttempts": 3,
          "BackoffRate": 1.5
        }
      ],
      "Catch": [
        {
          "ErrorEquals": ["CustomError"],
          "ResultPath": "$.error",
          "Next": "HandleCustomError"
        },
        {
          "ErrorEquals": ["States.ALL"],
          "ResultPath": "$.error",
          "Next": "HandleAllErrors"
        }
      ],
      "End": true
    },
    "HandleCustomError": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:function:HandleCustom",
      "End": true
    },
    "HandleAllErrors": {
      "Type": "Fail",
      "Error": "ProcessingFailed",
      "Cause": "An error occurred during processing"
    }
  }
}

CLI リファレンス

ステートマシンの管理
コマンド説明
aws stepfunctions create-state-machineステートマシンを作成します
aws stepfunctions update-state-machine定義を更新します
aws stepfunctions delete-state-machineステートマシンを削除します
aws stepfunctions list-state-machinesステートマシンの一覧を表示します
aws stepfunctions describe-state-machine詳細を取得します
実行
コマンド説明
aws stepfunctions start-execution実行を開始します
aws stepfunctions stop-execution実行を停止します
aws stepfunctions describe-execution実行の詳細を取得します
aws stepfunctions list-executions実行の一覧を表示します
aws stepfunctions get-execution-history実行履歴を取得します

ベストプラクティス

設計
  • 状態の役割を絞ります — 1つの状態につき1つの目的にします
  • 意味のある状態名を使用します
  • 包括的なエラー処理を実装します
  • 独立したタスクには Parallel を使用します
  • バッチ処理には Map を使用します
パフォーマンス
  • 高ボリュームで短時間のタスクには Express ワークフローを使用します
  • 適切なタイムアウトを設定します
  • スロットリングを避けるため、Map の同時実行数を制限します
  • 可能な場合は SDK 統合を使用します(Lambda によるラッパーを避けます)
信頼性
  • 一時的なエラーを再試行します
  • 特定のエラーを捕捉して処理します
  • 冪等性のある操作を使用します
  • X-Ray トレースを有効にします
コストの最適化
  • 短時間のワークフロー(< 5 minutes)には Express を使用します
  • 遷移回数を減らすため、関連する操作をまとめます
  • Lambda による遅延処理の代わりに Wait 状態を使用します

トラブルシューティング

実行の失敗
# Get execution history
aws stepfunctions get-execution-history \
  --execution-arn arn:aws:states:us-east-1:123456789012:execution:MyWorkflow:exec-123 \
  --query 'events[?type==`TaskFailed` || type==`ExecutionFailed`]'
Lambda のタイムアウト

原因:

  • Lambda の実行時間が長すぎます
  • タスクのタイムアウトが短すぎます

修正方法:

{
  "Type": "Task",
  "Resource": "arn:aws:lambda:...",
  "TimeoutSeconds": 300,
  "HeartbeatSeconds": 60
}
状態が停止したままになる

確認項目:

  • コールバック待ちの Task 状態
  • Wait 状態の待機時間がまだ経過していない
  • アクティビティワーカーが応答していない
無効なステートマシン
# Validate definition
aws stepfunctions validate-state-machine-definition \
  --definition file://workflow.json

参考資料

コメント