13

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!

rocky
  • 137
  • 1
  • 2
  • 6
  • This is basically the exact same question (just more localised to yourself) as the [one you already asked and accepted the answer for](http://stackoverflow.com/q/41003986/2291321). What is supposedly different here? – ydaetskcoR Dec 08 '16 at 17:38
  • 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 Dec 08 '16 at 18:54

1 Answers1

26

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.

Ryan E
  • 1,115
  • 10
  • 11
  • For me, I had a "vpc" module, and a "ec2" module. To get it to work I needed to have the output for the vpc_id that set the value to the ip of the vpc. Then I needed to set the variable for the vpc_id in file that calls the ec2 module, and get the value like this module "ec2" { source = "../modules/ec2" vpc_id = "${module.vpc.vpc_id}" } So, output in the outputs for the vpc module, variable for the ec2 module's variables file, and then actually calling that variable from the file that calls the ec2 module. Phew! – Maximus Sep 14 '22 at 22:55