Upgrade to Pro — share decks privately, control downloads, hide ads and more …

今日から使える AWS Step Functions 小技集 / AWS Step Funct...

今日から使える AWS Step Functions 小技集 / AWS Step Functions Tips

Avatar for Masanori Yamaguchi

Masanori Yamaguchi

December 08, 2025
Tweet

More Decks by Masanori Yamaguchi

Other Decks in Technology

Transcript

  1. 今日から使える AWS Step Functions 小技集 山口 正徳 / Masanori YAMAGUCHI

    JAWS-UG 茨城 #9 1周年だよ!水戸に集合だぁ! #jawsugibaraki
  2. 山口 正徳 フォージビジョン株式会社 JAWS-UG千葉支部 グローバル認定/表彰 ・AWS Community HERO ・AWS Ambassador

    ・APJ AWS Community Leaders Award 2回受賞(2022、2024) ・AWS Gold Jacket Club 日本国内認定 ・AWS Samurai ・Japan AWS Top Engineer 2019 – 2023, 2025 ・APN ALL AWS Certifications Engineers 2023 – 2024 好きなAWSサービス: Step Functions, ECS Fargate
  3. AWS re:Inforce 2025 も Step Functions 活用で登壇 • EC2インスタンスが侵害を受けた場合 のセキュリティインシデント対応に

    ついて解説しました。 • 解説した手順を自動対応する AWS Step Functions のステートマシンを 開発し公開しました。 re:Inforce 2025 COM324 YouTubeで検索すると アーカイブ動画があります。
  4. © 2025, Amazon Web Services, Inc. or its affiliates. All

    rights reserved. 「封じ込め」の手順が紹介されているドキュメント AWS Well-Architected Framework - Security Pillar https:// docs.aws.amazon.com/ja_jp/wellarchitected/latest/security-pillar/operations.html AWS Security Incident Response User Guide https://docs.aws.amazon.com/ja_jp/security-ir/latest/userguide/containment.html AWS Prescriptive Guidance https://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/automate-incident-response-and-forensics.html AWS Security Incident Response Technical Guide https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-security-incident-response-guide/infrastructure-domain-incidents.html AMS Advanced User Guide https://docs.aws.amazon.com/ja_jp/managedservices/latest/userguide/sir-contain.html
  5. © 2025, Amazon Web Services, Inc. or its affiliates. All

    rights reserved. 「収集」の手順が紹介されているドキュメント AWS Well-Architected Framework - Security Pillar https://docs.aws.amazon.com/ja_jp/wellarchitected/latest/security-pillar/operations.html AWS Security Incident Response User Guide https://docs.aws.amazon.com/ja_jp/security-ir/latest/userguide/operations.html https://docs.aws.amazon.com/ja_jp/security-ir/latest/userguide/capture-backups-and-snapshots.html https://docs.aws.amazon.com/ja_jp/security-ir/latest/userguide/appendix-b-incident-response-resources.html#forensic-resources https://docs.aws.amazon.com/ja_jp/security-ir/latest/userguide/collect-relevant-artifacts.html AWS Prescriptive Guidance https://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/automate-incident-response-and-forensics.html
  6. © 2025, Amazon Web Services, Inc. or its affiliates. All

    rights reserved. 「収集」の手順が紹介されているドキュメント (続き) AWS Security Incident Response Technical Guide https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-security-incident-response-guide/infrastructure-domain-incidents.html https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-security-incident-response-guide/capturing-volatile-data.html https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-security-incident-response-guide/using-aws-systems-manager.html https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-security-incident-response-guide/automating-the-capture.html AMS Advanced User Guide https://docs.aws.amazon.com/ja_jp/managedservices/latest/userguide/sir-contain.html
  7. 12 Step Functions では、各ステート(タスク)の出力を次のステートの入力データとして 自動的に引き継ぐことが可能ですが、データ構造が深くなるとそのままでは扱いづらくなります。 そこで便利なのが Parameters と ResultPathです。 ・

    Parameters: タスク(SDK/API)に渡すインプットで出力データを絞り込む ・ ResultPath: タスクの出力を格納する先を指定し、後続タスクで取り扱いやすくする 入力・出力の整理をする「Parameters」と「ResultPath」 "GetInstanceInfo": { "Type": "Task", "Resource": "arn:aws:states:::aws- sdk:ec2:describeInstances", "Parameters": { "InstanceIds.$": "$.instanceId" }, "ResultPath": "$.ec2" } Sdk:ec2:describeInstances に渡す InstanceIds を指定 出力を $.ec2 に格納 #jawsugibaraki
  8. 13 タスクの実行結果にもとづき、処理を分岐させる場合に Choice ステートを利用することで簡単に 条件分岐を指定することが可能です。ポイントは、比較対象を JSONPath で指定することと 明確なデフォルト遷移を設定することです。 JSON PATHをシンプルにすることで扱いやすくなるので

    ResultPathが役立ちます。 ステートで条件分岐を実現する「Choise」 "CheckStatus": { "Type": "Choice", "Choices": [ { "Variable": "$.status", "StringEquals": "SUCCESS", "Next": "NotifySuccess" } ], "Default": "NotifyFailure" } $.status の値が SUCCESS の場合は、 NotifySuccess ステートに遷移 どの条件にも一致しない場合は、 NotifyFailure ステートに遷移 #jawsugibaraki
  9. 14 Passステートを使えばLambdaを使わずにダミーデータを挿入することができます。 Choiceステートを使った条件分岐のテストを行いたいときに便利です。デバッグにもよく使います。 実際のAPI呼び出しをせずに、Choice条件($.status == "FAILED"など)の動作確認が可能です。 使った Pass ステートの定義は Notion

    などに保管しておくのがおすすめです。 ステートマシンをエンハンスする時のデバッグに再利用できるので効率を落とさずに開発できます。 「Pass」を使った固定値や分岐テスト用のダミーデータ挿入 "InjectTestData": { "Type": "Pass", "Result": { “status”: “FAILED”, "error_code": 503 }, "Next": "CheckStatus" } status の値に FAILED を挿入 #jawsugibaraki
  10. 16 エラー処理では単純なRetryやCatchだけではなく、エラーごとに異なる再試行ポリシーや分岐処理を 定義できます。特に、States.Timeout / Lambda.ServiceException / States.TaskFailed を 分けて扱うのが本番環境では重要です。 エラー分類にもとづいたフォールバック制御

    ”CallLambda": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Retry": [ { "ErrorEquals": ["States.Timeout"], "IntervalSeconds": 3, "MaxAttempts": 2, "BackoffRate": 1.5 } ], "Catch": [ { "ErrorEquals": ["Lambda.ServiceException", "States.TaskFailed"], "Next": "FallbackPath" } ], "End": true } エラーが Timeout だった場合は、一時的な エラーの可能性を考えて再実行を指定 Exponential Backoff も係数で制御できる Lambdaの例外エラー、タスク実行失敗の 場合はフォールバック処理へ遷移 #jawsugibaraki
  11. 17 ステートの実行結果が Raw データで返却される場合、ステートマシンの Output データでは取り扱いが極端に 難しくなります。(JSONPath で参照先を指定できないため) こんな時、Lambdaでjson.loads()を使ってパースしたくなりますが、States.StringToJson()を使えばJSON オブジェクトへ変換することができます。

    昔、AWS Top Engineers の競技大会でも States.StringToJson() の知識を問う課題がありました。 組み込み関数を覚えておくと AWS Jam などでも役立つかも。 RawデータからJSONへのデータ変換 "ParseText": { "Type": "Pass", "Parameters": { "Parsed.$": "States.StringToJson($.rawText)" }, "ResultPath": "$.data", "Next": "NextState" } $.rawText を JSONオブジェクトに変換 #jawsugibaraki
  12. 18 rawText RawデータからJSONへのデータ変換(つづき) "rawText": "{\"user\":\”kobayashi\",\"age\":36}" States.StringToJson()で変換後 "Parsed": { "user": ”kobayashi",

    "age": 36 } { "rawText": "{\"user\":\”kobayashi\",\"age\":36}", "data": { "Parsed": { "user": ”kobayashi", "age": 36 } } } 最終的な状態($.dataへの出力) #jawsugibaraki
  13. 20 ResultSelector でAPIレスポンスを整形して Output に渡す AWS SDK(API) は、Step Functions での利用を前提としているものではないため、レスポンスが深く

    Choice や Map における取り扱いが複雑になります。 ResultSelector を使うと、レスポンスを“必要最小限の構造”に整理して Output に渡せるため、 後続ステートでの取り扱いをシンプルにすることができます。 "DescribeInstance": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:ec2:describeInstances", "Parameters": { "InstanceIds.$": "$.instanceId" }, "ResultSelector": { "InstanceId.$": "$.Reservations[0].Instances[0].InstanceId", "State.$": "$.Reservations[0].Instances[0].State.Name", "Type.$": "$.Reservations[0].Instances[0].InstanceType", "Tags.$": "$.Reservations[0].Instances[0].Tags" }, "ResultPath": "$.instance", "Next": "NextTask" } ec2:describeInstances のレスポンスから 必要な値を抽出し、最小の JSONPath に 値を代入して整理 インスタンスIDは、$.instance.InstanceId で 取り出せるため、後続ステートのParameter 記述をシンプルできる #jawsugibaraki
  14. 21 Payload Templateで「Lambda相当の文字列生成」をASL内だけで完結 ASLで拡張された PayloadTemplate を使うことで、行数の多いメッセージやSlack通知用のテンプレート メッセージ作成を Lambda を使わずにステートマシン内で生成することができます。 JSONata

    でも実現できますが、PayloadTemplate は JSONPath で明示指定されたフィールドのみにて 利用可能なため、可読性が高く保守しやすいというメリットがあります。 "MakeMessage_PayloadTemplate": { "Type": "Pass", "Parameters": { "PayloadTemplate": { "Message": "States.Format('{} scored {} points!', $.name, $.score)" } }, "ResultPath": "$.result", "Next": "NextState" } “PayloadTemplate” は 明示指定した フィールドの中で使われ、JSONPath ($.name)および($.score)を参照できる #jawsugibaraki
  15. 22 Payload Templateで「Lambda相当の文字列生成」をASL内だけで完結 (JSONataの場合) "MakeMessage_JSONata": { "Type": "Pass", "Parameters": {

    "Message": "${$.name & ' scored ' & $.score & ' points!'}" }, "ResultPath": "$.result", "Next": "NextState" } ${ ... } の中は JSONata式 として評価される すべての文字列リテラル(キーや値)は、自動的に JSONataとして解釈されるため PayloadTemplate のように明示的な宣言は不要 { "result": { "Message": "Alice scored 95 points!" } } いずれも ResultPath で出力される Output は下記になる #jawsugibaraki
  16. 24 AWS re:Invent 2025 会場でセキュリティ拡張パック日本語版配布予定 AWS BuilderCards セキュリティ拡張パック、 Builder‘s Galore拡張パック、それぞれ日本語版

    の配布を予定しています。 場所: Caesar’s Forum(1階) 11月30日(日曜日) 午前10時 – 午後6時 12月1日(月曜日) 午前9時 – 午後5時 12月2日(火曜日) 午前9時 – 午後5時 12月3日(水曜日) 午前9時 – 午後5時 12月4日(木曜日) 午前9時 – 午後4時 日本人のスタッフもいるようですので英語ができなくて も大丈夫です。 日曜日の午後は私もCaesar’s Forumを歩いてい ると思いますので、現地参加する方は声をかけてくれ ると嬉しいです。