Terraform Lifecycle

Within the #resource block, we could define a lifecycle block to have fine control over how to manage the resource which could be useful in Immutable Infrastructure# implementation. There are three options available: create_before_destroy, prevent_destroy and ignore_changes.

Setting create_before_destroy to true like the following will command the resource to be created before destroyed, unlike the default behaviour where the resource will be destroyed first before created.

resource ... {
  lifecycle {
    create_before_destroy = true
  }
}

To disallow destroying the resource altogether when running terraform destroy, set prevent_destroy to true like below. That being said, the resource will still be destroyed if the command terraform destroy was run.

resource ... {
  lifecycle {
    create_before_destroy = true
  }
}

If we don’t want the changes result in altering the state of resource, that is whether it should be created or destroyed, we could tell #Terraform to ignore changes according to a list. We could define which variable should be ignored inside a list and then pass it to the option ignore_changes. If all changes should be ignored in the resource, then we could use the special keyword all and assigned it to the option.

resource ... {
  lifecycle {
    ignore_changes = [
      ...
    ]
  }
}
Links to this page
  • Terraform Providers

    The depended resources will be created first before the resources that depend on them, and be destroyed in reversed order. Using the above example, local_file.other_file will be created before local_file.my_file since it is the dependency of the latter, and destroyed (using the command terraform destroy) after the latter has been destroyed by Terraform. Otherwise, the resource creation will always be in parallel if possible. We can fine tune how could we handle the resource using Terraform Lifecycle#.

  • Terraform Meta Arguments
#devops #resource