0
votes

Environment folder setup:

  • Module A contains rg.tf file to create resource group on azure.
  • Module B contains vnet.tf file and it needs resource group name from Module A.

How do i use the output of one into another ?

Terraform -v = Terraform v0.12.6

Folder Struture :

C:\Terraform\ResourceGroup
   \rg.tf 
   \var.tf
   \output.tf
C:\Terraform\Vnet
    \vnet.tf 

rg.tf contains:

provider "azurerm" { 
  Subscription ID : xxxxxxxxxxxxxx
  Subscription Name :xxxxxxxxxxxxx
  Client ID : xxxxxxxxxxxxxxxxx
  Client Secret: xxxxxxxxxxxx
}
terraform {
  backend "azurerm" {
    storage_account_name  = xxxxxxxxxxxxx
    resource_group_name   = xxxxxxxxxxxxx
    container_name        = "versiontf"
    key                   = "terraform.tfstate"
  }
}
resource "azurerm_resource_group" "res_group" {
  location = "${var.location}"
  name     = "${var.name}"
}

var.tf contains

variable "location" {
  default     = "West US"
}

variable "name" {
  default = "testing"
}

output.tf contains:

output "rg_name" {
  value = "${azurerm_resource_group.res_group.name}"
}

vnet.tf contains:

provider "azurerm" { 
  Subscription ID : xxxxxxxxxxxxxx
  Subscription Name :xxxxxxxxxxxxx
  Client ID : xxxxxxxxxxxxxxxxx
  Client Secret: xxxxxxxxxxxx
}

resource "azurerm_virtual_network" "test" {
  name                = "vnet"
  location            = "east us"
  resource_group_name = "????????????"  (How do i read the resource group name which i created using rg.tf)
  address_space       = ["10.0.0.0/16"]
}

FYI: I am able to create and add output values to the backend state file.

1
Can you share your Terraform code? Also include the directory layout of things if they are in separate files.ydaetskcoR
@ydaetskcoR i have added the folder structure and the entire code. Thank you.mikeknows
I tried the below code but it shows following error i posted. I tried changing the name and location and playing around it also. Able to create the RG but while creating vnet the erros is thrown.mikeknows
Can you show the message of the error? It works well on my side.Charles Xu
on ..\rg\main.tf line 8, in resource "azurerm_resource_group" "rgtest": 8: resource "azurerm_resource_group" "rgtest" {mikeknows

1 Answers

0
votes

You just need to use the module in the file vnet.tf like below:

provider "azurerm" { 
    Subscription ID : xxxxxxxxxxxxxx
    Subscription Name :xxxxxxxxxxxxx
    Client ID : xxxxxxxxxxxxxxxxx
    Client Secret: xxxxxxxxxxxx
}

module "resourceGroup" {
  source = "../ResourceGroup"

  # the variable that you set for your resource group
  name = "rg_name"
  location = "rg_location"

}

resource "azurerm_virtual_network" "test" {
    name                = "vnet"
    location            = "east us"

    # use the module resource group
    resource_group_name = "${module.resourceGroup.rg_name}"     

    address_space       = ["10.0.0.0/16"]
}