terraform get: can't use variable in module source parameter?
Problem
I'm trying to avoid hard-coding module sources; the simplest approach would be: [code block] The result I get while attempting to run `terraform get -update` is [code block]
Error Output
Error loading Terraform: Error downloading modules: error downloading module 'file:///home/thisisme/terraform-env/${var.foo_module_source}': source path error: stat /home/thisisme/terraform-env/${var.foo_moUnverified for your environment
Select your OS to check compatibility.
1 Fix
Use Terraform locals for dynamic module source paths
Terraform does not support variable interpolation in module source paths directly. When you attempt to use a variable in the source parameter, Terraform tries to resolve it as a literal path, leading to errors when it cannot find the specified path.
Awaiting Verification
Be the first to verify this fix
- 1
Define a local variable for the module source
Create a local variable in your Terraform configuration that constructs the module source path using the variable you want to use. This allows you to dynamically set the source without hard-coding it.
hcllocals { foo_module_source = "${var.foo_module_source}" } - 2
Reference the local variable in the module block
Update your module block to use the local variable instead of the original variable directly. This ensures that Terraform can correctly resolve the path when it processes the module.
hclmodule "example" { source = local.foo_module_source } - 3
Run Terraform commands to apply changes
After making the changes, run the Terraform commands to ensure that the configuration is applied correctly. Start by initializing the configuration and then apply it.
bashterraform init terraform apply - 4
Verify module loading
Check the output of the Terraform commands to confirm that the module loads without errors. Ensure that the module is correctly sourced from the specified path.
bashterraform get -update
Validation
Confirm that the module loads successfully without any errors related to the source path. You can also check the Terraform state to ensure the module is correctly initialized.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep