2

I'm using the API gateway and have a service that passes on data to a Step Function.

Steps functions require JSON input in the following format:

{ 
    "input":"", 
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}

I'm currently passing stage variables in a manual way i.e.

#set($data = $util.escapeJavaScript($input.json('$')))
{ 
    "input": "{ 
        \"input\": $data, 
        \"stageVariables\" : { 
            \"clientId\": \"${stageVariables.clientId}\", 
            \"clientSecret\": \"${stageVariables.clientSecret}\", 
            \"password\": \"${stageVariables.password}\" },
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}

I know in the default mapping template you can use something like this to loop through the stage variables and generate a JSON:

"stage-variables" : {
#foreach($key in $stageVariables.keySet())
    "$key" : "$util.escapeJavaScript($stageVariables.get($key))"
    #if($foreach.hasNext),#end
#end
}

However the JSON required by a Step Function is slightly different. How can I get all stage variables into my JSON format without having to explicitly add each one manually?

Thanks

cyorkston
  • 225
  • 1
  • 10

2 Answers2

2

below is the solution that works. It seems that the template is very sensitive to line breaks, note the code below consists of 5 lines in total.

#set($data = $util.escapeJavaScript($input.json('$')))
{
    "input": "{ \"input\": $data, \"stageVariables\" : { #foreach($key in $stageVariables.keySet()) \"$key\" : \"$util.escapeJavaScript($stageVariables.get($key))\" #if($foreach.hasNext),#end #end } }",
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}
cyorkston
  • 225
  • 1
  • 10
0

I think this should work, but I didn't test it. I simply copied the foreach block you had there and escaped the quotes inline.

#set($data = $util.escapeJavaScript($input.json('$')))
{ 
    "input": "{ 
        \"input\": $data, 
        \"stageVariables\" : {
            #foreach($key in $stageVariables.keySet())
            \"$key\" : \"$util.escapeJavaScript($stageVariables.get($key))\"
            #if($foreach.hasNext),#end
            #end
        },
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}
jackko
  • 6,998
  • 26
  • 38