4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CDKでAPI Gatewayにステージを追加してもLambdaのパーミッションは自動で追加されない

Posted at

CDKでAPi Gateway+Lambdaの構成を作りました。
Gatewayのステージを2つ持たせて、ステージ毎に変数を持たせてLambdaを叩くという構成にしたかったのですが、追加したステージのパーミッションがLambdaに自動で追加されなかったので、CfnPermissionを使って自分で追加する必要がありました。
このことにちょっとハマって時間を要したので、コードを残しておきます。

環境

CDK CLI: 1.27.0

コード

cdk-lambda-stack.ts
import * as cdk from '@aws-cdk/core'
import * as lambda from '@aws-cdk/aws-lambda'
import * as apigateway from '@aws-cdk/aws-apigateway'
import * as iam from '@aws-cdk/aws-iam'

export class CdkLambdaStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props)
    // Lambdaの定義
    const lambdaFn = new lambda.Function(this, 'function', {
      runtime: lambda.Runtime.PYTHON_3_8,
      handler: 'lambda_function.lambda_handler',
      code: lambda.Code.asset('lambda_asset')
    })

    // API Gatewayの定義
    const api = new apigateway.RestApi(this, 'api', {
      deployOptions: {
        stageName: 'first stage name',
        variables: {foo: 'bar'}
      }
    })

    // ステージの追加
    const stage = new apigateway.Stage(this, 'stage', {
      deployment: new apigateway.Deployment(this, 'stage', {api: api}),
      stageName: 'second stage',
      variables: {foo: 'bar_bar'}
    })
    api.root.addResource(lambdaFn.functionName).addMethod('POST', new apigateway.LambdaIntegration(lambdaFn))

    // 追加したステージからのPermissionをlambdaに追加が必要
    new lambda.CfnPermission(this, 'secondStageInvoke', {
      action: 'lambda:InvokeFunction',
      functionName: lambdaFn.functionName,
      principal: 'apigateway.amazonaws.com',
      sourceArn: 'arn:aws:execute-api:' + this.region + ':' + this.account + ':' + api.restApiId + '/' + stage.stageName + '/POST/' + lambdaFn.functionName
    })
  }
}

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?