業界・業務から探す
導入目的・課題から探す
データ・AIについて学ぶ
News
Hakkyについて
ウェビナーコラム
◆トップ【Hakkyの社内Wiki】Strapi
クラウドとオンプレの違いAIシステム導入時におすすめのクラウドシステムスクレイピングのためのプロキシサーバのAPI
AI

執筆者:Handbook編集部

VPC Endpoint の Terraform での書き方

はじめに

この記事は、AWS の VPC Endpoint の Terraform での書き方をまとめた記事です。AWS の VPC Endpoint の基本的なことをさらいつつ、VPC Endpoint の Terraform での書き方について紹介します。

VPC Enpoint とは

AWS において、VPC と他サービス間でプライベートな接続を提供するコンポーネントです。インターネットを介さずに他サービスと接続できるため、コストの削減に役立ちます。 "AWS VPC Endpoint とは"に詳しく書いてあります。

Terraform での書き方

前提

ECS / Fargate で、コンテナーで動く Web アプリケーションのインフラを構築するとします。この時、以下の条件を満たすために、VPC Endpoint を設定するものとします。

  • NAT gateway を使わずに ECR から Docker イメージを pull
  • コンテナーから S3 に VPC Endpoint 経由でデータのやり取り

設定内容

具体的な設定内容は以下の通りです。

  • S3 は、Gateway 型なので、ルートテーブルとの紐付けが必要となります。
  • それ以外は、Interface 型なので、それぞれのエンドポイント用のセキュリティグループが必要となります。

以下のエンドポイントの設定をします。

  • s3
  • ecr.dkr
  • ecr.api

Terraform コード

AWS の VPC Endpoint を Terraform で設定するときは、いつも下記のようなコードを書きます。

#########################
# vpc endpoint          #
#########################
resource "aws_vpc_endpoint" "s3" {
  vpc_id            = aws_vpc.id
  service_name      = "com.amazonaws.ap-northeast-1.s3"
  vpc_endpoint_type = "Gateway"

  tags = {
    "Name" = "${var.env}-s3"
  }
}

resource "aws_vpc_endpoint_route_table_association" "private_s3" {
  count           = length(aws_subnet.private-net)
  vpc_endpoint_id = aws_vpc_endpoint.s3.id
  route_table_id  = aws_route_table.nat-route[count.index].id
}

resource "aws_vpc_endpoint" "ecr_dkr" {
  vpc_id              = aws_vpc.id
  service_name        = "com.amazonaws.ap-northeast-1.ecr.dkr"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = aws_subnet.private-net[*].id
  security_group_ids  = [aws_security_group.vpc_endpoint.id]
  private_dns_enabled = true

  tags = {
    "Name" = "${var.env}-ecr-dkr"
  }
}

resource "aws_vpc_endpoint" "ecr_api" {
  vpc_id              = aws_vpc.id
  service_name        = "com.amazonaws.ap-northeast-1.ecr.api"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = aws_subnet.private-net[*].id
  security_group_ids  = [aws_security_group.vpc_endpoint.id]
  private_dns_enabled = true

  tags = {
    "Name" = "${var.env}-ecr-api"
  }
}

#########################
# security group        #
#########################
resource "aws_security_group" "vpc_endpoint" {
  name   = "vpc_endpoint_sg"
  vpc_id = aws_vpc.id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.cidr_block]
  }

  egress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [aws_vpc.cidr_block]
  }
}

参考

info
備考

Hakky ではエンジニアを募集中です!まずは話してみたいなどでも構いませんので、ぜひお気軽に採用ページからお問い合わせくださいませ。

2025年06月15日に最終更新
読み込み中...