men6288
men6288

Reputation: 69

AWS State Machine ASL: Use the Result Selector only if data is returned

I am trying to configure a task state to find an organization, if the organization is found the Result Selector will select the name, id, and createTime. This will then be added back to the ticket under the org node (ResultPath).

The issue I am encountering is that if the organization isn't found then the state machine execution will be cancelled because the Result Selector is attempting to select nodes that do not exist in the result. Does anyone know if there is a way to use the Result Selector only if data is returned? I want the state machine to continue even if the org isn't found.

"Find Organization": {
    "Type": "Task",
    "Resource": "${aws_lambda_function.test_function.arn}",
    "Next": "Find User Account",
    "Parameters": {
        "name": "FindOrganization",
        "request.$": "$.item"
    },
    "ResultSelector": {
        "name.$": "$.name",
        "id.$": "$.id",
        "createTime.$": "$.createTime"
    },
    "ResultPath": "$.org",
    "Catch": [
        {
            "ErrorEquals": [
                "States.ALL"
            ],
            "ResultPath": "$.error",
            "Next": "Publish SNS Failure"
        }
    ]
}

Upvotes: 3

Views: 2193

Answers (1)

Allen
Allen

Reputation: 4789

This is exactly when Choice State comes into play.

An example modification to your original ASL definition would be

{
  "Comment": "An example of the Amazon States Language using a choice state.",
  "StartAt": "Find Organization",
  "States": {
    "Find Organization": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Next": "Check If Organization Exists",
      "Parameters": {
        "name": "FindOrganization",
        "request.$": "$.item"
      },
      "Catch": [
        {
          "ErrorEquals": [
            "States.ALL"
          ],
          "ResultPath": "$.error",
          "Next": "Publish SNS Failure"
        }
      ]
    },
    "Check If Organization Exists": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$",
          "IsNull": false,
          "Next": "Organization Exists"
        },
        {
          "Variable": "$",
          "IsNull": true,
          "Next": "Organization Not Exists"
        }
      ],
      "Default": "Organization Exists"
    },
    "Organization Exists": {
      "Type": "Pass",
      "Parameters": {
        "name.$": "$.name",
        "id.$": "$.id",
        "createTime.$": "$.createTime"
      },
      "ResultPath": "$.org",
      "Next": "Find User Account"
    },
    "Organization Not Exists": {
      "Type": "Fail"
    },
    "Find User Account": {
      "Type": "Succeed"
    },
    "Publish SNS Failure": {
      "Type": "Fail"
    }
  }
}

enter image description here

Upvotes: 2

Related Questions