我想使用 Terraform 获取订阅中的所有资源组。 其目标是遍历这些资源组中的存储帐户并基于这些存储帐户创建资源。
我尝试了以下操作,但资源组列表始终为空:
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"]
}
我还添加了一个输出来检查结果,这就是它所显示的:
+ 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"
}
编辑:请注意,获取资源组后,我将在 for 循环中过滤它们,以便仅包含某些资源组,但资源组可能不存在,这就是为什么需要首先获取它们。
我尝试在空资源中使用 cli 命令获取 Terraform 中的资源组列表。我能够成功配置资源。
我尝试使用您共享的模块,不幸的是它不起作用。因此,我尝试使用 CLI 命令来帮助列出资源组并将它们放置在 terraform 的空资源中,我可以在其中列出资源组。
我的地形配置:
provider "azurerm" {
features {}
}
resource "null_resource" "resource_groups_list" {
triggers = {
always_run = "${timestamp()}"
}
provisioner "local-exec" {
command = <<-EOT
az group list --query '[].name'--output json > resource_groups.json
EOT
}
}
输出:
命令
Terrafrom Plan
命令
Terraform Apply
此命令将创建一个
json
,其中包含与订阅中可用资源组相关的所有信息。
现在运行命令
cat resource_groups.json
这将列出订阅中的可用资源组。