Terraform 将地图作为变量传递给模块

问题描述 投票:0回答:1

这可能是一个非常愚蠢的问题。我有一个想法,但它对我不起作用。我只是想问问社区里有没有人做过这样的事情?

这是我强调的测试场景

main.tf
variables.tf
env.tfvars
  |
  |__resource.tf
  |__variables.tf 

这两个变量.tf 都定义了一个对象映射:

variable "storageAccount" {
  type = map(
    object({
      name       = string
      CreatedBy  = string
    })
  )
  default = {
    "storageAccount" = {
       name      = ""
       CreatedBy = ""
    }
  }
}

resource.tf 正在迭代变量中的映射以创建多个资源。示例:

resource "azurerm_storage_account" "storageAccount" {
  for_each  = var.storageAccount
  name      = each.value.name
  CreatedBy = each.value.CreatedBy
}

main.tf 有模块调用,例如:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>3.0"
    }
  }
}

provider "azurerm" {
  features {
    key_vault {
      recover_soft_deleted_secrets = false
    }
  }
  skip_provider_registration = true
}

module "storageAccount" {
  source         = "./modules"
  storageAccount = var.storageAccount
}

我相信我正在尝试在 tfvars 中发送整个地图,其中可能会定义地图中的 2 个资源配置,然后让资源块对其进行迭代。这是一个有效的工作流程,因为在我的例子中,resource.tf 似乎只是获取空值或空白,并抛出值不能为空白或空值或与正则表达式不匹配等错误。

azure terraform azure-blob-storage terraform-provider-azure
1个回答
0
投票

将地图作为 terraform 中的变量传递给模块。

您提供的目录结构将无法有效工作,因为根目录和子目录级别都有重复的

variables.tf
文件,这可能会因变量重新定义而导致混乱或错误。此外,正确组织
env.tfvars
文件需要在 Terraform 操作期间显式引用它,因为除非命名为
terraform.tfvars
,否则它不会自动加载。模块和变量文件的正确结构对于 Terraform 项目的清晰度和功能至关重要。

  • 确保
    default
    中的
    variables.tf
    值与类型声明匹配。默认情况下它应该是一个地图,而不是包含地图的对象。
  • resource.tf
    中迭代映射时,验证映射是否正确地从
    env.tfvars
    通过
    main.tf
    传递到模块至关重要。确保模块已正确设置为接收和使用传递的变量。

我更新的地形代码:

main.tf:

provider "azurerm" {
  features {}
}

variable "storageAccount" {
  type = map(object({
    name      = string
    CreatedBy = string
  }))
  default = {}
}

module "storageAccount" {
  source          = "./modules"
  storageAccount  = var.storageAccount
}

terra.tfvars:

storageAccount = {
  "account1" = {
    name      = "adminvkstorage1"
    CreatedBy = "admin"
  },
  "account2" = {
    name      = "adminvkstorage2"
    CreatedBy = "admin"
  }
}

模块/资源.tf:

variable "storageAccount" {
  type = map(object({
    name      = string
    CreatedBy = string
  }))
}


resource "azurerm_resource_group" "rg" {
  name     = "testvk-rg"
  location = "East US2"
}

resource "azurerm_storage_account" "storageAccount" {
  for_each                 = var.storageAccount
  name                     = each.value.name
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"  
  account_replication_type = "GRS"       

  tags = {
    CreatedBy = each.value.CreatedBy
  }
}

现在运行命令

terraform apply -var-file="terra.tfvars"

部署成功:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.