8
votes

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!

1
This is basically the exact same question (just more localised to yourself) as the one you already asked and accepted the answer for. What is supposedly different here? - ydaetskcoR
I am new to terraform,the one previously asked is like for using inventory of one terraform script in another terraform script.Here i asked only for one terraform script with different modules in it and accessing of local variables of one module in another in same terraform script - rocky

1 Answers

21
votes

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.