terraform.aws-baseline-infra/modules/networking/vpc-endpoints/main.tf

95 lines
2.4 KiB
Terraform
Raw Normal View History

2023-07-06 12:02:34 +08:00
data "aws_region" "this" {}
data aws_default_tags this {}
2023-07-06 12:02:34 +08:00
2022-09-22 00:43:34 +08:00
resource "aws_vpc_endpoint" "vpc-interface-ep" {
2023-07-06 12:02:34 +08:00
for_each = toset(var.interface-ep-services)
2022-09-22 00:43:34 +08:00
vpc_id = data.aws_vpc.this-vpc.id
2023-07-06 12:02:34 +08:00
service_name = "com.amazonaws.${data.aws_region.this.name}.${each.value}"
2022-09-22 00:43:34 +08:00
vpc_endpoint_type = "Interface"
security_group_ids = [
2023-07-06 12:02:34 +08:00
aws_security_group.vpc-ep-sg.id,
2022-09-22 00:43:34 +08:00
]
# deploy to all subnets
2023-07-06 12:02:34 +08:00
subnet_ids = local.one_subnet_in_each_az
2022-09-22 00:43:34 +08:00
private_dns_enabled = true
tags = { "Name" : "${var.resource-prefix}-vpcep-${each.value}" }
2023-07-06 12:02:34 +08:00
lifecycle {
precondition {
condition = data.aws_vpc.this-vpc.enable_dns_support
error_message = "enableDnsSupport needs to be turned on."
}
}
}
resource "aws_vpc_endpoint" "vpc-gateway-ep" {
for_each = toset(var.gateway-ep-services)
vpc_id = data.aws_vpc.this-vpc.id
service_name = "com.amazonaws.${data.aws_region.this.name}.${each.value}"
vpc_endpoint_type = "Gateway"
route_table_ids = data.aws_route_tables.this.ids
tags = { "Name" : "${var.resource-prefix}-vpcep-${each.value}" }
2022-09-22 00:43:34 +08:00
}
resource "random_id" "rid" {
2023-07-06 12:02:34 +08:00
byte_length = 2
}
resource "aws_security_group" "vpc-ep-sg" {
name = "HttpsAccessToVpcEndpoints-${random_id.rid.dec}"
description = "HttpsAccessToVpcEndpoints-${random_id.rid.dec}"
2022-09-22 00:43:34 +08:00
vpc_id = data.aws_vpc.this-vpc.id
ingress {
description = "TLS from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [data.aws_vpc.this-vpc.cidr_block]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = compact(concat(["0.0.0.0/0"], var.secondary_cidrs))
2022-09-22 00:43:34 +08:00
}
tags = { "Name" : "VpcEpAccess" }
2022-09-22 00:43:34 +08:00
}
2023-07-06 12:02:34 +08:00
data "aws_vpc" "this-vpc" {
2022-09-22 00:43:34 +08:00
id = var.vpc-id
}
data "aws_availability_zones" "this" {
state = "available"
}
# find all subnets for this vpc in all availability zones
data "aws_subnets" "subnets_and_az" {
for_each = toset(data.aws_availability_zones.this.zone_ids)
2022-09-22 00:43:34 +08:00
filter {
2023-07-06 12:02:34 +08:00
name = "vpc-id"
2022-09-22 00:43:34 +08:00
values = [var.vpc-id]
}
filter {
name = "availability-zone-id"
values = [each.value]
}
2023-07-06 12:02:34 +08:00
}
data "aws_route_tables" "this" {
vpc_id = var.vpc-id
2023-07-06 12:02:34 +08:00
}
locals {
# pick first subnet in each AZ
one_subnet_in_each_az = compact([for k, v in data.aws_subnets.subnets_and_az : try(element(v.ids, length(v.ids) - 1), "")])
2023-07-06 12:02:34 +08:00
}