githubEdit

4019504503__how-do-i-prevent-terraform-from-destroying-resources-when-drift-is-detected

How do I prevent Terraform from destroying resources when drift is detected?

Context When managing infrastructure with Terraform, resources that were created manually or modified outside of Terraform can cause state drift. By default, Terraform may attempt to destroy these resources to maintain consistency with the defined state. This can lead to unintended disruptions in infrastructure, such as VPC peering connections or S3 buckets being removed. Answer To properly manage resources and prevent unwanted destruction when drift is detected, follow these best practices: Import existing resources into Terraform state: terraform import [resource_type].[resource_name] [resource_id] For example, to import a VPC peering connection: terraform import aws_vpc_peering_connection.peer_connection pcx-12345678 Define the resource in your Terraform configuration to match the existing infrastructure: resource "aws_vpc_peering_connection" "peer_connection" { vpc_id = "vpc-123456" peer_vpc_id = "vpc-789012" peer_owner_id = "123456789012" } Use lifecycle rules to prevent automatic destruction: resource "aws_vpc_peering_connection" "peer_connection" {

... resource configuration ...

lifecycle { prevent_destroy = true } } Best Practice: Always import existing infrastructure into Terraform before making changes to ensure proper state management and prevent unintended resource destruction.

Last updated

Was this helpful?