Search code examples
amazon-cloudwatchaws-step-functions

How can I call directly CloudWatch from a step function?


I have a step function that catches an eventual failure from a Glue function (fallback):

{
  "Comment": "A Hello World example demonstrating various state types of the Amazon States Language",
  "StartAt": "Parallel State",
  "States": {
    "Parallel State": {
      "Comment": "A Parallel state can be used to create parallel branches of execution in your state machine.",
      "Type": "Parallel",
      "Branches": [
        {
          "StartAt": "Wait",
          "States": {
            "Wait": {
              "Type": "Wait",
              "Seconds": 500,
              "Next": "Glue StartJobRun SUCCESS"
            },
            "Glue StartJobRun SUCCESS": {
              "Type": "Task",
              "Resource": "arn:aws:states:::glue:startJobRun.sync",
              "Parameters": {
                "JobName": "job_success"
              },
              "End": true,
              "Credentials": {
                "RoleArn": "arn:aws:iam::094815468753:role/glue_test"
              }
            }
          }
        },
        {
          "StartAt": "Glue StartJobRun FAIL",
          "States": {
            "Glue StartJobRun FAIL": {
              "Type": "Task",
              "Resource": "arn:aws:states:::glue:startJobRun.sync",
              "Catch": [ {
                "ErrorEquals": ["States.TaskFailed"],
                "Next": "fallback"
               } ],
              "Parameters": {
                "JobName": "job_fail"
              },
              "End": true,
              "Credentials": {
                "RoleArn": "arn:aws:iam::094815468753:role/glue_test"
              }
            },
            "fallback": {
               "Type": "Pass",
               "Result": "ERROR HERE",
               "End": true
            }
          }
        }
      ],
      "Next": "Pass"
    },
    "Pass": {
      "Type": "Pass",
      "End": true
    }
  }
}

when the fallback is called, how can I send from there a metric data to CloudWatch?


Solution

  • You can call the CloudWatch PutMetricData API from a Step Functions Task with the so-called AWS SDK service integration. The request parameters go in the task's Parameters key.

    {
      "PutMetricData": {
        "Next": "Success",
        "Type": "Task",
        "Resource": "arn:aws:states:::aws-sdk:cloudwatch:putMetricData",
        "Parameters": {
          "MetricData": [
            { "MetricName": "FooMetric", "Value": 1 },
            { "MetricName": "FooMetric", "Value.$": "$.foo" }
          ],
          "Namespace": "Dummy"
        }
      }
    }