英文:
Using Conditions on Terraform to deploy resources on Azure
问题
I found the above example, but it does not work.
我找到了上面的示例,但它不起作用。
英文:
I'm currently developing new terraform modules and facing some problems validating existing resources such as resource groups.
Using the ARM template makes it possible to use the option deploy if it does not exist. But I couldn't find a similar solution on Terraform code.
For example, before creating a brand-new resource group. I would like to check if the subscription contains it and if not, create it.
resource "azurerm_resource_group" "mssql_server_resource_group" {
name = var.mssql_resource_group_name
location = "eastus"
# Check if resource group exists before creating
lifecycle {
ignore_changes = [tags] # Ignore tag changes to prevent unnecessary updates
create_before_destroy = true # Create a new resource before destroying the existing one
}
}
I found the above example, but it does not work.
答案1
得分: 1
以下是您要翻译的内容:
要检查资源组是否已存在,您可以尝试下面的代码,这对我有效。
我尝试使用 count
运算符来检查条件,如下所示:
provider "azurerm" {
features {}
}
variable "resource_group" {
type = string
}
data "azurerm_resource_group" "example" {
name = var.resource_group
}
resource "azurerm_resource_group" "example" {
count = length(data.azurerm_resource_group.example) == 0 ? 1 : 0
name = var.resource_group
location = "eastus"
}
运行 terraform init
后:
运行 Terraform plan 后,它会提示您输入 resource group
变量。我使用了现有的变量,输出如下:
为了再次验证,我使用新的资源组名称运行了 terraform plan
,返回了状态 "resource not found"。然后,您可以检查状态并相应地进行操作。
或者,您可以使用以下命令查看 Terraform state
文件,包括 resource ID
。如果资源存在,它将检索以下资源信息。
terraform state show azurerm_resource_group.example
英文:
To check whether the resource group already exists, You can try the below code which worked for me.
I tried with the count
operator to check the condition as follows:
provider "azurerm"{
features{}
}
variable "resource_group"{
type = string
}
data "azurerm_resource_group" "example" {
name = var.resource_group
}
resource "azurerm_resource_group" "example" {
count = length(data.azurerm_resource_group.example) == 0 ? 1 : 0
name = var.resource_group
location = "eastus"
}
terraform init
:
After I run the Terraform plan, it prompts me for the resource group
variable. I used the existing one, and the output is as follows.
To verify again, I ran terraform plan
with the new resource group name, and it returned the status "resource not found"
. You can then check the status and proceed accordingly.
Alternatively, you can use the below command to view the Terraform state
file, including the resource ID
. If the resource exists, it retrieves the following resource information.
terraform state show azurerm_resource_group.example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论