Terraform: Lifecycle
The lifecycle
block in Terraform is used to define various settings and behaviors related to the lifecycle of a resource. This block allows you to customize how Terraform manages resources during the stages of creation, updating, and deletion.
In this article you’ll learn more about it and how to use in specific situatuons.
Basic Syntax:
The lifecycle
block is typically embedded within a resource block and has various configuration options:
resource "aws_instance" "example" {
# ... other configurations ...
lifecycle {
# Settings go here
}
}
Example – create_before_destroy
:
One of the frequently used settings in the lifecycle
block is create_before_destroy
. This setting is a boolean that controls the order in which Terraform creates and destroys resources during an update.
resource "aws_instance" "example" {
ami = "ami-12345678"
instance_type = "t2.micro"
# ... other configurations ...
lifecycle {
create_before_destroy = true
}
}
In this example, create_before_destroy
is set to true
, indicating that Terraform should create a new instance before destroying the old one during updates. This is useful when replacing resources that cannot be updated in place, such as instances with certain attribute changes.
Other Settings:
Beyond create_before_destroy
, the lifecycle
block supports other settings, including:
- Prevent Destroy (
prevent_destroy
):- If set to
true
, this prevents Terraform from destroying the resource during theterraform destroy
command. This can be useful to protect certain resources from accidental deletion.
- If set to
- Ignore Changes (
ignore_changes
):- Specifies a list of attribute names for which changes should be ignored during updates. This can be used to prevent certain attributes from triggering updates.
lifecycle { prevent_destroy = true ignore_changes = ["tags"] }
Use Cases:
- Create Before Destroy:
- As mentioned earlier,
create_before_destroy
is commonly used when dealing with resources that must be replaced during an update, such as instances with certain attribute changes.
- As mentioned earlier,
- Prevent Destroy:
prevent_destroy
can be used to safeguard critical resources from accidental deletion.
- Ignore Changes:
ignore_changes
is useful when certain attribute changes should not trigger updates.