CodexBloom - Programming Q&A Platform

Terraform: implementing Conditional Resource Creation Based on Local Variables

👀 Views: 90 💬 Answers: 1 📅 Created: 2025-06-12
terraform aws s3 hcl

I'm a bit lost with I'm stuck on something that should probably be simple... I'm trying to use local variables in Terraform to conditionally create resources based on input variables, but I'm running into issues where the resources are not being created as expected. I'm using Terraform version 1.3.0 with the AWS provider version 4.0.0. Here's the relevant part of my `main.tf` file: ```hcl variable "create_s3_bucket" { type = bool default = false } locals { bucket_name = "my-bucket-${var.environment}" } resource "aws_s3_bucket" "my_bucket" { count = var.create_s3_bucket ? 1 : 0 bucket = local.bucket_name acl = "private" } ``` In my `terraform.tfvars`, I have set `create_s3_bucket = true`, but when I run `terraform apply`, I get: ``` behavior: Incorrect attribute value type on main.tf line 11, in resource "aws_s3_bucket" "my_bucket": 11: count = var.create_s3_bucket ? 1 : 0 The "count" argument must be a whole number, not a tuple. ``` I’ve double-checked the variable definitions and ensured there are no type mismatches. I’ve also tried hard-coding the `count` to 1 to see if the S3 bucket creation works independently, which it does. However, when I use the conditional logic, it fails. I suspect there might be something off with how I'm using the local variable or the condition itself. What am I missing here? Is there a better way to handle conditional resource creation in Terraform using local variables? Any insights would be greatly appreciated! For context: I'm using Hcl on Ubuntu. How would you solve this? What's the best practice here? What am I doing wrong?