CodexBloom - Programming Q&A Platform

Terraform - how to to Dynamically Reference Module Outputs Based on Conditional Logic

👀 Views: 49 💬 Answers: 1 📅 Created: 2025-06-15
terraform modules outputs HCL

I'm integrating two systems and I'm collaborating on a project where I've searched everywhere and can't find a clear answer... I'm running into an scenario where I'm trying to reference outputs from a Terraform module conditionally, based on an input variable. I have a module that creates either an RDS instance or a DynamoDB table based on a user input variable (`db_type`). Depending on this variable, I want to output either the RDS endpoint or the DynamoDB table name, but I keep getting the behavior that the output is not defined. Here's the relevant part of my Terraform code: ```hcl variable "db_type" { description = "Type of database to create" type = string default = "rds" } module "database" { source = "./modules/database" db_type = var.db_type } output "db_endpoint" { value = var.db_type == "rds" ? module.database.rds_endpoint : module.database.dynamodb_table_name } ``` In the module `database`, I have defined outputs like this: ```hcl output "rds_endpoint" { value = aws_db_instance.my_rds.endpoint } output "dynamodb_table_name" { value = aws_dynamodb_table.my_table.name } ``` When I run `terraform apply`, I receive the following behavior: ``` behavior: Invalid reference on main.tf line 8, in output "db_endpoint": 8: value = var.db_type == "rds" ? module.database.rds_endpoint : module.database.dynamodb_table_name References to outputs must be known after apply. You can only use them in other outputs if they are defined for all cases. ``` I’ve checked the module outputs, and it seems fine. I’ve also tried separating the outputs into different outputs based on the condition and aggregating them later, but that’s not really clean. I’d like to know if there’s a best practice for conditionally selecting outputs from a module in Terraform, especially if the outputs are dynamically generated based on the input variables. Any guidance would be appreciated! This issue appeared after updating to Hcl stable. Thanks for taking the time to read this! Am I approaching this the right way?