【问题标题】:Pass a single JSON config variable to Terraform template using tfvars使用 tfvars 将单个 JSON 配置变量传递给 Terraform 模板
【发布时间】:2021-08-16 04:10:25
【问题描述】:

我有这个 json 文件名为:dev.auto.tfvars.json,其内容:

{
  "config": {
    "KEY1": "VAL2",
    "KEY2": "VAL2"
  }
}

现在,我想将 config(它是一个对象)导入到我的 terraform tf 模板中的单个 terraform 环境变量中,如下所示(main.tf 文件):

variable config { type = map }
...
resource "aws_lambda_function" "mylambda" {
  ...
  environment {
    variables = {
      config = var.config
    }
  }
}

这样做的目的是通过我的应用程序 server.js 中的 1 个配置变量读取整个 JSON:

const allConfig = process.env.config;
console.log(allConfig.KEY1) // Will print VAL1

我想避免像这样引用我的 main.tf 文件中的每个变量(这很乏味):

variable KEY1{}
variable KEY2{}
...
resource "aws_lambda_function" "mylambda" {
  ...
  environment {
    variables = {
      KEY1 = var.KEY1
      KEY2 = var.KEY2
    }
  }

当我尝试上面的解决方案时,terraform 会抛出一个错误:

var.config is a map of dynamic, known only after apply
Inappropriate value for attribute "variables": element "config": string
required.

【问题讨论】:

    标签: terraform


    【解决方案1】:

    在这个 stackoverflow 帖子中找到了答案:

    https://stackoverflow.com/a/63509997/3263659

    使用jsonencode 成功了:

    variable config { type = map }
    ...
    resource "aws_lambda_function" "mylambda" {
      ...
      environment {
        variables = {
          config = jsonencode(var.config)
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      使用 jsonencode 而不是读取 json 文件。查看official documentation 以获取更多示例。

      【讨论】:

        猜你喜欢
        • 2021-01-20
        • 2021-04-14
        • 2019-01-21
        • 2019-04-24
        • 2018-09-07
        • 2017-11-10
        • 2021-01-15
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多