Terraform output variables to be used as input variables

SiddhiMorajkar picture SiddhiMorajkar · Mar 30, 2020 · Viewed 9.5k times · Source

I want to use output variables of one resource/module as an input to another resource/modules. Is that possible? Here i want the output value from 'outputs.tf' in root to be used as input in 'main.tf' of module.

    root
    |--main.tf
    |--vars.tf
    |--outputs.tf
    |---module
         |--main.tf
         |--vars.tf

Answer

Charles Xu picture Charles Xu · Mar 31, 2020

Of course you can. And there is nothing more you need to do. Just do it as usual. Here is an example:

main.tf
├── rg
│   ├── output.tf
│   └── rg.tf
└── vnet
    ├── output.tf
    └── vnet.tf

You create the modules rg and vnet as it does. Set the output you need. Here I set the output rg_name and rg_location. And I also set the variables rg_name and rg_location in the module vnet as need. Then the main.rf shows here:

provider "azurerm" {
  features {}
}

module "rg" {
  source = "./rg"

  rg_name = "charlesTerraform"
}

module "vnet" {
  source = "./vnet"

  rg_name = module.rg.rg_name
  rg_location = module.rg.rg_location
}

output "vnet" {
  value = module.vnet.vnet
}

You see, I use the output of the module rg as input for the module vnet. Hope it help you understand the Terraform modules.

Update:

It's also the same way when the structure is the thing you said. You just need to input the output you need into the module. For example:

resource "azurerm_resource_group" "example" {
  name = "xxxxxx"
  location = "xxxx"
}

module "vnet" {
  source = "./modules"

  resource_group = azurerm_resource_group.example.name
}

This is just an example, but it shows you how to achieve it. Hope you understand.