user15778874
user15778874

Reputation: 47

Attaching an AWS VPC to an IGW with Terraform

I am trying to build a VPC resource with Terraform to provide for an MWAA build. In the AWS documentation, I see the below resources (in addition to subnets, etc.) are defined to create a whole VPC environment. I have defined aws_vpc & aws_internet_gateway with Terraform, but cannot find a Terraform template for InternetGatewayAttachment - only for aws_vpn_gateway_attachment.

  1. How do I go about attaching the VPC resource to the IGW w/Terraform?
  2. Do I need an resource, or is that implied w/the vpc_id in the TF aws_internet_gateway resource definition?

P. S. - I am coming from GCP & not super familiar w/AWS Networking concepts.

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCIDR
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC

....

Upvotes: 0

Views: 3593

Answers (3)

bemo
bemo

Reputation: 489

How do I go about attaching the VPC resource to the IGW w/Terraform?

You've got two options - one is what X-Men's answer shows, i.e. using a aws_vpc and a aws_internet_gateway.

There's another option to attach later using a separate aws_internet_gateway_attachment resource.

Do I need an resource, or is that implied w/the vpc_id in the TF aws_internet_gateway resource definition?

You don't need a resource, it's implied from the vpc_id on the internet gateway, but a resource would be helpful if you want to defer attachment until later.

Be sure you don't define both a vpc_id in the aws_internet_gateway and a aws_internet_gateway_attachment - this cause Terraform to try to double-attach and result in an error like this, which I've just had and found this question(!) (IDs removed):

Internet Gateway ... Resource.AlreadyAssociated ... already attached to network

Upvotes: 0

X-Men
X-Men

Reputation: 446

1 Create VPC

2 Create an Internet Gateway

resource "aws_vpc" "my_vpc" { cidr_block = "10.0.0.0/16"}

resource "aws_internet_gateway" "gw" { vpc_id = aws_vpc.my_vpc.id}

in the internet gateway you can give the name of the vpc.

Upvotes: 3

Mark B
Mark B

Reputation: 200860

If you look at the official documentation you will see that the Internet Gateway resource requires you to specify the VPC ID. Terraform doesn't support creating internet gateways without immediately attaching them to a VPC.

Upvotes: 0

Related Questions