Background
It is possible to import an existing AWS EC2 instance with existing attached Network Interfaces into Terraform's management, but there is a known issue that can cause unexpected plan output after running terraform import on the aws_instance and associated aws_network_interface resources. This results in a couple of possible issue scenarios:
Issue A. Configuring the network_interface block on the aws_instance to reference the associated aws_network_interface forces recreation:
Terraform will perform the following actions:
# aws_instance.example must be replaced
-/+ resource "aws_instance" "example" {
... + network_interface { # forces replacement
+ delete_on_termination = false
+ device_index = 0
+ network_interface_id = "eni-0aadab1c2f7ec218d"
} ...
Issue B. Configuring the aws_network_interface_attachment resource to connect the existing EC2 instance and network interface resources will show the resource will be created in the plan output:
# aws_network_interface_attachment.foo will be created
+ resource "aws_network_interface_attachment" "foo" {
But the apply will error:
│ Error: Error attaching network interface (eni-0aadab1c2f7ec218d) to instance (i-0ff957ed6b6cbbe6b), message: "Instance 'i-0ff957ed6b6cbbe6b' already has an interface attached at device index '0'.", code: "InvalidParameterValue"
│
│ with aws_network_interface_attachment.foo,
│ on main.tf line 41, in resource "aws_network_interface_attachment" "foo":
│ 41: resource "aws_network_interface_attachment" "foo" {
│
Solution
Instead of configuring an aws_network_interface_attachment resource or the network_interface block on aws_instance, use the attachment block on the aws_network_interface resource, e.g.:
resource "aws_network_interface" "test" {
...
attachment {
instance = aws_instance.example.id
device_index = 0
}
}
This will allow the apply to proceed without unexpected recreation or errors related to the network interface(s):
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Additional Resources
If you are unfamiliar with running the terraform import command, please check out the following resources:
- Importing Infrastructure
- How to Import Resources into a Remote State Managed by Terraform Cloud
aws_instanceimport specificsaws_network_interfaceimport specifics