CodexBloom - Programming Q&A Platform

Terraform 1.4.3: scenarios with Dynamic Provider Alias in Conditional Resource Creation

šŸ‘€ Views: 65 šŸ’¬ Answers: 1 šŸ“… Created: 2025-08-24
terraform aws dynamic-provider HCL

I need help solving I've hit a wall trying to I'm working on a project and hit a roadblock... This might be a silly question, but I'm working with an scenario with using dynamic provider aliases in Terraform 1.4.3 when trying to conditionally create resources based on a variable... I have two AWS accounts set up with different provider configurations, and I want to toggle between them using a variable. My setup includes the following provider configurations: ```hcl provider "aws" { region = "us-east-1" alias = "account_a" } provider "aws" { region = "us-west-2" alias = "account_b" } ``` Then I have a variable defined to toggle between the two accounts: ```hcl variable "use_account_a" { type = bool default = true } ``` Next, I try to conditionally create an S3 bucket based on this variable: ```hcl resource "aws_s3_bucket" "my_bucket" { count = var.use_account_a ? 1 : 0 provider = var.use_account_a ? aws.account_a : aws.account_b bucket = "my-bucket-${count.index}" acl = "private" } ``` However, when I run `terraform apply`, I get the following behavior: ``` behavior: Invalid function argument on main.tf line 8, in resource "aws_s3_bucket" "my_bucket": 8: provider = var.use_account_a ? aws.account_a : aws.account_b Invalid value for "provider" argument: provider "aws.account_a" is not a valid reference. ``` I've tried using `for_each` instead of `count`, but it leads to similar errors related to provider reference. Can someone guide to understand how to properly reference the provider based on a variable in this conditional setup? I've also checked that both providers are properly defined, and I’m unsure why this is happening. Any guidance would be greatly appreciated! My development environment is Linux. Any help would be greatly appreciated! For context: I'm using Hcl on Windows. Is there a better approach? Thanks for taking the time to read this! Could someone point me to the right documentation?