amazon-web-servicesamazon-cloudwatchterraform

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?


Solution

  • 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.