S73417H
S73417H

Reputation: 2671

Cross-Stack Lambda and API Gateway Permissions with AWS-CDK

I have two code bases. One defines a service (Service A) that includes an AWS lambda which queries a dynamoDB table.

Another, defines an aggregating API Gateway which needs to call multiple service lambdas.

The API Gateway imports the lambda defined in service A using a cross stack reference and creates a Lambda integration for it:

    const queryTrackFunction = lambda.Function.import(this, 'TrackQueryServiceQueryTrackFunction', {
      functionArn: cdk.Fn.importValue('TrackQueryServiceStack:QueryTrackFunctionArn')
    })

    const customerApi = new api.RestApi(this, 'CustomerAPI')
    
    const tracks = customerApi.root.addResource('tracks')
    tracks.addMethod('GET', new api.LambdaIntegration(queryTrackFunction))

When the API is invoked it fails, presumably because the apigateway service has not been given invoke permissions.

In the aws-cdk project for Service A I add the following:

queryTracksFunction.grantInvoke(new ServicePrincipal('apigateway.amazonaws.com'))

When I attempt to deploy the service I get this error:

Error: Cannot use tokens in construct ID: Invoke{"Service":["${Token[TOKEN.139]}"]}

Upvotes: 4

Views: 2513

Answers (1)

jogold
jogold

Reputation: 7407

This is a bug. As a workaround, in your Service A, you can do:

queryTracksFunction.addPermission('APIGateway', {
  principal: new iam.ServicePrincipal('apigateway.amazonaws.com')
});

Upvotes: 3

Related Questions