Search code examples
terraformcloud-foundryinfrastructure-as-codeterraform-modules

Alternative to Terraform `lifecycle` for modules


I have a Terraform file that I want to prevent anyone from ever running terraform destroy on.

The normal way to do this would be to include the lifecycle block containing prevent_destroy = true on one or more resources in the file. But, I cannot do this. The file contains only modules, which do not accept lifecycle.

I considered modifying the modules themselves to contain a lifecycle block that could be configured with an argument. But that won't work either because the block accepts only literal values, not variables.

Another alternative would be to add a do-nothing resource to the file that would accept the lifecycle block. It dosen't much matter what resource this is, I guess? Any resource containing the block with prevent_destroy set should be enough to halt the destroy command. Right?

So, what's the most economical resource type for me to use to do nothing but hold this block? Ideally, one that dosen't incur additional cloud provider costs or security exposure.

The provider is Cloud Foundry. Terraform version is 1.7.5.


Solution

  • I think you can use the "Do-Nothing" Resources here.

    1. Pick a Placeholder: Terraform offers a couple of resources that are basically there to hold your spot. You have two options:
    • null_resource: This is like a blank notecard specifically designed for situations where you just need a space filler.

    • local_value: Even though it's meant to define local values, it can also act as a do-nothing resource in a pinch.

    Add Resource and lifecycle block:

    In your main Terraform file (the one with the modules), add your chosen resource and the lifecycle block with prevent_destroy = true:

    resource "null_resource" "prevent_destroy" {
    
      lifecycle {
        prevent_destroy = true
      }
    }
    
    

    This code just defines a null_resource named prevent_destroy and tells Terraform to avoid this if someone tries to run terraform destroy.

    Hope this helps!