When infrastructure is provisioned with Terraform, it is sometimes necessary to retrieve information about the already existing resources. Indeed, when deploying resources to a certain infrastructure, there is often a need to place ourselves in an existing infrastructure or link it to other resources that have already been provisioned.
In this recipe, we will learn how, in our Terraform configuration, to retrieve information about resources already present in an infrastructure.
Getting ready
For this recipe, we will use an existing Terraform configuration that provides an Azure App Service in the Azure cloud. This source code is available at https://github.com/PacktPublishing/Terraform-Cookbook/tree/master/CHAP02/data.
This code is incomplete because, for this project, we need to store the App Service in an existing Service Plan. This Service Plan is the one we will use for the entire App Service.
How to do it…
Perform the following steps:
- In our file that contains our Terraform configuration, add the following data block:
data "azurerm_app_service_plan" "myplan" {
name = "app-service-plan"
resource_group_name = "rg-service_plan"
}
In the properties sections, specify the name and the Resource Group of the Service Plan to be used.
- Then, complete the existing App Service configuration, as follows:
resource "azurerm_app_service" "app" {
name = "${var.app_name}-${var.environement}"
location = azurerm_resource_group.rg-app.location
resource_group_name = azurerm_resource_group.rg-app.name
app_service_plan_id = data.azurerm_app_service_plan.myplan.id
}
How it works…
In step 1, a data block is added to query existing resources. In this data block, we specify the Resource Group and the name of the existing Service Plan.
In step 2, we use the ID of the Service Plan that was retrieved by the data block we added in step 1.
The result of executing this Terraform configuration can be seen in the following screenshot:
As we can see, we have the ID of the Service Plan that was retrieved by the data block.
There's more…
What's interesting about the use of data blocks is that when executing the terraform destroy command on our Terraform configuration, Terraform does not perform a destroy action on the resource called by the data block.
Moreover, the use of data blocks is to be preferred to the use of IDs written in clear text in the code, which can change because the data block recovers the information dynamically.
Finally, the data block is also called when executing the terraform plan command, so your external resource must be present before you execute the terraform plan and terraform apply commands.
If this external resource is not already present, we get the following error in the terraform plan command:
See also
For more information about data blocks, take a look at the following documentation: https://www.terraform.io/docs/configuration/data-sources.html