【问题标题】:How to save Terraform output variable into a Github Action’s environment variable如何将 Terraform 输出变量保存到 Github Action 的环境变量中
【发布时间】:2021-12-23 19:14:15
【问题描述】:

我的项目使用 Terraform 来设置基础架构,并使用 Github Actions 进行 CI/CD。运行terraform apply 后,我想将 Terraform 输出变量的值保存为 Github Action 环境变量,以供工作流稍后使用。

根据 Github Action 的文档,this 是使用工作流命令创建或更新环境变量的方法。

这是我简化的 Github Action 工作流程:

name: Setup infrastructure
jobs:
  run-terraform:
    name: Apply infrastructure changes
    runs-on: ubuntu-latest
    steps:
      ...
      - run: terraform output vm_ip
      - run: echo TEST=$(terraform output vm_ip) >> $GITHUB_ENV
      - run: echo ${{ env.TEST }}

当在本地运行命令 echo TEST_VAR=$(terraform output vm_ip) 时,输出完全是 TEST="192.168.23.23" 但从 Github Action CLI 输出中我得到了一些非常奇怪的东西:

我试过单引号,双引号。在某些时候,我改变了策略并尝试使用jq。所以我添加了以下步骤,以便将所有 Terraform 输出导出到 json 文件并使用 jq 解析它:

- run: terraform output -json >> /tmp/tf.out.json
- run: jq '.vm_ip.value' /tmp/tf.out.json

但现在它抛出以下错误:

parse error: Invalid numeric literal at line 1, column 9

即使生成的 JSON 完全有效:

{
  "cc_host": {
    "sensitive": false,
    "type": "string",
    "value": "private.c.db.ondigitalocean.com"
  },
  "cc_port": {
    "sensitive": false,
    "type": "number",
    "value": 1234
  },
  "db_host": {
    "sensitive": false,
    "type": "string",
    "value": "private.b.db.ondigitalocean.com"
  },
  "db_name": {
    "sensitive": false,
    "type": "string",
    "value": "XXX"
  },
  "db_pass": {
    "sensitive": true,
    "type": "string",
    "value": "XXX"
  },
  "db_port": {
    "sensitive": false,
    "type": "number",
    "value": 1234
  },
  "db_user": {
    "sensitive": false,
    "type": "string",
    "value": "XXX"
  },
  "vm_ip": {
    "sensitive": false,
    "type": "string",
    "value": "206.189.15.70"
  }
}

terraform output -json >> /tmp/tf.out.jsonjq '.vm_ip.value' /tmp/tf.out.json 命令在本地相应地工作。

【问题讨论】:

    标签: json continuous-integration environment-variables terraform github-actions


    【解决方案1】:

    经过几个小时的搜索,我终于弄明白了。

    似乎Terraform's Github Action 提供了一个名为terraform_wrapper 的附加参数,如果您计划在命令中使用输出,则需要将其设置为false。你可以阅读更深入的文章here

    否则,它们将自动暴露给步骤的输出,并且可以像steps.<step_id>.outputs.<variable> 一样访问它们。你可以阅读更多关于他们的信息herehere

    【讨论】:

    • FWIW,如果您打算直接在其他地方使用字符串输出值,那么我建议您使用 terraform output -raw NAME 访问它,因为这样它就不会包含用于引用和转义 Terraform 的内容人类读者可以看到 Terraform 语言语法中的值,而只是文字字符串值。
    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 2021-02-26
    • 2021-09-24
    • 2021-10-08
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多