【问题标题】:How do I pass a variable from a pipeline task into a terraform task and apply it in my terraform code?如何将管道任务中的变量传递给 terraform 任务并将其应用到我的 terraform 代码中?
【发布时间】:2021-12-28 22:52:48
【问题描述】:

所以我有一个带有任务的管道,我通过 Powershell 检查日期。

 - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $iso8601_time = Get-Date -Format "o"
          echo "##vso[task.setvariable variable=pitr_time;]$iso8601_time"
        displayName: "Get point-in-time record before launching migration"

我稍后会在我的 terraform 任务中尝试使用此日期来根据我的 PowerShell 任务中的 DateTime 创建一个数据库。

如果我正确地使用了

echo "##vso[task.setvariable variable=pitr_time;]$iso8601_time"

我创建了一个名为 pitr_time 的环境变量,可以将其传递给同一管道中的其他任务。

因此,我现在有第二个任务,我使用这个环境变量。

- stage: DeployInfraPOC
  dependsOn: BuildInfraPOC
  variables:
    env: poc
    # TODO: check if variable get transfered to tf.
    TF_VAR_PITR: $(pitr_time)
  jobs: 
  - template: templates/deploy-infra.yml
    parameters:
      env: poc
      armServiceConnection: "Service connection devops"
      projectRoot: $(System.DefaultWorkingDirectory)
      planArtifactName: "pitr-database-migration-poc-$(Build.BuildId).tfplan

现在,当我查看 terraform 文档时,我发现我必须使用前缀“TF_VAR_”来定义它才能使用我想要传递的变量。

但现在我的问题是:如何在 Terraform 中使用这个变量?

我想我可以将它添加到我的 variables.tf 文件中

variable "TF_VAR_PITR" {
  description = "Env var - Point-in-time restore."
  type = string
}

但是当我想像这样在 main.tf 中调用我的变量时,它似乎不起作用

resource "azurerm_mssql_database" "mssqldb" {
  name                          = "db-bkup-temp-pitr"
  server_id                     = data.azurerm_mssql_server.mssqlsrv.id
  create_mode                   = "PointInTimeRestore"
  creation_source_database_id   = "/subscriptions/##############"
  restore_point_in_time         = var.TF_VAR_PITR
  }

我做错了什么?有更好的选择吗?

【问题讨论】:

  • 变量不会跨阶段共享,除非它们是输出变量并使用特定语法引用。请参阅有关变量的文档。

标签: azure azure-devops terraform azure-pipelines


【解决方案1】:

如果你的环境变量是TF_VAR_PITR,那么TF变量就叫做PITR

variable "PITR" {
  description = "Env var - Point-in-time restore."
  type = string
}

【讨论】:

  • 不起作用,我仍然得到:│错误:预期“restore_point_in_time”是有效的 RFC3339 日期,得到“$(pitr_time)”:解析时间“$(pitr_time)”为“2006- 01-02T15:04:05Z07:00”:无法将“$(pitr_time)”解析为“2006”││使用 azurerm_mssql_database.mssqldb,│在 main.tf 第 17 行,资源“azurerm_mssql_database”“mssqldb”:│17: restore_point_in_time = var.PITR
  • @PrayingMantis 这是您发布的新问题。现在的问题是关于时间戳的正确格式,而不是访问你的变量。因此,应该提出新的问题,包括相关的细节,例如,你的 PITR 到底是什么。
  • @PrayingMantis 如果我的回答帮助您克服了您报告的原始问题,我们将不胜感激。
猜你喜欢
  • 2021-07-29
  • 2020-11-30
  • 2021-03-27
  • 2021-02-01
  • 2019-05-20
  • 2020-09-13
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
相关资源
最近更新 更多