How Do I get amplify environment variables into custom resolvers mapping template.
Is your feature request related to a problem? Please describe. I'm always frustrated when I need to hardcode tablenames in mapping templates, this happens often with batch operations that require the tablename, for example:
#set($ids = [])
#foreach($id in ${ctx.args.ids})
#set($map = {})
$util.qr($map.put("id", $util.dynamodb.toString($id)))
$util.qr($ids.add($map))
#end
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"MyTablename-GraphQLIDRandomThing-Env": {
"keys": $util.toJson($ids),
"consistentRead": true
}
}
}
Describe the solution you'd like
If I could have access to env name and GraphqlID I'd be able to construct the table name instead of hardcoding it.
Thanks!!
A less desirable alternative would be a $util function that returns the tablename of the associated datasource. It is less desirable because it only solves the problem for single table batch operations -- but it may be easier to implement. On the other hand, this solution would be independent of Amplify (i.e., it would solve the problem for Appsync users not using Amplify as long as they are doing single-table applications).
OK, here's the solution for getting an environment variable into an Appsync resolver (facepalm) in an Amplify project.
Create a function in a custom cloudformation stack that sticks the desired environment variable(s) in $ctx.stash. Then you can refer to it whenever you want. Here's my function resource declaration:
"getEnvironmentFunction": { "Type": "AWS::AppSync::FunctionConfiguration", "Properties": { "ApiId": { "Ref": "AppSyncApiId" }, "DataSourceName": { "Fn::GetAtt": [ "NoneDS", "Name" ] }, "Description": "Sets $ctx.stash.environment equal to the Amplify development environment pushed", "FunctionVersion": "2018-05-29", "Name": "getEnvironment", "RequestMappingTemplate": "{\n \"version\": \"2017-02-28\",\n \"payload\": {}\n }", "ResponseMappingTemplate": { "Fn::Join": [ "", [ "$util.qr($context.stash.put(\"environment\", \"", { "Ref" : "env" }, "\"))\n$util.toJson($ctx.prev.result)" ] ] } } }
Note that you need a "none" datasource (here it is called 'NoneDS').
@ericweissmann does your solution work for custom resolvers? Meaning it will run before every resolver?
@ericweissmann does your solution work for custom resolvers? Meaning it will run before every resolver?
As I understand it, you will have to create a Pipeline resolver that calls the above function, then your resolver. So you will need to define this function in custom resources (and include the AppSyncApiId variable if you're doing a batch operation), then your custom resolver function, then a pipeline resolver that calls them both.
Add the variables to the stash
"addEnvVariablesToStash": {
"Type": "AWS::AppSync::FunctionConfiguration",
"Properties": {
"ApiId": {
"Ref": "AppSyncApiId"
},
"DataSourceName": "NONE",
"Description": "Sets $ctx.stash.env to the Amplify environment and $ctx.stash.apiId to the Amplify API ID",
"FunctionVersion": "2018-05-29",
"Name": "addEnvVariablesToStash",
"RequestMappingTemplate": "{\n \"version\": \"2017-02-28\",\n \"payload\": {}\n }",
"ResponseMappingTemplate": {
"Fn::Join": [
"",
[
"$util.qr($context.stash.put(\"env\", \"",
{ "Ref" : "env" },
"\"))\n$util.qr($context.stash.put(\"apiId\", \"",
{ "Ref": "AppSyncApiId" },
"\"))\n$util.toJson($ctx.prev.result)"
]
]
}
}
},
Your custom resolver function
"FunctionMutationDoThing": {
"Type": "AWS::AppSync::FunctionConfiguration",
"Properties": {
"ApiId": {
"Ref": "AppSyncApiId"
},
"DataSourceName": "MyTableName",
"FunctionVersion": "2018-05-29",
"Name": "FunctionMutationDoThing",
"RequestMappingTemplateS3Location": {
"Fn::Sub": [
"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Function.Mutation.doThing.req.vtl",
{
"S3DeploymentBucket": {
"Ref": "S3DeploymentBucket"
},
"S3DeploymentRootKey": {
"Ref": "S3DeploymentRootKey"
}
}
]
},
"ResponseMappingTemplateS3Location": {
"Fn::Sub": [
"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Function.Mutation.doThing.res.vtl",
{
"S3DeploymentBucket": {
"Ref": "S3DeploymentBucket"
},
"S3DeploymentRootKey": {
"Ref": "S3DeploymentRootKey"
}
}
]
}
}
},
Your pipeline resolver that calls the first and second functions above
"PipelineMutationDoThingResolver": {
"Type": "AWS::AppSync::Resolver",
"Properties": {
"ApiId": {
"Ref": "AppSyncApiId"
},
"Kind": "PIPELINE",
"PipelineConfig": {
"Functions": [
{
"Fn::GetAtt": ["addEnvVariablesToStash", "FunctionId"]
},
{
"Fn::GetAtt": ["FunctionMutationDoThing", "FunctionId"]
}
],
"TypeName": "Mutation",
"FieldName": "doThing",
"RequestMappingTemplate": "{}",
"ResponseMappingTemplate": "$util.toJson($ctx.result)"
},
"DependsOn": ["addEnvVariablesToStash", "FunctionMutationDoThing"]
}
}
Then you can reference the variables in your Function.Mutation.doThing.req.vtl function with:
$ctx.stash.env
$ctx.stash.apiId
Hope that makes sense. Just thought it was worth putting up the full solution. Seeing as @ericweissmann 's solution has been heavily referenced (and stopped me from tearing my hair out!).
@jonperryxlm thanks for the explanation. Was really helpful. I'm kinda new to amplify and the customer resolver file is looking foreign to me. is this the right way to access the resolver $ctx.stash in the resolver file?
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"MyTablename-$ctx.stash.env-$ctx.stash.apiId": {
"keys": $util.toJson($ids),
"consistentRead": true
}
}
}
@jonperryxlm thanks for the explanation. Was really helpful. I'm kinda new to amplify and the customer resolver file is looking foreign to me. is this the right way to access the resolver $ctx.stash in the resolver file? ...
@Somtozech I've updated your example to use the correct syntax...
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"MyTablename-${ctx.stash.env}-${ctx.stash.apiId}": {
"keys": $util.toJson($ids),
"consistentRead": true
}
}
}
Though I'm guessing it should actually be:
"MyTablename-${ctx.stash.apiId}-${ctx.stash.env}" as that's the naming convention for @model generated DynamoDB table names.
The resolvers are Velocity Templates, which if you're mainly focused on something like JavaScript (as I am), it does look weird. You can find the docs here - They aren't great. The AWS Resolver Mapping Template docs are decent.
I went through a fair amount of pain with the learning curve, mainly just down the code being so damn unreadable. My advice would be to play around with the code in the AppSync UI to test out your changes before putting it into source control, building it etc. (assuming you've got a sandbox type environment or similar). I know the AppSync UI is painfully slow, but it's way quicker than building and pushing just to realise you've made a stupid syntax error. Seems a no-duh type suggestion, but I didn't think to do it for ages!
Good luck, and hope that helps!
@jonperryxlm did you experience this or know how I might solve it?

Oh. I was able to resolve this by creating a data source named NONE pointing to None as the source type from the appsync console
Oh. I was able to resolve this by creating a data source named NONE pointing to None as the source type from the appsync console
@Somtozech you can create that none data source in the CustomResources.json file. You will probably overwrite that none data source when you push your next set of changes.
here's an example of my none data source under the Resources object:
"NoneDataSource": {
"Type": "AWS::AppSync::DataSource",
"Properties": {
"ApiId": {
"Ref": "AppSyncApiId"
},
"Name": "NoneDataSource",
"Type": "NONE"
}
},
Closing this in favor of aws-amplify/amplify-category-api#408 to increase visibility.
How you call this? the Pipeline resolver within the schema??? Some how I am having issue,
Invalid template property or properties
This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.
Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels for those types of questions.