Amazon AWS Transit Gateway·续4

cloudflare = { source = "cloudflare/cloudflare" version = "~> 5.27.0" } } }

Authentication comes from CLOUDFLARE_API_TOKEN rather than a Terraform variable,

which keeps the API token out of configuration and variable files.

provider "cloudflare" {}

provider "aws" { region = var.aws_region # Refuse to operate if the active credentials point at the wrong AWS account. allowed_account_ids = [var.expected_account_id]

default_tags { tags = { Deployment = var.deployment_name ManagedBy = "Terraform" } } }


#### `variables.tf`

Create `variables.tf` to declare deployment inputs and reject invalid account IDs, CIDRs, anycast IPs, ASNs, and pre-shared keys.

```hcl
variable "aws_region" {
  description = "AWS Region for the reference deployment."
  type        = string
  default     = "us-east-2"
}

variable "expected_account_id" {
  description = "Twelve-digit AWS account ID allowed to receive the deployment."
  type        = string

validation {
    condition     = can(regex("^[0-9]{12}$", var.expected_account_id))
    error_message = "expected_account_id must be a 12-digit AWS account ID."
  }
}

variable "cloudflare_account_id" {
  description = "Cloudflare account ID that owns the Cloudflare WAN configuration."
  type        = string

validation {
    condition     = can(regex("^[0-9a-fA-F]{32}$", var.cloudflare_account_id))
    error_message = "cloudflare_account_id must be a 32-character hexadecimal Cloudflare account ID."
  }
}

variable "deployment_name" {
  description = "Name used to tag the reference deployment."
  type        = string
  default     = "cloudflare-wan-reference"

validation {
    condition     = can(regex("^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$", var.deployment_name))
    error_message = "deployment_name may contain only letters, numbers, periods, underscores, and hyphens."
  }
}

variable "vpc_cidr" {
  description = "IPv4 CIDR for the workload VPC."
  type        = string
  default     = "192.168.0.0/16"

validation {
    # Require the canonical network address so containment checks are unambiguous.
    condition = try(
      can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.vpc_cidr)) &&
      cidrhost(var.vpc_cidr, 0) == split("/", var.vpc_cidr)[0] &&
      tonumber(split("/", var.vpc_cidr)[1]) >= 16 &&
      tonumber(split("/", var.vpc_cidr)[1]) <= 28,
      false
    )
    error_message = "vpc_cidr must be an IPv4 network with an AWS-supported /16 through /28 prefix."
  }
}

variable "workload_subnet_cidr" {
  description = "Public subnet for workloads that use split Internet and Cloudflare WAN connectivity."
  type        = string
  default     = "192.168.125.0/24"

validation {
    condition = try(
      can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.workload_subnet_cidr)) &&
      cidrhost(var.workload_subnet_cidr, 0) == split("/", var.workload_subnet_cidr)[0] &&
      tonumber(split("/", var.workload_subnet_cidr)[1]) >= 16 &&
      tonumber(split("/", var.workload_subnet_cidr)[1]) <= 28,
      false
    )
    error_message = "workload_subnet_cidr must be an IPv4 network with an AWS-supported /16 through /28 prefix."
  }
}

variable "vpn_routed_prefixes" {
  description = "IPv4 destination prefixes routed through the Transit Gateway and Site-to-Site VPNs instead of the Internet Gateway."
  type        = list(string)
  default     = []

validation {
    # The default route belongs to the Internet Gateway; only more-specific
    # canonical networks can be selected for the VPN path.
    condition = length(distinct(var.vpn_routed_prefixes)) == length(var.vpn_routed_prefixes) && alltrue([
      for cidr in var.vpn_routed_prefixes : try(
        can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", cidr)) &&
        cidrhost(cidr, 0) == split("/", cidr)[0] &&
        tonumber(split("/", cidr)[1]) >= 1 &&
        tonumber(split("/", cidr)[1]) <= 32,
        false
      )
    ])
    error_message = "vpn_routed_prefixes must contain unique canonical IPv4 network CIDRs more specific than 0.0.0.0/0."
  }

validation {
    # Overlapping local and remote address space cannot be routed unambiguously.
    condition = alltrue([
      for cidr in var.vpn_routed_prefixes : try(
        cidrhost("${cidrhost(cidr, 0)}/${split("/", var.vpc_cidr)[1]}", 0) != cidrhost(var.vpc_cidr, 0) &&
        cidrhost("${cidrhost(var.vpc_cidr, 0)}/${split("/", cidr)[1]}", 0) != cidrhost(cidr, 0),
        false
      )
    ])
    error_message = "vpn_routed_prefixes must not overlap vpc_cidr."
  }
}

variable "tgw_subnet_a_cidr" {
  description = "Transit Gateway attachment subnet in the first Availability Zone."
  type        = string
  default     = "192.168.124.0/28"

validation {
    condition = try(
      can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.tgw_subnet_a_cidr)) &&
      cidrhost(var.tgw_subnet_a_cidr, 0) == split("/", var.tgw_subnet_a_cidr)[0] &&
      tonumber(split("/", var.tgw_subnet_a_cidr)[1]) >= 16 &&
      tonumber(split("/", var.tgw_subnet_a_cidr)[1]) <= 28,
      false
    )
    error_message = "tgw_subnet_a_cidr must be an IPv4 network with an AWS-supported /16 through /28 prefix."
  }
}

variable "tgw_subnet_b_cidr" {
  description = "Transit Gateway attachment subnet in the second Availability Zone."
  type        = string
  default     = "192.168.124.16/28"

validation {
    condition = try(
      can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.tgw_subnet_b_cidr)) &&
      cidrhost(var.tgw_subnet_b_cidr, 0) == split("/", var.tgw_subnet_b_cidr)[0] &&
      tonumber(split("/", var.tgw_subnet_b_cidr)[1]) >= 16 &&
      tonumber(split("/", var.tgw_subnet_b_cidr)[1]) <= 28,
      false
    )
    error_message = "tgw_subnet_b_cidr must be an IPv4 network with an AWS-supported /16 through /28 prefix."
  }
}

variable "tunnel_inside_cidrs" {
  description = "Two unique AWS VPN tunnel /30 networks per Cloudflare anycast IP, ordered by VPN connection and tunnel."
  type        = list(string)
  default = [
    "169.254.240.44/30",
    "169.254.240.48/30",
  ]

validation {
    # Every AWS VPN connection contains exactly two tunnels.
    condition = length(var.tunnel_inside_cidrs) == length(var.cloudflare_anycast_ips) * 2 && length(distinct(var.tunnel_inside_cidrs)) == length(var.tunnel_inside_cidrs) && alltrue([
      for cidr in var.tunnel_inside_cidrs : try(
        split("/", cidr)[1] == "30" &&
        cidrhost(cidr, 0) == split("/", cidr)[0] &&
        cidrhost("${cidrhost(cidr, 0)}/20", 0) == "169.254.240.0" &&
        cidrhost("${cidrhost(cidr, -1)}/20", 0) == "169.254.240.0",
        false
      )
    ])
    error_message = "tunnel_inside_cidrs must contain two unique /30 network addresses within 169.254.240.0/20 for each Cloudflare anycast IP."
  }
}

variable "vpn_preshared_keys" {
  description = "Two AWS-compatible pre-shared keys per Cloudflare anycast IP, in tunnel order."
  type        = list(string)
  # Sensitive suppresses CLI display, but the keys are still stored in state.
  sensitive = true

validation {
    # List order matches tunnel_inside_cidrs and the generated tunnel numbering.
    # Key format matches the AWS Site-to-Site VPN PreSharedKey constraints.
    condition = length(var.vpn_preshared_keys) == length(var.cloudflare_anycast_ips) * 2 && alltrue([
      for key in var.vpn_preshared_keys : can(regex("^[A-Za-z1-9._][A-Za-z0-9._]{7,63}$", key))
    ])
    error_message = "vpn_preshared_keys must contain two keys per Cloudflare anycast IP; each key must contain 8-64 letters, numbers, periods, or underscores and cannot begin with 0."
  }

validation {
    # The AWS provider identifies tunnel1_address by matching the tunnel 1 PSK.
    # Identical PSKs disable that match and can swap the AWS public IPv4
    # addresses assigned to the Cloudflare WAN tunnels.
    condition     = length(distinct(var.vpn_preshared_keys)) == length(var.vpn_preshared_keys)
    error_message = "vpn_preshared_keys must be unique for every tunnel."
  }
}

variable "cloudflare_anycast_ips" {
  description = "One or two Cloudflare anycast IPs leased to cloudflare_account_id."
  type        = list(string)
  default     = ["162.159.135.1"]

validation {
    # Each anycast IP backs one AWS VPN connection containing two tunnels.
    condition = length(var.cloudflare_anycast_ips) >= 1 && length(var.cloudflare_anycast_ips) <= 2 && length(distinct(var.cloudflare_anycast_ips)) == length(var.cloudflare_anycast_ips) && alltrue([
      for address in var.cloudflare_anycast_ips : try(
        can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}$", address)) &&
        cidrhost("${address}/32", 0) == address,
        false
      )
    ])
    error_message = "cloudflare_anycast_ips must contain one or two distinct IPv4 addresses."
  }
}

variable "aws_transit_gateway_asn" {
  description = "Private ASN used by the AWS Transit Gateway."
  type        = number
  default     = 65020

validation {
    condition     = floor(var.aws_transit_gateway_asn) == var.aws_transit_gateway_asn && ((var.aws_transit_gateway_asn >= 64512 && var.aws_transit_gateway_asn <= 65534) || (var.aws_transit_gateway_asn >= 4200000000 && var.aws_transit_gateway_asn <= 4294967294))
    error_message = "aws_transit_gateway_asn must be an AWS-supported private ASN."
  }
}

variable "cloudflare_asn" {
  description = "CF Account ASN configured in Cloudflare WAN and used by every AWS customer gateway."
  type        = number
  default     = 13335

validation {
    # Cloudflare defaults to 13335 and permits a private 2-byte ASN instead.
    condition     = floor(var.cloudflare_asn) == var.cloudflare_asn && (var.cloudflare_asn == 13335 || (var.cloudflare_asn >= 64512 && var.cloudflare_asn <= 65534))
    error_message = "cloudflare_asn must match the CF Account ASN: 13335 or a private ASN from 64512 through 65534."
  }

validation {
    # The CF Account ASN must differ from the customer device ASN on each tunnel.
    condition     = var.cloudflare_asn != var.aws_transit_gateway_asn
    error_message = "cloudflare_asn must differ from aws_transit_gateway_asn."
  }
}

variable "cloudflare_additional_advertised_prefixes" {
  description = "Additional prefixes for Cloudflare to advertise to AWS on every BGP session. Eligible Cloudflare WAN routes are advertised without listing them here."
  type        = list(string)
  default     = []

validation {
    condition = length(distinct(var.cloudflare_additional_advertised_prefixes)) == length(var.cloudflare_additional_advertised_prefixes) && alltrue([
      for cidr in var.cloudflare_additional_advertised_prefixes : try(
        can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", cidr)) &&
        cidrhost(cidr, 0) == split("/", cidr)[0],
        false
      )
    ])
    error_message = "cloudflare_additional_advertised_prefixes must contain unique IPv4 network CIDRs."
  }
}

variable "cloudflare_tunnel_names" {
  description = "Optional Cloudflare WAN tunnel names in tunnel order, two per Cloudflare anycast IP. Leave empty to use &lt;deployment_name>-tun-01, -02, and so on."
  type        = list(string)
  default     = []

validation {
    # Cloudflare rejects a tunnel whose name matches any other tunnel in the account.
    condition = length(var.cloudflare_tunnel_names) == 0 || (
      length(var.cloudflare_tunnel_names) == length(var.cloudflare_anycast_ips) * 2 &&
      length(distinct(var.cloudflare_tunnel_names)) == length(var.cloudflare_tunnel_names) &&
      alltrue([for name in var.cloudflare_tunnel_names : can(regex("^[A-Za-z0-9_-]+$", name))])
    )
    error_message = "cloudflare_tunnel_names must be empty or contain two unique names per Cloudflare anycast IP, using only letters, numbers, hyphens, and underscores."
  }
}

main.tf

Create main.tf to build the AWS VPC, public workload subnet, Internet Gateway, split-egress routes, Transit Gateway, and one customer gateway and VPN connection per configured anycast IP. Each VPN connection contains two ordered tunnels.

```hcl data "aws_availability_zones" "available" { state = "available" }

locals { # Resources require two AZs; try() keeps expression evaluation safe until the # VPC precondition can return a clear error in a single-AZ Region. availability_zone_a = data.aws_availability_zones.available.names[0] availability_zone_b = try(data.aws_availability_zones.available.names[1], data.aws_availability_zones.available.names[0]) subnet_cidrs = [var.workload_subnet_cidr, var.tgw_subnet_a_cidr, var.tgw_subnet_b_cidr] subnet_pairs = [[0, 1], [0, 2], [1, 2]]

Each anycast IP creates one AWS customer gateway and one two-tunnel VPN.

customer_gateways = { for index, anycast_ip in var.cloudflare_anycast_ips : format("%02d", index + 1) => { cloudflare_anycast_ip = anycast_ip tunnel1_index = index * 2 tunnel2_index = index * 2 + 1 } } }

resource "aws_vpc" "workload" { cidr_block = var.vpc_cidr instance_tenancy = "default" enable_dns_support = true enable_dns_hostnames = false

tags = { Name = "${var.deployment_name}-vpc" }

lifecycle { precondition { condition = length(data.aws_availability_zones.available.names) >= 2 error_message = "The selected AWS Region must have at least two available Availability Zones." }

precondition { # Check both ends of each subnet against the VPC to prevent partial overlap. condition = alltrue([ for cidr in local.subnet_cidrs : try( cidrhost(cidr, 0) == split("/", cidr)[0] && tonumber(split("/", cidr)[1]) >= tonumber(split("/", var.vpc_cidr)[1]) && cidrhost("${cidrhost(cidr, 0)}/${split("/", var.vpc_cidr)[1]}", 0) == cidrhost(var.vpc_cidr, 0) && cidrhost("${cidrhost(cidr, -1)}/${split("/", var.vpc_cidr)[1]}", 0) == cidrhost(var.vpc_cidr, 0), false ) ]) error_message = "Each subnet CIDR must be a valid network contained within vpc_cidr." }

precondition { # Evaluate every pair so no workload or attachment subnet can overlap. condition = try(alltrue([ for pair in local.subnet_pairs : cidrhost("${cidrhost(local.subnet_cidrs[pair[1]], 0)}/${split("/", local.subnet_cidrs[pair[0]])[1]}", 0) != cidrhost(local.subnet_cidrs[pair[0]], 0) && cidrhost("${cidrhost(local.subnet_cidrs[pair[0]], 0)}/${split("/", local.subnet_cidrs[pair[1]])[1]}", 0) != cidrhost(local.subnet_cidrs[pair[1]], 0) ]), false) error_message = "The workload and Transit Gateway subnet CIDRs must not overlap." } } }

resource "aws_subnet" "workload" { vpc_id = aws_vpc.workload.id cidr_block = var.workload_subnet_cidr availability_zone = local.availability_zone_a map_public_ip_on_launch = true

tags = { Name = "${var.deployment_name}-workload" } }

The workload subnet uses direct Internet Gateway egress for destinations that

do not match a more-specific VPN route. Workloads still need a public IPv4

address and security controls; this reference deployment does not create workloads.

resource "aws_internet_gateway" "workload" { vpc_id = aws_vpc.workload.id

tags = { Name = "${var.deployment_name}-igw" } }

resource "aws_subnet" "tgw_a" { vpc_id = aws_vpc.workload.id cidr_block = var.tgw_subnet_a_cidr availability_zone = local.availability_zone_a

tags = { Name = "${var.deployment_name}-tgw-${local.availability_zone_a}" } }

resource "aws_subnet" "tgw_b" { vpc_id = aws_vpc.workload.id cidr_block = var.tgw_subnet_b_cidr availability_zone = local.availability_zone_b

tags = { Name = "${var.deployment_name}-tgw-${local.availability_zone_b}" } }

resource "aws_route_table" "workload" { vpc_id = aws_vpc.workload.id

tags = { Name = "${var.deployment_name}-workload-rt" } }

resource "aws_route_table_association" "workload" { subnet_id = aws_subnet.workload.id route_table_id = aws_route_table.workload.id }

resource "aws_ec2_transit_gateway" "cloudflare" { amazon_side_asn = var.aws_transit_gateway_asn auto_accept_shared_attachments = "disable" # Explicit associations and propagations below avoid implicit routing changes. default_route_table_association = "disable" default_route_table_propagation = "disable" dns_support = "enable" multicast_support = "disable" security_group_referencing_support = "disable" vpn_ecmp_support = "enable"