CodexBloom - Programming Q&A Platform

Terraform 1.4.3: Issues with Conditional Resource Creation in GCP Based on Existing Resources

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-01
terraform gcp google-cloud-storage HCL

I tried several approaches but none seem to work. I've tried everything I can think of but I'm a bit lost with I've been struggling with this for a few days now and could really use some help. I'm working on a project and hit a roadblock. After trying multiple solutions online, I still can't figure this out... I'm encountering issues with conditionally creating Google Cloud Platform resources using Terraform 1.4.3. My goal is to create a Cloud Storage bucket only if it doesn't already exist, but I'm hitting a snag with the `count` parameter and the `data` block for the existing bucket. Hereโ€™s what I have: ```hcl provider "google" { project = var.project_id region = var.region } data "google_storage_bucket" "existing_bucket" { name = "my-existing-bucket" } resource "google_storage_bucket" "new_bucket" { count = data.google_storage_bucket.existing_bucket ? 0 : 1 name = "my-new-bucket" location = var.region } ``` However, Iโ€™m getting the following error when I try to apply the configuration: ``` Error: Invalid value for "count"; must be a non-negative integer ``` It seems that Terraform is not recognizing the data source as a condition that can return `true` or `false`. I attempted to use the `length` function to check if the bucket exists but that didnโ€™t help either. To troubleshoot, I tried simplifying the logic by defining a local variable: ```hcl locals { bucket_exists = length(data.google_storage_bucket.existing_bucket.id) > 0 } ``` Then changing the `count` parameter accordingly: ```hcl count = local.bucket_exists ? 0 : 1 ``` But I continue to face the same issue. Is there a specific way to check for existing resources and conditionally create new ones in GCP with Terraform? Any insights or best practices would be greatly appreciated. My development environment is Linux. Any help would be greatly appreciated! This is part of a larger service I'm building. What am I doing wrong? I'm working on a service that needs to handle this. I'm working on a API that needs to handle this. What's the correct way to implement this? What's the correct way to implement this?