Terraform: Reference Current Infra
Description:
Many times we will need to reference current resources and then pass other information to build on them. For example, adding a Virtual Machine to an already existing Resource Group. I’m not sure how to modify
these resources just yet, that will have to be a different post.
To Resolve:
-
To get the resource ID of the current subscription:
1 2 3 4 5 6 7 8 9
data "azurerm_subscription" "current" {} output "sub_name" { value = data.azurerm_subscription.current.id } output "tenant_name" { value = data.azurerm_subscription.current.tenant_id }
- Output:
1 2
sub_name = "/subscriptions/subscription-id-guid" tenant_name = "tenant-id-guid"
-
You can do this for any existing resource. For example:
1 2 3 4 5 6 7 8 9 10
data "azurerm_virtual_network" "vnet" { name = var.vnet_name resource_group_name = var.rg } data "azurerm_subnet" "my_subnet" { resource_group_name = var.rg virtual_network_name = data.azurerm_virtual_network.vnet.name name = var.subnet_name }
- You can reference them by syntax:
data.$ARM_Resource_Name.$Alias.output
whereARM_Resource_Name
matches the resource in Azure Docs and$alias
is whatever label you give the resource.
- You can reference them by syntax:
-
You can check outputs by going to their AzureRM (ARM) documents at AzureRM Docs
-
For example, I see Virtual Network has many attributes exported such as
id
,name
,resource_group_name
, and more. -
This means that later in my code I can reference like:
data.azurerm_virtual_network.vnet.resource_group_name
for example ordata.azurerm_virtual_network.vnet.name
-
Comments