Search code examples
aws-cdkaws-step-functions

How do I access a specific index value in AWS CDK step functions using the "Iterating a Loop Using Lambda" example


Use Case: The Iterating a Loop Using Lambda example offers a solution that allows one to loop through an array using Choice state. I would like to use the index of the iterator as a means of accessing a specific element in an array.

Iterating a Loop Using Lambda

AWS CDK Code:

this.iterator = new LambdaInvoke(this, "iterator", {
  lambdaFunction: stepFunctionTasksLambdaStack.iterator,
  payloadResponseOnly: true,
  comment: "Manage iterating over the array of configurable product skus",
  retryOnServiceExceptions: true,
  timeout: Duration.minutes(3),
});

this.countReached = new Choice(this, "Count Reached?");

this.encodeSku = new LambdaInvoke(this, "Encode Simple Product SKU", {
  lambdaFunction: stepFunctionTasksLambdaStack.encodeURIComponent,
  payloadResponseOnly: true,
  comment: "Encode the SKU to make it suitable for querying the Magento API with",
  retryOnServiceExceptions: true,
  timeout: Duration.minutes(3),
});

Where could I concatenate the index value the iterator is on for this.encodeSku, plus the array of skus? It'd have to be something like input: "$.arrayOfSkus"["$.iterator.index"].


Solution

  • In the CDK, the solution is to create a payload where we use TaskInput.fromObject to access the information.

    this.pickSku = new LambdaInvoke(this, "Choose The SKU", {
      lambdaFunction: stepFunctionTasksLambdaStack.arrayElementSelector,
      inputPath: "$.augmentArrayAndIndex",
      payloadResponseOnly: true,
      comment: "Manage iterating over the array of configurable product skus",
      retryOnServiceExceptions: true,
      timeout: Duration.minutes(3),
      payload: TaskInput.fromObject({
        "array": JsonPath.stringAt("$.[LOCATION_OF_INFORMATION]"),
        "index": JsonPath.numberAt("$.[LOCATION_OF_INFORMATION]")
      })
    });