Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create azurerm_resourcegroup through terraform only when it does not exist in Azure?

I want my terraform script to create the resource group only when it does not exist in Azure, otherwise it should skip the creation of resource group.

like image 246
paras mehta Avatar asked Dec 30 '25 09:12

paras mehta


1 Answers

Well, you can use Terraform external to execute the CLI command to check if the resource group exists or not. And then use the result to determine whether the resource group will create. Here is an example:

./main.tf

provider "azurerm" {
    features {}
}

variable "group_name" {}

variable "location" {
    default = "East Asia"
}

data "external" "example" {
    program = ["/bin/bash","./script.sh"]

    query = {
        group_name = var.group_name
    }
}

resource "azurerm_resource_group" "example" {
    count = data.external.example.result.exists == "true" ? 0 : 1
    name = var.group_name
    location = var.location
}

./script.sh

#!/bin/bash 

eval "$(jq -r '@sh "GROUP_NAME=\(.group_name)"')"
result=$(az group exists -n $GROUP_NAME)

jq -n --arg exists "$result" '{"exists":$exists}'
like image 84
Charles Xu Avatar answered Jan 01 '26 05:01

Charles Xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!