Disclaimer: I am working at HashiCorp (now IBM) as part of the Terraform
Core team. The postings on this site are my own and don’t necessarily represent
IBM’s positions, strategies or opinions.
Since I am involved in Terraform my opinions can sometimes be (unconsciously)
biased. I hope you enjoy the post anyway.
This blog post is meant as a growing library of common usage patterns when using Terraform Actions in your configuration. If you have a pattern that you would like to see here, please leave a comment below or write me on LinkedIn.
Content
- What are Terraform Actions?
- Pattern: If any of these resources changed, run this action exactly once
- Pattern: This could be your problem!
What are Terraform Actions?
Terraform Actions are a new block in the Terraform language that allows you to express non-CRUD operations in your configuration. Please see Introduction to Terraform Actions for a detailed introduction.
Pattern: If any of these resources changed, run this action exactly once
It’s a very classical pattern: If either your ansible playbook or one of the servers changes you want to re-run the ansible playbook to configure the server. If you configure the action to run after_create / after_update on both resources ansible will run twice if both resources changed in the same apply.
The pattern we found most helpful for this when designing Terraform Actions was using a terraform_data resource (that comes built-in with Terraform, so no need to install an external provider).
resource "foo" "a" {}
resource "foo" "b" {}
resource "foo" "c" {}
action "bar" "if_something_changed" {}
resource "terraform_data" "trigger_if_something_changes" {
lifecycle {
replace_triggered_by = [foo.a, foo.b, foo.c]
action_trigger {
# The first creation and replace will trigger this
events = [after_create]
actions = [action.bar.if_something_changed]
}
}
}
There is only one terraform_data so it can be replaced at most once per apply. If any of the foo resources changed, the terraform_data will be replaced, which will trigger the action exactly once.
Pattern: This could be your problem!
This blog post is meant to extend over time: Did you run into a tricky Terraform Actions situation you don’t have a solution to yet? Please let me know in the comments below and I will try to find a solution and add it to this post. If you have a solution already, please share it in the comments as well so others can learn from it!
Do you have feedback around actions or do you want to hear about a specific topic around Terraform / Software Development / Language Design / Infrastructure as Code? Please let me know in the comments below.