Conditionally Creating Terraform Resources
September 17, 2021
til | terraform | cloud
til | terraform | cloud
You can conditionally create a Terraform infrastructure object by combining the ternary operator with the count
meta-argument.
The count
meta-argument lets you define multiple similar objects using a single block. For example:
resource "aws_instance" "server" {count = 4 # create four similar EC2 instancesami = "ami-a1b2c3d4"instance_type = "t2.micro"tags = {Name = "Server ${count.index}"}}
We can therefore define a resource to be create with a count of 0
(don't create the resource at all) or 1
based on some condition. Here's an example of how we'd create some resource only if the variable env
is set to "prod"
.
resource "aws_instance" "server" {count = var.env == "prod" ? 1 : 0ami = "ami-a1b2c3d4"instance_type = "t2.micro"}
Further reading: Terraform documentation
Copyright © 2022 Darren Burns