首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有可能动态地将用户定义的变量(key = value)传递给terraform模块?

是否有可能动态地将用户定义的变量(key = value)传递给terraform模块?
EN

Stack Overflow用户
提问于 2022-05-21 08:10:53
回答 1查看 248关注 0票数 0

有以下资源:

代码语言:javascript
复制
resource "resource_name" "foo" {
  name        = "test"
  
  config {
    version = 14

    resources {
      disk_type_id       = "network-ssd"
    }

    postgresql_config = {
      enable_parallel_hash              = true
    }
  }
}

我需要一个模块,它接受"postgresql_config“中的可选用户变量。可以有许多这样的变量。

我下一次尝试:

variables.tf

代码语言:javascript
复制
variable "postgresql_config" {
  description = "User defined for postgresql_config"
  type = list(object({
  # key1 = value1
  # ...
  # key50 = value50
  }))
}

variable "config" {
  description = "for dynamic block 'config' "
  type = list(object({
    version                   = number
  }))
  default = [{
    version                   = 14
  }]
}

variable "resources" {
  description = "for dynamic block 'resources' "
  type = list(object({
    disk_type_id       = string
  }))
  default = [{
    disk_type_id       = "network-hdd"
  }]
}

module/postgresql/main.tf

代码语言:javascript
复制
resource "resource_name" "foo" {
  name        = "test"
  
  dynamic "config" {
    for_each = var.config
    content {
      version                   = config.value["version"]

      dynamic "resources" {
        for_each = var.resources
        content {
          disk_type_id       = resources.value["disk_type_id"]
        }
      }
      
      # problem is here
      postgresql_config = {
        for_each = var.postgresql_config
        each.key = each.value
      }

    }
}

example/main.tf

代码语言:javascript
复制
module "postgresql" {
  source = "../module/postgresql"

  postgresql_config = [{
    auto_explain_log_buffers = true
    log_error_verbosity = "LOG_ERROR_VERBOSITY_UNSPECIFIED"
    max_connections                   = 395
    vacuum_cleanup_index_scale_factor = 0.2
  }]

也就是说,我知道我需要使用"dynamic",但它只能应用于块"config“和嵌套块"resource_name”。

如何将"postgresql_config“的值从main.tf传递给模块?当然,我在for_each = var.postgresql_config中的例子不起作用,但我希望这样可以给出我需要什么的想法。

或者terraform根本没有动态使用自定义变量的选项,而且所有这些变量都必须显式指定?

如能提供任何帮助,将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2022-05-22 13:55:16

据我所知,您正在尝试为资源postgres_config动态创建一个映射。

我建议使用for表达式来解决这个问题。

但是,我认为您的问题在于如何为模块定义变量。如果您的postgress_config列表中有多个信任项,您可能会遇到问题,因为该配置只能根据它的外观获取一个映射。

请看以下文档:

这个是关于如何定义变量的。

https://www.terraform.io/language/expressions/dynamic-blocks#multi-level-nested-block-structures

用于表达

https://www.terraform.io/language/expressions/for

对于您的配置问题,我的解决方案是这样的,假设postgres_config列表始终有一个元素:

代码语言:javascript
复制
      # problem is here
      postgresql_config = var.postgresql_config[0]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72327779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档