Dovid Gefen
Dovid Gefen

Reputation: 403

How to get the name of the calling module in Terraform

How can I access the name of the parent/calling module from within its child module.
Alternatively how can I get the filename of the calling module from within its child module?

e.g.

module "test_parent_module" {
    source = "./child_module"
}
module "child_module" {
    locals {
        // What could I use here to get parent module name?
        parent_module_name = module.parent # Should output "test_parent_module"
        // What could I use here to get the parent module's file name?
        parent_file_name = module.parent.filename # Should output "test_parent_module.tf"
    }

}

Thanks

Upvotes: 2

Views: 3655

Answers (1)

valem
valem

Reputation: 1890

You can't. This type of inheritance hierarchy does not work for terraform. I would recommend passing variables instead. (Though it seems like there are other problems in your config if you are relying on the terraform file name so you might want to reexamine your code structures)

module "test_A_module" {} // what you had as parent
module "test_B_module" {
    source = "./child_module"

    module_name = "test_A_module"
    file_name = "test_A_module.tf"
}
module "child_module" {
    locals {
        module_name = var.module_name
        file_name = var.file_name
    }

}

Upvotes: 5

Related Questions