I am trying to retrieve OCI instance OCIDs but hitting "A managed resource X Y has not been declared"

Hi guys, resubmitting this question in a better formatted way in the hope that someone can assist.

I am trying to reference node_ocids (OCI instance OCIDs) in locals.tf but hitting the following during validation.

│ Error: Reference to undeclared resource
│
│   on modules/B/locals.tf line 3, in locals:
│    3:   node_ocids  = oci_core_instance.instance.id
│
│ A managed resource "oci_core_instance" "instance" has not been declared in module.B.

From modules/A/main:

resource "oci_core_instance" "instance" {
  count               = var.instance_count
  availability_domain = var.availability_domain_id
  compartment_id      = var.compartment_id
  display_name        = format("${var.prefix}-%03d", count.index + 1)
  shape               = var.instance_shape

  connection {
    agent               = false
    timeout             = "10m"
    host                = self.private_ip
    user                = "user"
    private_key         = file(var.ssh_private_key_path)
  }
......
......

From modules/B/locals.tf:

locals {
  agent_nodes = distinct(concat(var.server_nodes, var.worker_nodes))
  node_ocids  = oci_core_instance.instance.id

  setup = templatefile("${path.module}/files/setup.sh", {
    node_ocids            = local.node_ocids
    agent_nodes           = local.agent_nodes
    })}

This is happening because the resource is declared in another module. You can’t refer to resources in other modules. To pass information between modules (such as this instance’s ID) you can use input variables. I’m not sure exactly what to recommend here, as it depends on how your two modules are called in context.

See the Terraform Modules guide for more guidance on how to use modules.

Sorted as follows (somewhat obfuscated).

From modules/A/outputs.tf

......
output "node_ocids" {
  value      = oci_core_instance.instance.*.id
}
......

From modules/B/locals.tf

locals {
  agent_nodes = distinct(concat(var.server_nodes, var.worker_nodes))

  setup = templatefile("${path.module}/files/setup.sh", {
    node_ocids            = var.node_ocids
    agent_nodes           = local.agent_nodes
    })}

From main.tf

module "A" {
......
......
}

module "B" {
  source     = "./modules/B"
......
node_ocids                = module.A.node_ocids
......