How to change the subnet association from one route table to another route table using terraform?

1.9k views Asked by At

In AWS, using Terraform I have launched certain instances running in private subnet. I have to install certain packages in the private instances. So i make a temporary associaton with a route table which is connected to internet gateway. After installation of the packages when i want to make the association of that particular subnet with the route table which is connected to NAT, it is throwing an error telling that route table association already exist. But if i go to aws console i'm able to do it manually. Is there any way on how can i do it using terraform?

Thank you in Advance.

1

There are 1 answers

0
rvelaz On

Without seeing your Terraform file is a bit difficult. But from your explanation it seems that the default behaviour of the VPC is to use the route table that is connected to a NAT instance. You can create the route table and then make it VPC's default with Terraform in this way:

resource "aws_main_route_table_association" "a" {
  vpc_id         = "${aws_vpc.foo.id}"
  route_table_id = "${aws_route_table.bar.id}"
}

Then when you want to temporarily associate a subnet to your internet gateway it's just a matter of adding the following:

resource "aws_route_table_association" "a" {
  subnet_id      = "${aws_subnet.your_subnet.id}"
  route_table_id = "${aws_route_table.your_IG_route_table.id}"
}

Once you're done remove the route table association.