Unlocking the Full Potential of Terraform: Expert Tricks and Hacks
Terraform is an incredibly powerful tool for managing infrastructure, and with just a few hours of practice, you can master the basics. However, as you dive deeper, you’ll encounter tasks that seem straightforward but lack an obvious solution. In this article, we’ll explore some expert tricks and hacks to help you get the most out of this popular infrastructure as code (IaC) solution.
On-Off Switch for Resources with Count
One of Terraform’s strengths is its ability to turn blocks of resources and data into reusable modules. However, you’ll often need a way to disable the creation of certain resources based on an input variable. While there’s no attribute like resource_enabled = false
to disable resource creation, you can achieve a similar effect by setting count = 0
to disable resource creation or count = 1
to enable it. This technique is commonly used even within official Terraform modules.
Running Local Commands with Null_Resource
Sometimes, Terraform’s built-in functionality just isn’t enough. You may need to execute a command locally on the machine running Terraform. This is where the mysterious null_resource
comes in. Acting like a normal resource within the Terraform resource graph, null_resource
doesn’t actually do anything. However, it can run provisioners, including the local-exec
provisioner, which runs a command on the local machine.
Breaking Up Dependent Providers into Staged Terraform Runs
When building a large infrastructure in Terraform, you’ll likely need to create a service and then configure that service via a separate Terraform provider. However, Terraform can’t handle situations where a Terraform provider depends on the creation of a resource in another provider. To solve this, break up your Terraform project into smaller projects that can be run in a chain, using remote state to import the Terraform state from previous runs.
Handling File Dependencies between Resources with Templatefile()
Terraform makes it easy to take outputs from one resource and pipe them as inputs to another resource. However, it struggles when a resource writes a file on the local filesystem that another resource needs to read as an input. To trick Terraform into realizing this dependency, use the templatefile()
function, which reads a file from the filesystem and substitutes any variables you pass to the function into the file as it reads it.
By mastering these expert tricks and hacks, you’ll be able to unlock the full potential of Terraform and streamline your infrastructure management. Happy Terraforming!