How to check if resource exists or not in terraform using AzApi

Babula ParidaBabula Parida
2 min read

Data Sources

Data sources allow Terraform to use the information defined outside of Terraform, defined by another separate Terraform configuration, or modified by functions.

Data Source - Terraform

Problem

Data sources are a great way to find details about existing resources and use them to manage our code dependencies. Data sources work great when the resource we want to identify exists however when the resource we are trying to query not exists, then it gives an error.

To demonstrate the problem, I have created a storage account as shown below

I am getting the details of the storage account using the data source as shown below.

data "azurerm_storage_account" "existing" {
  name = "stgtest1111"
  resource_group_name = "1-60b15f44-playground-sandbox"
}

output "stg" {
  value = data.azurerm_storage_account.existing
}

Let's use the data source to fetch information for a storage account which is not available

data "azurerm_storage_account" "notavailable" {
  name = "stgtest1112"
  resource_group_name = "1-60b15f44-playground-sandbox"
}

output "stg" {
  value = data.azurerm_storage_account.notavailable.id
}


Solution

To find the solution for the above problem, we will use AzApi terraform provider.

The AzAPI provider is a very thin layer on top of the Azure ARM REST APIs. This provider compliments the AzureRM provider by enabling the management of Azure resources that are not yet or may never be supported in the AzureRM provider such as private/public preview services and features.

AzAPI - Microsoft

AzApi - Terraform

As part of this approach, we will create a storage account using Terraform. Before creating the storage account, we will verify if the storage account exists or not. If the storage account exists, we will not create the account.

Code Structure

Code Used for this Activity

Created a new storage account

Trying to recreate the same account


This use case is not specific to the storage account and can be used across all the services in Azure. Please refer to below Microsoft documentation for getting information about different resource types and API.

Microsoft Templates


I hope you enjoyed reading this article, feel free to add your comments, thoughts or feedback and don’t forget to get in touch on LinkedIn

0
Subscribe to my newsletter

Read articles from Babula Parida directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Babula Parida
Babula Parida