The following example Terraform code snippet creates a Transit Gateway with VPC and VPN attachments:
provider "aws" {
region = "us-west-2"
}
# Create a transit gateway
resource "aws_ec2_transit_gateway" "example" {
description = "Example transit gateway"
}
# Create a VPC attachment
resource "aws_ec2_transit_gateway_vpc_attachment" "example_vpc_attachment" {
subnet_ids = ["subnet-abc123", "subnet-def456"] # IDs of the subnets in the VPC to attach
transit_gateway_id = aws_ec2_transit_gateway.example.id
vpc_id = "vpc-xyz789" # ID of the VPC to attach
}
# Create a VPN attachment
resource "aws_ec2_transit_gateway_vpn_attachment" "example_vpn_attachment" {
transit_gateway_id = aws_ec2_transit_gateway.example.id
vpn_connection_id = "vpn-123456" # ID of the VPN connection to attach
}
In this example, we’re using the aws_ec2_transit_gateway resource type to create a transit gateway in the us-west-2 region. We’re specifying a description parameter to provide a description for the transit gateway.
We’re also using the aws_ec2_transit_gateway_vpc_attachment and aws_ec2_transit_gateway_vpn_attachment resource types to create VPC and VPN attachments, respectively. For the VPC attachment, we’re specifying the IDs of the subnets in the VPC to attach with the subnet_ids parameter, and the ID of the VPC to attach with the vpc_id parameter. For the VPN attachment, we’re specifying the ID of the VPN connection to attach with the vpn_connection_id parameter.
Note that in both cases, we’re referencing the id attribute of the transit gateway resource created earlier with the aws_ec2_transit_gateway.example.id syntax, which ensures that the attachments are created on the correct transit gateway.