Middle
What approach does Terraform use when recreating resources?
sobes.tech AI
Answer from AI
Terraform uses the "destroy and create" approach.
When a complete update or change of a resource is necessary, which cannot be done in-place, Terraform performs the following steps:
- Destroy the existing resource: Terraform deletes the resource from the infrastructure by calling the provider's API.
- Create a new resource: After successful deletion, Terraform creates a new instance of the resource with the new parameters.
This occurs when changes in the Terraform configuration require a full replacement of the resource. For example, changing the subnet type in the cloud (from public to private), which is not supported by in-place provider updates. Terraform determines the need for this approach during the execution of the terraform plan command. The plan output will explicitly indicate that the resource will be destroyed and recreated.
// Example of a resource that may be recreated when certain attributes change
resource "aws_instance" "example" {
ami = "ami-0abcdef1234567890" // Changing the AMI usually requires recreation
instance_type = "t2.micro" // Changing the instance type may also require recreation
subnet_id = "subnet-0123456789abcdef0" // Changing Subnet ID almost always requires recreation
tags = {
Name = "ExampleInstance"
}
}
Example output of terraform plan indicating recreation:
Plan: 1 to add, 0 to change, 1 to destroy.
Terraform will perform the following actions:
# aws_instance.example will be destroyed
- resource "aws_instance" "example" {
- ami = "ami-old-id" -> null
- arn = "arn:aws:ec2:..." -> null
... (other attributes)
}
# aws_instance.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-new-id"
+ instance_type = "t2.micro"
+ subnet_id = "subnet-0123456789abcdef0"
... (other attributes)
}