Lifecycle
In this lesson, we'll discuss the advanced Terraform resource "lifecycle" in detail.
We'll cover the following
Lifecycle#
Every resource has a special block that can be set on it called the lifecycle
block. This gives you, the creator, a bit more control as to the lifecycle
of the resource. Let’s run through the options that
you can configure using the lifecycle
block.
create_before_destroy
is a bool that you can set on a resource. For example:
Setting this property means that, as long as the backend API allows, Terraform will create the new resource before it destroys the old one. This can be handy in certain scenarios when replacing infrastructure where you want to make sure the new infrastructure is created before the old infrastructure is destroyed.
prevent_destroy
is a bool that you can set on a resource. For example:
Setting this property will stop Terraform from destroying a resource as long as the property remains set.
Project example#
Let’s dive into a quick example:
Running the project#
Clicking the terminal will run terraform init
followed by terraform apply
. Confirm the plan with yes
and you
should see a single queue get created.
After running the terraform apply
, try and run terraform destroy
. You will see the error.
message Error: Instance cannot be destroyed
This is Terraform preventing you from destroying the resource since you have set the lifecycle to prevent a destroy command.
📝Note: You can remove the whole resource block from your code and run
terraform apply
and Terraform will quite happily remove the queue.
The prevent destroy can be useful if you want to make sure that a resource is never
destroyed when someone runs terraform destroy
or if someone changes something that would
cause Terraform to have to recreate the resource. The prevent_destroy
flag can make some Terraform changes impossible to make, however, so it should be used very sparingly.
ignore_changes
attribute#
ignore_changes
is a special attribute that allows you to ignore any changes to a certain property or
set of properties. This should again be used sparingly as you are preventing Terraform from doing
its job of syncing the world to your code. However, this property is worth knowing about as it can
be handy in a small set of circumstances.