azureterraform

Check if the resource exists before using data


I want to check if the resource exists before I run below code. I also want to use output of this code further in the code.

data "azurerm_api_management" "res-data" {
  name                = "res_name"
  resource_group_name = "rg_name"
}

resource "azurerm_api_management" "apim" {
  name                = "res_name"
  location            = var.location
  resource_group_name = "rg_name"
  publisher_email     = data.azurerm_api_management.res-data.publisher_email
  }

Solution

  • Check if the resource exists before using data module in terraform

    There is no in-build feature in terraform to check the existence of resource before using data module in terraform.

    In general, data module is used for the resource which is preexisted if the resource doesn't exists this will through an error. Since the requirement is to check the existence of resource in portal before running the data module, we need external script support using cli to achieve this requirement.

    Configuration:

    variable "apim_name" {
      type        = string
      description = "The name of the API Management resource"
      default     = ""
    }
    
    resource "null_resource" "check_apim_existence" {
      provisioner "local-exec" {
        command = <<EOT
          apim_exists=$(az apim show --name ${var.apim_name} --resource-group vinay-rg --query "name" -o tsv)
          if [ -n "$apim_exists" ]; then
            echo "APIM exists: $apim_exists"
          else
            echo "APIM does not exist"
            exit 1
          fi
        EOT
        interpreter = ["bash", "-c"]
      }
    
      triggers = {
        always_run = "${timestamp()}"
      }
    }
    
    data "azurerm_api_management" "res_data" {
      depends_on          = [null_resource.check_apim_existence]  
      name                = var.apim_name
      resource_group_name = "vinay-rg"
    }
    
    output "apim_name" {
      value = data.azurerm_api_management.res_data.name
      description = "The name of the API Management resource"
    }
    

    Deployment:

    enter image description here

    with this script we can make sure the existence of resource name mentioned under our RG.

    If the resource doesn't exist it will through the error at null resource level mentioning the same as we use depends on in data module.

    enter image description here

    Refer:

    azurerm_api_management | Data Sources | hashicorp/azurerm | Terraform | Terraform Registry

    https://learn.microsoft.com/en-us/cli/azure/apim?view=azure-cli-latest#az-apim-show