仅当 Azure 中不存在时,如何通过 Terraform 创建 azurerm_resourcegroup?
How to create azurerm_resourcegroup through terraform only when it does not exist in Azure?
我希望我的 Terraform 脚本仅在 Azure 中不存在资源组时创建资源组,否则它应该跳过资源组的创建。
Terraform 是声明性的,而不是命令性的。使用 Terraform 时,您不需要检查现有资源
验证您的 tf 脚本
terraform plan
并应用 tf 脚本更改
terraform apply
这将验证资源是否已经存在,如果不存在则创建
那么,您可以使用Terraform external执行CLI命令来检查资源组是否存在。然后根据结果判断资源组是否创建。这是一个例子:
./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}'
我希望我的 Terraform 脚本仅在 Azure 中不存在资源组时创建资源组,否则它应该跳过资源组的创建。
Terraform 是声明性的,而不是命令性的。使用 Terraform 时,您不需要检查现有资源
验证您的 tf 脚本
terraform plan
并应用 tf 脚本更改
terraform apply
这将验证资源是否已经存在,如果不存在则创建
那么,您可以使用Terraform external执行CLI命令来检查资源组是否存在。然后根据结果判断资源组是否创建。这是一个例子:
./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}'