ABOMINABLE.dev about

Import AWS VPN Connection to Terraform

Acquiring technical debt in DevOps eventually means creating cloud resources by hand. The Terraform CLI tool has a process to import these resources into your infrastructure code.

The Terraform code for each resource must be written before you can import it. In the case of an AWS VPN Connection it would look something like this:

// main.tf
// ... existing code
resource "aws_vpn_gateway" "hell" {
  bgp_asn = 65000
  ip_address = var.hell.vpn_gateway_ip
  type = "ipsec.1"
  tags {
    Name = "hell"
  }
}

resource "aws_vpn_connection" "hell" {
  vpn_gateway_id      = "${aws_vpn_gateway.hell.id}"
  customer_gateway_id = "${aws_customer_gateway.main.id}"
  type                = "ipsec.1"
  static_routes_only  = false
  tags {
    Name = "abington-house"
  }
}

Ensure the resource's parameters match with what exists in AWS. The tags do not matter, insofar as they don't need to match for the import, however Terraform will align the resource's tags to what you've codified.

Once that is written we can run the terraform import command. First we need to know what attribute Terraform expects to import on. Looking at the docs for an aws_vpn_gateway it is vpn_gateway_id. Grab this from AWS. Finally we can run:

$ terraform import aws_vpn_gateway.hell vgw-666f666ffff
aws_vpn_gateway.hell: Importing from ID "vgw-666f666ffff"...
aws_vpn_gateway.hell: Import complete!
  Imported aws_vpn_gateway (ID: vgw-666f666ffff)
aws_vpn_gateway.hell: Refreshing state... (ID: vgw-666f666ffff)

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

That is it! Run the import command for the aws_vpn_connection as well to bring it into your state.

Not all resources need to be imported to bring them into your state. For a VPN connection that has existing static routes we can write a aws_vpn_connection_route for each. Looking at the docs we can see it has no import attribute. When you run Terraform after creating the aws_vpn_connection_route to match your existing routes, they will be brought into your state. It is best to check the Terraform docs on what needs/doesn't need to be imported.