ゆずめも

メモ的なブログです。主に勉強した事について書いてます。

aws-cdkでapigatewayに独自ドメインを設定する

自分のメモ用

前提

紐付けたいドメイン(例: example.com)をroute53に登録し、NSレコードのdns設定が済んでいる。

独自ドメインを設定するための定義

api gatewayapi.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, // 追加
})