LoginSignup
0
1

More than 3 years have passed since last update.

AWS CDKを使って、既存のドメインとAWS Lambdaに対してAPI Gatewayを作ってLambdaを実行する許可を出したりするサンプル。

Last updated at Posted at 2019-12-11

AWS CDKを使って、既存のドメインとAWS Lambdaに対してAPI Gatewayを作ってLambdaを実行する許可を出したりするサンプル。

example.ts
import cdk = require("@aws-cdk/core");
import apigateway = require("@aws-cdk/aws-apigateway");
import lambda = require("@aws-cdk/aws-lambda");

interface MultistackProps extends cdk.StackProps {
  stage: "staging" | "production";
  functionArn: string;
  domainName: string;
  domainNameAliasHostedZoneId: string;
  domainNameAliasTarget: string;
}

export class MuaFrontendApiGatewayStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: MultistackProps) {
    super(scope, id, props);

    const domain = apigateway.DomainName.fromDomainNameAttributes(
      this,
      `existing-domain-${props.stage}`,
      {
        domainName: props.domainName,
        domainNameAliasHostedZoneId: props.domainNameAliasHostedZoneId,
        domainNameAliasTarget: props.domainNameAliasTarget
      }
    );

    const api = new apigateway.RestApi(this, `api-gateway-${props.stage}`, {
      restApiName: `api-gateway-${props.stage}`
    });

    new apigateway.BasePathMapping(this, `basePathMapping-${props.stage}`, {
      domainName: domain,
      restApi: api
    });

    const lambdaOne = lambda.Function.fromFunctionArn(
      this,
      `lambdaOne-${props.stage}`,
      props.functionArn
    );
    const lambdaIntegration = new apigateway.LambdaIntegration(lambdaOne, {
      contentHandling: apigateway.ContentHandling.CONVERT_TO_BINARY
    });
    const rootProxy = api.root.addProxy({
      anyMethod: false
    });

    const methodOne = rootProxy.addMethod("ANY", lambdaIntegration);

    new lambda.CfnPermission(this, `permission-for-lambda-${props.stage}`, {
      action: "lambda:invokeFunction",
      principal: "apigateway.amazonaws.com",
      functionName: lambdaOne.functionArn,
      sourceArn: methodOne.methodArn.toString()
    });
  }
}
0
1
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
0
1