简体   繁体   中英

How to move from Terraform aws_network_interface with attachment block to aws_network_interface_attachment resource

We use Terraform to create and manage our AWS infrastructure. We have some exiting ec2 instances with a second network interface that were created by using the attachment block in the aws_network_interface resource. We are wanting to move to using the aws_network_interface_attachment resource and remove the attachment block from the aws_network_interface resource. However, when we attempt this, Terraform just wants to attach the network interface event though it's already attached, this causes the job to fail. We can't remove the interface manually and let Terraform attach it because this will cause a service outage. Does anyone have any suggestions?

Old Code

resource "aws_network_interface" "name" {
...
attachment {
    instance     = "SomeInstanceId"
    device_index = 1
  }
}

New Code

resource "aws_network_interface_attachment" "attachmentName" {
  provider = "aws.client"
  instance_id = "SomeInstanceId"
  network_interface_id = "SomeInterfaceId"
  device_index = 1
}

Disclaimer: its a bad idea to mess around with your state file like this, except sometimes its the only way. Before you start make sure you backup your tf state, and if you want to be extra safe, run terraform with read only credentials temporarily so it cant mess up anything important. This is an advanced change with the chance to permanently corrupt your state so dont proceed if you're not sure.

Attachments are a weird non-resource terraform construct so its not really possible to work on them in the normal way.

However the tfstate file is just json, you can adjust it to represent whatever state you want. I'd do something like the following:

  1. Create a brand new terraform instance, with just an ec2 instance and the second eni as an embedded block, save the state file
  2. Create another new terraform instance, this time with the ec2 instance and secondary eni setup how you want
  3. Compare the state files and work out the differences
  4. Triple check your production tfstate file is backed up
  5. Manually change the tfstate file (the one in s3 if you're using remote state) to look like it does in step 2
  6. Run a terraform plan to make sure there are no problems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM