Problem
When importing an existing AWS EC2 instance with attached Elastic Network Interfaces (ENIs) into Terraform management, you may encounter unexpected plan output. This is due to a known issue with the AWS provider that occurs after running terraform import on the aws_instance and aws_network_interface resources.
Cause
This issue occurs because common approaches to defining the network interface attachment in configuration result in errors after the import.
Incorrect Approach 1: Using the network_interface block
Configuring the network_interface block on the aws_instance resource forces the recreation of the instance.
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"
}
# ...
}Incorrect Approach 2: Using the aws_network_interface_attachment resource
Using a separate aws_network_interface_attachment resource to connect the instance and network interface will show that the attachment will be created in the plan output.
# aws_network_interface_attachment.foo will be created
+ resource "aws_network_interface_attachment" "foo" {
# ...
}However, the terraform apply command will fail because the interface is already attached.
│ 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
To correctly manage an imported EC2 instance and its ENIs, define the attachment within the aws_network_interface resource itself, using the attachment block.
This approach correctly reflects the existing infrastructure in your configuration.
resource "aws_network_interface" "test" {
# ...
attachment {
instance = aws_instance.example.id
device_index = 0
}
}After applying this configuration, Terraform will report no changes are needed.
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 Information
If you are unfamiliar with the terraform import command, review the following resources: