Terraform Associate 004 ยท Dependencies, validation and sensitive data
Preconditions and postconditions
precondition and postcondition in lifecycle blocks, what each can reference, when they are evaluated and what happens on failure (4g).
Key points
- Both live in a lifecycle block with a condition and error_message.
- A precondition (resource, data, output) is checked before the object is created and can reference other objects.
- A postcondition (resource, data) is checked after the object is applied or read and refers to itself through self.
- A failure is an error that halts the operation, and it does not undo actions already taken.
Source: https://developer.hashicorp.com/terraform/language/expressions/custom-conditions
Practice questions
How does a postcondition refer to the object it is attached to?
- self
- this
- local
- each
Show answer
Answer: A. self
Inside a postcondition the object itself is available as self, for example self.tags["Component"].
Which statements are true?
- Preconditions can be used in resource, data and output blocks
- Postconditions can refer to the object through self
- A failed condition throws an error and halts the operation
- A failed postcondition rolls back what Terraform did
- Preconditions can use self
Show answer
Answer: A. Preconditions can be used in resource, data and output blocks, B. Postconditions can refer to the object through self, C. A failed condition throws an error and halts the operation
Preconditions work in resource, data and output blocks; postconditions use self; a failed condition is an error that halts. Neither rolls back earlier actions.
If a postcondition fails, Terraform automatically undoes the changes it already made to that resource.
Show answer
Answer: False
False. Terraform stops and blocks dependents, but it does not undo actions already taken.
Practice 8 questions on this topic in Bitzu
Short lessons, instant explanations and spaced review of what you get wrong. Free on iOS and Android.
