Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using one module local variable in another module in terraform

I am trying to access one module variable in another new module to get aws instance ids which are created in that module and use them in a module Cloud watch alerts which creates alarm in those instance ids . The structure is something like the below

**Amodule #here this is used for creating kafka aws instances*

     main.tf
     kafkainstancevariables.tf

Bmodule #here this is used for creating alarms in those kafka instances

     main.tf
     cloudwatchalertsforkafkainstancesVariables.tf

Outside modules terraform mainfile from where all modules are called main.tf variables.tf***

How to access the variables created in Amodule in Bmodule?

Thank you!

like image 216
rocky Avatar asked Dec 08 '16 14:12

rocky


1 Answers

You can use outputs to accomplish this. In your kafka module, you could define an output that looks something like this:

output "instance_ids" {
  value = ["${aws_instance.kafka.*.id}"]
}

In another terraform file, let's assume you instantiated the module with something like:

module "kafka" {
  source = "./modules/kafka"
}

You can then access that output as follows:

instances = ["${module.kafka.instance_ids}"]

If your modules are isolated from each other (i.e. your cloudwatch module doesn't instantiate your kafka module), you can pass the outputs as variables between modules:

module "kafka" {
  source = "./modules/kafka"
}

module "cloudwatch" {
  source = "./modules/cloudwatch"
  instances = ["${module.kafka.instance_ids}"]
}

Of course, your "cloudwatch" module would have to declare the instances variable.

See https://www.terraform.io/docs/modules/usage.html#outputs for more information on using outputs in modules.

like image 164
Ryan E Avatar answered Oct 21 '22 07:10

Ryan E