Using Data Sources for Resource Reference with Terraform

Scenario:

You have infrastructure already deployed in the cloud and for a variety of reasons (comfort level, scope of responsibilities, etc.) are not keen on importing everything and managing it through Terraform. At the same time, you'd still like to leverage IaC through Terraform to provision some infra.

For example, you have a resource group called "rg-pre-existing" and you don't care to import it in Terraform but would like to use code to provision infrastructure into that resource group. 

For such use cases you can use a data source - basically something that Terraform needs to know about but not manage, that can be referenced.

Now that you have it, how do you reference it in the rest of your code...

Each resource and data source has attributes that it outputs. You can find the attributes in the Terraform resource reference. In the example above, azurerm_resource_group has 4:

  • location
  • name 
  • id
  • tags

You can reference the data source and respective attribute this way:

  location            = data.azurerm_resource_group.rg-pre-existing.location

  resource_group_name = data.azurerm_resource_group.rg-pre-existing.name

Terraform plan and apply just read the data source block and terraform destroy doesn't touch it either. 

Here are the resources provisioned in the resource group:

After issuing terraform destroy, the rg-pre-existing resource group will remain as is, with terraform only cleaning up the resources it provisioned earlier. 

 

Related posts