CodexBloom - Programming Q&A Platform

Unexpected Terraform Behavior with Conditional Resource Creation Based on Data Source Output

πŸ‘€ Views: 8368 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-24
terraform aws s3 conditional-resources hcl

I'm prototyping a solution and I've been banging my head against this for hours... I've been banging my head against this for hours... I'm relatively new to this, so bear with me. I'm working with Terraform 1.4.3 to provision AWS resources, but I'm working with an unexpected behavior when I try to conditionally create an S3 bucket based on the output of a data source. I have a data source that fetches the current AWS region, and I want to create the S3 bucket only if the region matches `us-west-2`. Here's what I have: ```hcl data "aws_region" "current" {} resource "aws_s3_bucket" "my_bucket" { count = data.aws_region.current.name == "us-west-2" ? 1 : 0 bucket = "my-bucket-${var.environment}" acl = "private" } ``` I expected that if the region is not `us-west-2`, the bucket would not be created, but I'm getting an behavior: ``` behavior: `count` want to be computed from data sources on main.tf line 5, in resource "aws_s3_bucket" "my_bucket": 5: count = data.aws_region.current.name == "us-west-2" ? 1 : 0 ``` It seems that I'm not allowed to use a data source directly in the `count` meta-argument. I tried moving the logic to a variable instead, but I'm not sure how to structure it properly. I attempted the following: ```hcl variable "should_create_bucket" { type = bool default = data.aws_region.current.name == "us-west-2" } resource "aws_s3_bucket" "my_bucket" { count = var.should_create_bucket ? 1 : 0 bucket = "my-bucket-${var.environment}" acl = "private" } ``` However, this still results in an behavior because the variable can’t be assigned directly from a data source. Is there a recommended way to conditionally create resources based on data source outputs? Should I be using a different approach, like a local value or a for_each with a conditional? Any insights would be greatly appreciated! I'd love to hear your thoughts on this. The project is a web app built with Hcl. The project is a service built with Hcl. I'm working on a REST API that needs to handle this. Thanks, I really appreciate it!