首页 > 解决方案 > 使用模块时无法创建 Terraform 资源组

问题描述

我正在使用模块优化我的 terraform 代码。当我创建一个资源组模块时,它工作得很好,但它创建了两个资源组,即

  1. Temp-AppConfiguration-ResGrp
  2. Temp-AppServices-ResGrp

相反,它应该只创建

Temp-AppConfiguration-ResGrp

代码资源组.tf 。

resource "azurerm_resource_group" "resource" {
  name     = "${var.environment}-${var.name_apptype}-ResGrp"
  location = var.location
  tags = {
    environment = var.environment
  }
}
output "resource_group_name" {
  value = "${var.environment}-${var.name_apptype}-ResGrp"
}

output "resource_group_location" {
  value = var.location
}

变量.tf

variable "name_apptype" {
  type    = string
  default = "AppServices"
}
variable "environment" {
  type    = string
  default = "Temp"
}
variable "location" {
  type    = string
  default = "eastus"
}

主文件

 module "resourcegroup" {
  source = "../Modules"
  name_apptype = "AppConfiguration"
}

我想在调用资源组模块时在 main.tf中传递name_apptype 。这样我就不需要每次都更新 variable.tf 了。

任何我做错的建议。另外我也无法输出该值,我需要它以便我可以在我要创建的下一个模块中传递资源组名称。

谢谢

标签: terraformdevopsterraform-provider-azure

解决方案


你需要在Main.tf

module "resourcegroup" {
  source = "../Modules"
  name_apptype = "AppConfiguration"
}

module "resourcegroup-appservices" {
  source = "../Modules"
  name_apptype = "AppServices"
}

这些使用您需要的值创建了 2 个资源组,此外,您可以从name_apptype变量中删除默认值。

如果要使用相同的模块创建两个资源组,则需要使用 count 来遍历名称数组


推荐阅读