如何在 Azure DevOps 发布管道中使用存储在存储帐户中的 Terraform 输出变量?

时间:2021-05-27 18:08:58

标签: azure-devops terraform terraform-provider-azure

在 Stackoverflow 上有与此类似的问题,但没有一个解决我在使用 Azure 存储帐户保留输出时使用 Terraform 的问题。

这是我的场景,听起来可能很熟悉:

我的 terraform 脚本使用功能键预配 Azure HTTP 触发的函数。此外,此 terraform 脚本提供了一个 Web 应用程序,该应用程序调用上述 HTTP 触发的函数。 HTTP 触发函数的密钥存储在 Web 应用程序的 appsettings.json 文件中,以将其包含在 HTTP 标头对 HTTP 触发函数的调用中。

以下代码片段说明了如何在 terraform 中配置 HTTP 触发的函数:

resource "azurerm_function_app" "myhttpfunc" {
  name                      = var.funcname
  location                  = "${azurerm_resource_group.rc.location}"
  resource_group_name       = "${azurerm_resource_group.rc.name}"
  app_service_plan_id       = "${azurerm_app_service_plan.funcsserviceplan.id}"
  storage_account_name      = "${azurerm_storage_account.funcstorage.name}"
  storage_account_access_key = "${azurerm_storage_account.funcstorage.primary_access_key}"
}

访问函数键的输出变量如下:

output "funchostkeys" {
  value = data.azurerm_function_app_host_keys.myhttpfunc
  sensitive = true
}

我假设此输出和其他输出将出现在托管在专用 Azure 存储帐户上的 terraform.tfstate 中。

我的问题是,如何通过用输出变量中生成的 terraform 替换配置条目,在 Azure Release 管道中获取特定输出以操作 appsettings.json 文件?

例如,this post 建议按照以下行将 terraform 的输出生成到文件中,但在我的情况下这似乎不是一个选项,因为我的 terraform 脚本利用 Azure 存储来保留输出。

terraform output -json > outputs.json

1 个答案:

答案 0 :(得分:1)

根据您的要求,您可以尝试使用以下命令输出变量:

terraform output -raw funchostkeys

然后您可以使用 logging command 将该值设置为管道变量。

例如:Powershell 脚本

- powershell: |
   echo ##vso[task.setvariable variable=varname]$(terraform output -raw funchostkeys)
   
  displayName: 'PowerShell Script'

然后您可以使用 Replace token task 使用管道变量来替换 appsettings.json 中的值。

您可以在 appsettings.json 中定义 #{variablename}#。运行管道时,输出值将设置在目标位置。