[英]Terraform can't create resource in group already exist
我將使用 Terraform 創建一個示例 azure web 應用程序。我使用此代碼創建資源。
這是我的 main.tf 文件:
resource "azurerm_resource_group" "rg" {
name = var.rgname
location = var.rglocation
}
resource "azurerm_app_service_plan" "plan" {
name = var.webapp_plan_name
location = var.rglocation
resource_group_name = var.rgname
sku {
tier = var.plan_settings["tier"]
size = var.plan_settings["size"]
capacity = var.plan_settings["capacity"]
}
}
resource "azurerm_app_service" "webapp" {
name = var.webapp_name
location = var.rglocation
resource_group_name = var.rgname
app_service_plan_id = azurerm_app_service_plan.plan.id
}
這是 variable.tf
# variables for Resource Group
variable "rgname" {
description = "(Required)Name of the Resource Group"
type = string
default = "example-rg"
}
variable "rglocation" {
description = "Resource Group location like West Europe etc."
type = string
default = "eastus2"
}
# variables for web app plan
variable "webapp_plan_name" {
description = "Name of webapp"
type = string
default = "XXXXXXXXXx"
}
variable "plan_settings" {
type = map(string)
description = "Definition of the dedicated plan to use"
default = {
kind = "Linux"
size = "S1"
capacity = 1
tier = "Standard"
}
}
variable "webapp_name" {
description = "Name of webapp"
type = string
default = "XXXXXXXX"
}
terraform apply --auto-approve
顯示錯誤:
Error: creating/updating App Service Plan "XXXXXXXXXXX" (Resource Group "example-rg"): web.AppServicePlansClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="ResourceGroupNotFound" Message="Resource group 'example-rg' could not be found."
但在 Azure 門戶中,創建了資源組
我的代碼有什么問題?
在傳遞到下一個資源之前,我可以按住 Terraform 檢查資源是否已創建嗎?
您需要引用這些資源來表明它們與 terraform 之間的依賴關系,這樣才能保證先創建資源組,然后再創建其他資源。 該錯誤表明資源組尚不存在。 您的代碼嘗試先創建 ASP,然后再創建 RG。
resource "azurerm_resource_group" "rg" {
name = var.rgname
location = var.rglocation
}
resource "azurerm_app_service_plan" "plan" {
...
resource_group_name = azurerm_resource_group.rg.name
...
}
...但我不能使用變量?
要回答該問題並提供有關當前問題的更多詳細信息,原始代碼中發生的情況是您沒有以 terraform 可用於創建其依賴關系圖的方式引用 terraform 資源。
如果var.rgname
等於<my-rg-name>
並且azurerm_resource_group.rg.name
也等於<my-rg-name>
那么從技術上講,這是一樣的,對吧?
好吧,不,不一定。 它們確實具有相同的值。 不同之處在於第一個只是回應價值。 第二個包含相同的值,但它也是對 terraform 的指令,它說,“嘿,等一下。我們需要azurerm_resource_group.rg
中的名稱值,所以讓我確保先設置它,然后我將提供此資源“
區別很微妙但很重要。 以這種方式使用值可以讓 Terraform 了解它必須首先提供什么,並讓它創建它的依賴關系圖。 單獨使用變量不會。 特別是在大型項目中,始終嘗試使用資源變量值而不是僅輸入變量,這將有助於避免不必要的問題。
使用輸入變量來定義某些初始數據是很常見的,例如您在上面所做的資源組的名稱。 然而,在那之后,每次在清單中引用resource_group_name
時,您應該始終使用 terraform 生成的值,因此resource_group_name = azurerm_resource_group.rg.name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.