I want to get all resource groups in the subscription using Terraform.
The goal of it is to go through the storage accounts in these resource groups and create resources based on those storage accounts.
I’ve tried the following things but the list of resource groups is always empty:
data "azurerm_resources" "resource_groups" {
type = "Microsoft.Resources/resourceGroups"
}
data "azapi_resource_list" "all_resource_groups" {
// Get version from here: https://learn.microsoft.com/en-us/azure/templates/microsoft.resources/resourcegroups?pivots=deployment-language-bicep#resource-format
type = "Microsoft.Resources/resourceGroups@2022-09-01"
parent_id = "/subscriptions/${data.azurerm_client_config.current.subscription_id}"
response_export_values = ["name"]
}
I also added an output to check the result and this is what it shows:
+ all_resource_groups = {
+ id = "/subscriptions/<redacted>/resourceGroups"
+ output = jsonencode({})
+ parent_id = "/subscriptions/<redacted>"
+ response_export_values = [
+ "name",
]
+ timeouts = null
+ type = "Microsoft.Resources/resourceGroups@2022-09-01"
}
EDIT: Note that after getting the resource groups I’m going to filter them in a for loop so that only certain resource groups are included but the resource groups may not exist which is why it is necessary to fetch them first.
2
Answers
I tried to use the module that you shared unfortunately that doesn’t work. So I tried using the CLI commands which helped list out the resource group and place them in a null resource of terraform where I could list out resource group.
My terraform configuration:
Output:
command
Terrafrom Plan
Command
Terraform Apply
This command will create a
json
with all the info related to resource groups available in the subscription.Now run the command
cat resource_groups.json
This will list out the available resource groups in the subscription.
Have you tried adding the parent (the subscription)? I managed to fetch a list of Azure Container Apps using the resource, then parsing the output and creating new resources based on the exported attributes.