[英]How to use depends_on in terraform if resources are created using count or for_each
你好如何在count或for_each的情況下使用depends_on。
depends_on 的基本語法假定
resource "azurerm_storage_container" "cont1"{
.....
.....
depends_on = [
azurerm_storage_account.storageAccount
]
}
resource "azurerm_storage_account" "storageAccount" {
count = 3
name = "storageAccountName-${count.index}"
resource_group_name = "rg-demo"
location = "centralus"
account_tier = "Standard"
account_replication_type= "LRS"
# all other relevant attributes
}
所以在這里它的 azurerm_storage_account.storageAccount 如果只創建一個這樣的資源,但是如果我們有許多 azurerm_storage_account 創建為 for_each 或在其中使用了計數那么寫什么來代替 storageAccount? 假設我們必須在容器上有 storageAccountName-2 的依賴項,那么我們將如何編寫依賴項?
正如上面評論中提到的,您可以向 storageAccount 資源引用添加索引:
resource "azurerm_storage_account" "test_storage_account" {
count = 3
name = "teststorageaccount${count.index}"
...
}
resource "azurerm_storage_container" "container" {
depends_on = [
azurerm_storage_account.test_storage_account[0]
]
name = "testcontainer"
...
}
您還可以省略索引並讓容器依賴於整個存儲帳戶資源。 兩者都在我的測試中起作用。
此外,雖然隱式依賴通常允許您在容器資源中沒有“depends_on”塊(如果您有一個存儲帳戶),但當您有多個使用“for_each”創建的存儲帳戶時,隱式依賴似乎不起作用" 稍后在存儲容器資源中引用。
Terraform 中的依賴關系僅存在於靜態塊之間,而不存在於這些塊聲明的各個實例之間。 這是因為count
和for_each
表達式本身可以具有依賴關系,因此 Terraform 必須在計算每個資源或模塊將存在哪些實例之前構建依賴關系圖。
因此,對資源使用count
和for_each
不會改變您為資源創建依賴項的方式。
與往常一樣,創建依賴項的最常見方法是僅在另一個資源的至少一個參數中引用該資源。 這會自動創建依賴關系,因此您根本不需要depends_on
:
resource "azurerm_storage_account" "example" {
count = 3
# ...
}
resource "azurerm_storage_container" "example" {
# the azurerm_storage_account.example part of the following
# expression creates a dependency, regardless of what
# else this expression does.
count = length(azurerm_storage_account.example)
# ...
}
depends_on
參數僅在遠程 API 設計導致存在 Terraform 無法通過注意您的引用自動發現的“隱藏依賴項”的情況下才需要。
對於您在此處顯示的資源類型,一種可能適用的方法是,如果您正在編寫一個聲明這兩種資源的共享模塊,然后將存儲帳戶 ID 導出為輸出值。 在這種情況下,您可能希望告訴 Terraform 輸出值還取決於存儲容器,這表示在創建存儲容器之前存儲帳戶實際上尚未准備好使用:
output "storage_account_ids" {
value = toset(azurerm_storage_account.example[*].id)
# The storage accounts are not ready to use
# until their containers are also ready.
depends_on = [azurerm_storage_container.example]
}
請注意depends_on
僅指azurerm_storage_container.example
,因為 Terraform 僅跟蹤對整個資源的依賴性。
盡管在此處寫入實例 ID 在語法上是有效的——例如,您可以聲明對azurerm_storage_container.example[0]
的依賴關系,Terraform 會接受它——Terraform 只會忽略[0]
部分並創建對無論如何,整個資源。 [0]
后綴對 Terraform 的行為完全沒有影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.