gpt4 book ai didi

azure - Terraform 依赖于模块

转载 作者:行者123 更新时间:2023-12-03 14:45:54 26 4
gpt4 key购买 nike

我是 terraform 的新手,我在模块结构上创建了自定义 azure 策略。每个策略代表一个自定义模块。我创建的模块之一是为创建的任何新的 azure 资源启用诊断日志。但是,我需要一个存储帐户。 (在启用诊断设置之前,我如何实现“depends_on”?或任何其他方法?我想首先创建存储帐户,然后创建诊断设置模块。在 main.tf (调用所有其他模块的地方)或资源(模块)内部?

感谢您的帮助! :)

下面的代码代表 main.tf 文件:

//calling the create storage account name

module "createstorageaccount" {

source = "./modules/module_create_storage_account"
depends_on = [
"module_enable_diagnostics_logs"
]

}

这代表创建存储帐户模块

resource "azurerm_resource_group" "management" {


name = "management-rg"
location = "West Europe"
}

resource "azurerm_storage_account" "test" {
name = "diagnostics${azurerm_resource_group.management.name}"
resource_group_name = "${azurerm_resource_group.management.name}"
location = "${azurerm_resource_group.management.location}"
account_tier = "Standard"
account_replication_type = "LRS"

tags = {
environment = "diagnostics"
}
}

depends_on = [
"module_enable_diagnostics_logs"
]

最佳答案

在大多数情况下,必要的依赖关系只是由于您的引用而自动发生。如果一个资源的配置直接或间接引用另一个资源,Terraform 会自动推断它们之间的依赖关系,而无需显式 depends_on

这是有效的,因为模块变量和输出也是依赖关系图中的节点:如果子模块资源引用 var.foo 那么它间接依赖于该变量值所依赖的任何内容。

对于自动依赖项检测不足的罕见情况,您仍然可以利用模块变量和输出是依赖项图中的节点这一事实来创建间接显式依赖项,如下所示:

variable "storage_account_depends_on" {
# the value doesn't matter; we're just using this variable
# to propagate dependencies.
type = any
default = []
}

resource "azurerm_storage_account" "test" {
name = "diagnostics${azurerm_resource_group.management.name}"
resource_group_name = "${azurerm_resource_group.management.name}"
location = "${azurerm_resource_group.management.location}"
account_tier = "Standard"
account_replication_type = "LRS"

tags = {
environment = "diagnostics"
}

# This resource depends on whatever the variable
# depends on, indirectly. This is the same
# as using var.storage_account_depends_on in
# an expression above, but for situations where
# we don't actually need the value.
depends_on = [var.storage_account_depends_on]
}

调用此模块时,可以将 storage_account_depends_on 设置为包含要确保在存储帐户之前创建的对象的任何表达式:

module "diagnostic_logs" {
source = "./modules/diagnostic_logs"
}

module "storage_account" {
source = "./modules/storage_account"

storage_account_depends_on = [module.diagnostic_logs.logging]
}

然后在您的 diagnostic_logs 模块中,您可以为 logging 输出配置间接依赖关系,以完成模块之间的依赖关系链接:

output "logging" {
# Again, the value is not important because we're just
# using this for its dependencies.
value = {}

# Anything that refers to this output must wait until
# the actions for azurerm_monitor_diagnostic_setting.example
# to have completed first.
depends_on = [azurerm_monitor_diagnostic_setting.example]
}

如果您的关系可以通过传递实际来表达,例如通过包含 id 的输出,我建议您首选该方法,因为它会导致更容易配置跟随。但在极少数情况下,资源之间存在无法建模为数据流的关系,您也可以使用输出和变量来传播模块之间的显式依赖关系。

关于azure - Terraform 依赖于模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com