Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing resources among modules

I'm creating a terraform module which is working fine. However, when I use it multiple times it creates multiples roles and policies which are literally the same.

I'm thinking if there is a way for the module to create a role when I call it for the first time and keep using the same role for the subsequent modules

like image 335
DevOpsNRZ Avatar asked Apr 23 '26 06:04

DevOpsNRZ


1 Answers

No, Terraform does not support this. Your best bet is to create the shared resources outside the module (or in a separate module), and then pass them in as input arguments into the module you're creating multiple times.

I like the approach of having a module for "shared" resources, because then you can pass that entire module in as an input argument into any module that uses those shared resources.

EDIT: Sample code for shared modules:

main.tf

module "mod1" {
  source = "./mymodule1"
}

module "mod2" {
  source       = "./mymodule2"
  input_module = module.mod1
}

output "mod2" {
  value = module.mod2
}

mymodule1/main.tf

output "some_field" {
  value = "foo"
}

mymodule2/main.tf

variable "input_module" {}

output "module_that_was_input" {
  value = var.input_module
}

Result:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

mod2 = {
  "module_that_was_input" = {
    "some_field" = "foo"
  }
}
like image 82
Jordan Avatar answered Apr 25 '26 02:04

Jordan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!