aws-cdkでapigatewayに独自ドメインを設定する
自分のメモ用
前提
紐付けたいドメイン(例: example.com
)をroute53に登録し、NSレコードのdns設定が済んでいる。
独自ドメインを設定するための定義
api gatewayにapi.example.com
を設定する
import * as apigw from "aws-cdk-lib/aws-apigateway"; import * as acm from "aws-cdk-lib/aws-certificatemanager"; import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"; import * as route53 from "aws-cdk-lib/aws-route53"; import * as route53Tg from "aws-cdk-lib/aws-route53-targets"; const hostedZone = route53.HostedZone.fromHostedZoneAttributes( this, "HostedZone", { hostedZoneId: "hostedZoneId", // route53のコンソールから確認できるID zoneName: "example.com", // 紐付けたいドメイン }, ); // httpsにしたいのでacmを使用する const certificate = new acm.Certificate(this, "APIDomainCertificate", { domainName: "api.example.com", validation: acm.CertificateValidation.fromDns(hostedZone), }); const lambda = new NodejsFunction({/* 省略 */}); // apigwの用意 const httpEndpoint = new apigw.RestApi(this, "HttpEndpoint", { restApiName: "hello", endpointTypes: [apigw.EndpointType.REGIONAL], }); httpEndpoint.root.addMethod("GET", new apigw.LambdaIntegration(lambda)); // apigwとドメインを紐付ける const customDomain = httpEndpoint.addDomainName("CustomDomain", { domainName: "api.example.com", certificate, endpointType: apigw.EndpointType.REGIONAL, }); const aRecord = new route53.ARecord(this, "WebApiARecord", { recordName: "api.example.com.", zone: hostedZone, target: route53.RecordTarget.fromAlias( new route53Tg.ApiGatewayDomain(customDomain), ), });
これをcdk deploy
するとhttps://api.example.com
にアクセスするとlambdaを呼び出す事ができる
デフォルトで設定されるドメインをオフにする
カスタムドメインを設定してもApi Gatewayがデフォルトで生成するエンドポイントにはアクセスできたのでこれを無効にする。
disableExecuteApiEndpoint: true
を設定するとログにはエンドポイントが表示されるがリクエストをすると403が返ってきてアクセスができないようになっている。
const httpEndpoint = new apigw.RestApi(this, 'HttpEndpoint', { restApiName: 'hello', endpointTypes: [EndpointType.REGIONAL], disableExecuteApiEndpoint: true, // 追加 })