Send every time new UUID to AWS step function through AWS CloudWatch event rule

Viewed 2719

How to send a unique value(UUID4) to the step function is the json format, when it was triggered every time from the cloudwatch event rules? Can any one help on this. Thanks in advance.

3 Answers

Since AWS recently added Step Functions as a CloudWatch target, you could easily make the first function in the Step Function generate the UUID. And then pass that down to the next function. This would allow the Step Function to be self contained.

"GenerateUuid": {
  "Type": "Task",
  "Resource": "arn:aws:states:us-east-1:123456789012:activity:GenerateUuid",
  "Next": "CreateNewRecord"
},

Another way is to have a Lambda function generate the UUID and pass is into the State Machine which you could again trigger from a CloudWatch event.

var params = {
  stateMachineArn: 'MyStateMachine-12345',
  input: uuidv4()
};
stepfunctions.startExecution(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

A little late to the party, but in case someone else comes across this...

When you setup your cloudwatch event you can set Input Transformers on it and luckily the event that is fired has an ID that should solve your problem without adding any extra lambdas to your state machine.

Below is an example of setting it up so that the input to your state machine will like this:

{
  "meta": {
    "uniqueId": "96c80428-14fe-c8d0-f6e3-639384992391"
  }
}

Using the AWS console: Screenshot

Using code (JS):

const targets = [
  {
    Arn: "my-state-machine-arn",
    Id: "my cloud watch rule name",
    InputTransformer: {
      InputTemplate: '{"meta":{"uniqueId":<id>}}',
      InputPathsMap: {
        id: '$.id',
      },
    },
    RoleArn: "my-cloudwatch-arn",
  },
];
const params = {
  Rule: "my cloud watch rule name",
  Targets: targets,
};
cloudwatch.putTargets(params, (err, data) => {
  if (err) {
    // error
  } else {
    // success
  }
});
Related