Problem
The terraform import command is successful, but the imported resource is not visible in the state file.
Prerequisites
- Using terraform version "< 1.7".
Cause
- You are using a terraform version < 1.7.
- The resource you want to import uses a
for_each
. - The imported resource is not defined in your code.
For example:
- You are using the following code:
variable "my_map" {
type = map(any)
default = {
key1 = "value1"
}
}
resource "random_uuid" "test" {
for_each = var.my_map
}
- The state list is showing the following:
terraform state list
random_uuid.test["key1"]
- You want to import
key2
which you haven't added to the code yet. This should give an error, but instead you get a successful import.
terraform import 'random_uuid.test["key2"]' aabbccdd-eeff-0011-2233-445566778899
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.
- The state file doesn't reflect this:
terraform state list
random_uuid.test["key1"]
Solution:
The main issue is you get an Import successful! message which is incorrect. It should give an error stating the imported target is not defined in your code.
- Update your terraform binary to version 1.7 or higher
- Execute the import command again
terraform import 'random_uuid.test["key2"]' aabbccdd-eeff-0011-2233-445566778899
╷
│ Error: Configuration for import target does not exist
│
│ The configuration for the given import random_uuid.test["key2"] does not exist. All target instances must have an associated configuration
│ to be imported.
- Now you get a proper error message.
- Alter your code to reflect the imported target:
variable "my_map" {
type = map(any)
default = {
key1 = "value1"
key2 = "value2"
}
}
resource "random_uuid" "test" {
for_each = var.my_map
}
- The import command will now succeed and add the resource to the state:
terraform import 'random_uuid.test["key2"]' aabbccdd-eeff-0011-2233-445566778899
random_uuid.test["key2"]: Importing from ID "aabbccdd-eeff-0011-2233-445566778899"...
random_uuid.test["key2"]: Import prepared!
Prepared random_uuid for import
random_uuid.test["key2"]: Refreshing state... [id=aabbccdd-eeff-0011-2233-445566778899]
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.
Outcome
The use of a terraform binary lower then 1.7 can give an incorrect import result. Please use the latest terraform version to get the proper error message and alter the code.
Additional Information
-
The import command has been fixed in version 1.7. Please see the details for the fix here