How to tell the terraform not to destroy the existing resource on condition
Hello I have a terraform variable which controls the creation of the resource
variable "apigw_key" {
type = string
default = "X"
}
When i run the terraform apply It create the resource appropriately
resource "aws_api_gateway_resource" "whitelist-create" {
parent_id = "u8u7hy"
path_part = "create"
rest_api_id = "9uumm7"
count = var.apigw_key == "X" ? 1 : 0
}
resource "aws_api_gateway_resource" "account-delete" {
parent_id = "fgty72"
path_part = "delete"
rest_api_id = "9uumm7"
count = var.apigw_key == "Y" ? 1 : 0
}
The output seems to be perfect when terraform apply is run
terraform apply -var="apigw_key=X"
Plan: 1 to add, 0 to change, 0 to destroy.
When i run the terraform plan on Y the X resources shows destroyed in the plan
variable "apigw_key" {
type = string
default = "Y"
}
terraform plan -var="apigw_key=Y"
Plan: 1 to add, 0 to change, 1 to destroy.
How to control the existing resource not to be destroyed
Edited based on Marko feedback
variable "X" {
type = bool
default = false
}
variable "Y" {
type = bool
default = false
}
This is my updated resource config
resource "aws_api_gateway_resource" "whitelist-create" {
parent_id = "u8u7hy"
path_part = "create"
rest_api_id = "9uumm7"
count = var.Y ? 1 : 0
}
resource "aws_api_gateway_resource" "account-delete" {
parent_id = "fgty72"
path_part = "delete"
rest_api_id = "9uumm7"
count = var.X ? 1 : 0
}
terraform apply -var X=true
aws_api_gateway_resource.account-delete will get created and maintain the state file
and when i do the following terraform apply -var Y=true it will create one resource and delete one
My Question is how to prevent existing resource not to be deleted ?
Generally, the behavior you're describing is desirable - if your configuration doesn't create a resource, you don't want that resource to exist. However, in some cases there might be requirements for record keeping or depreciation that prevent you from deleting it as soon as you don't need it.
If you want to conditionally create a resource, but not delete it when that condition changes, use the prevent_destroy lifecycle argument:
resource "aws_api_gateway_resource" "whitelist-create" {
parent_id = "u8u7hy"
path_part = "create"
rest_api_id = "9uumm7"
count = var.Y ? 1 : 0
lifecycle {
prevent_destroy = true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With