Terraform Series - LifeCycles
In this post we will see an interesting concept called "LifeCycle Rules".
This is almost like a hook to tell terraform on what needs to be done.
There are 3 lifecycle rules:
1) Prevent Destroy
2) Create Before Destroy
3) Ignore Changes
resource "local_file" "name" {
filename = "/root/pets.txt"
content = "We love pets"
file_permission = "0700"
}
I am using the resource "local_file" to create a file with a content and permission "0700".
# local_file.name:
resource "local_file" "name" {
content = "We love pets"
directory_permission = "0777"
file_permission = "0700"
filename = "/root/pets.txt"
id = "978236bb65828b96bae1df000a4f9d6e6c5ca5a8"
}
Modifying the permission back "0755" with lifecycle rules.
resource "local_file" "name" {
filename = "/root/pets.txt"
content = "We love pets"
file_permission = "0700"
lifecycle {
create_before_destroy = true
}
}
By default terraform will destroy and create a resource.
-/+ destroy and then create replacement
With "create_before_destroy" the resource will be created first and deleted.
+/- create replacement and then destroy
Terraform will perform the following actions:
# local_file.name must be replaced
+/- resource "local_file" "name" {
~ file_permission = "0755" -> "0700" # forces replacement
~ id = "978236bb65828b96bae1df000a4f9d6e6c5ca5a8" -> (known after apply)
# (3 unchanged attributes hidden)
}
local_file.name: Creating...
local_file.name: Creation complete after 0s [id=978236bb65828b96bae1df000a4f9d6e6c5ca5a8]
local_file.name (deposed object 1e72cdfc): Destroying... [id=978236bb65828b96bae1df000a4f9d6e6c5ca5a8]
local_file.name: Destruction complete after 0s
Prevent_Destroy:
Prevents a resource from destroyed.
resource "local_file" "name" {
filename = "/root/pets.txt"
content = "We love pets"
file_permission = "0755"
lifecycle {
prevent_destroy = true
}
}
When I try to make changes it will throw the below errors:
PS C:\Users> terraform plan
local_file.name: Refreshing state... [id=978236bb65828b96bae1df000a4f9d6e6c5ca5a8]
╷
│ Error: Instance cannot be destroyed
│
│ on main.tf line 1:
│ 1: resource "local_file" "name" {
│
│ Resource local_file.name has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with
│ the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target flag.
Ignore_Changes:
Ignore any changes applied to a resource.
resource "local_file" "name" {
filename = "/root/pets.txt"
content = "We love pets"
file_permission = "0700"
lifecycle {
ignore_changes = [
file_permission
]
}
}
PS C:\Users\> terraform apply
local_file.name: Refreshing state... [id=978236bb65828b96bae1df000a4f9d6e6c5ca5a8]
No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Comments
Post a Comment