I am currently modularizing my Infrastructure as Code (IaC) but I keep hitting a "Reference to undeclared resource" error. It happens when I try to output a value from one resource to another. I have checked the spelling multiple times, but Terraform insists the resource doesn't exist in the current scope. Is this a mapping issue between modules, or am I missing a dependency declaration in my main configuration file?
3 answers
The "Reference to undeclared resource" error typically occurs when you attempt to access a resource attribute that hasn't been defined in the current block's scope. In Terraform, resources defined inside a module are not automatically visible to the root configuration. To fix this, you must explicitly define an output block inside the child module to export the desired attribute. Then, in your root module, you reference it using module.<module_name>.<output_name>. Also, ensure you aren't referencing a resource using its type name instead of its specific local name. For instance, use aws_instance.web.id instead of just aws_instance.id.
Have you checked if the resource you are referencing is inside a conditional block using count or for_each, and are you using the correct index notation in your reference? If a resource is created with count = 1, you cannot reference it as aws_instance.example.id; you must use aws_instance.example[0].id, otherwise Terraform will treat the base name as an undeclared single resource.
Most of the time, this is just a simple typo or a case of the resource being defined in a different .tf file that isn't being loaded. Make sure all your files are in the same directory!
I agree with Linda. I once spent an hour debugging this only to realize I named my resource aws_s3_bucket.data_logs but tried to reference it as aws_s3_bucket.datalogs. A single underscore can break the entire plan!
Christopher, that index issue is exactly what caught me off guard last week. When using dynamic resource creation, the reference syntax changes completely. If you are using for_each, you actually have to reference the specific key, like aws_instance.example["web_server"].id. If you forget the key or the index, Terraform assumes you are looking for a static resource that simply isn't in the state file yet, triggering that frustrating undeclared error.