In azure, using terraform and the azurerm provider, I want to check whether a resource group with a given name already exists.
In a perfect world there’d be something like an azurerm_resource_groups block that took a name pattern and returned all matching resource groups in a list, but that doesn’t exist. The azurerm_resource_group data block will fail if the provided name doesn’t exist. And as far as I can tell from testing it, the azurerm_resources block doesn’t seem to find resource groups.
What I want to be able to do is to say "if this resource group exists, put some other resources you’re about to create in it, but if it doesn’t exist, create it first"
I just can’t find a way – shorting of requiring a variable to tell me whether it exists or not – to differentiate between the cases.
I’ve tried
data "azurerm_resources" "resource_group" {
name = var.resource_group_name
}
output "rg_list" {
value = data.azurerm_resources.resource_group
}
but I got back an empty block:
rg_list = {
"id" = "resource-8c79a1bd-fcb4-423b-9327-d62f3274210d"
"name" = "my-rg-name"
"required_tags" = tomap(null) /* of string */
"resource_group_name" = tostring(null)
"resources" = tolist([])
"timeouts" = null /* object */
"type" = tostring(null)
}
2
Answers
You can use the
data
block forazurerm_resource_group
to check if a resource group with a given name is already existed.After a workaround on this, I used the
locals
block to check whether the resource group exists based on the length ofdata.azurerm_resource_group.existed_rg
as follows.Deployed the above code by giving the existing resource name and the output is shown as below.
After that, I tested the same code by passing the new resource group name and was able to create it successfully.
You can use aztfexport A tool to bring your existing Azure resources under the management of Terraform.
Source: https://github.com/Azure/aztfexport
You can install the last release on any OS
Source: https://github.com/Azure/aztfexport/releases/tag/v0.12.0
Usage
At its most abstract, Azure Export is called as follows:
The scope changes depending on the command being run, as do the available set of option flags. There are three commands that should be used based on what you are trying to export:
Export a single resource.
Export a resource group.
Export using a query.
More info: https://learn.microsoft.com/en-us/azure/developer/terraform/azure-export-for-terraform/export-terraform-overview
Let me know if this work by accepting the answer.