如何在Azure DevOps管道中初始化Terraform变量

huangapple go评论79阅读模式
英文:

How to initialize terraform variables in Azure DevOps pipeline

问题

Here's the translated content:

在我的 Terraform 变量文件中,我定义了以下变量:

variable "environment" {
  type = string
}
variable "resource_group" {
  type = object({
    name        = string
    location    = string
  })
}

我在 terraform.tfvars 文件中按照以下代码片段进行初始化:

environment = "Dev"
resource_group = {
  name = "mytestresourcegroup"
  location = "Canada Central"
}

我在 Azure DevOps 中有一个构建管道,用于运行我的 Terraform 实现并成功创建 Azure 资源。这很好,但这并不是一个可扩展的解决方案,无法在另一个环境(例如生产环境或用户验收测试环境)中创建资源。

如何在 Azure DevOps 管道中初始化 environmentresource_group 变量的值,使得 environment 可以变成 "prod" 或 "uat" 等,更重要的是 resource_group 是一个更复杂的对象,如何初始化 namelocation 呢?

英文:

I have the following variables defined in my terraform variables file:

variable "environment" {
  type = string
}
variable "resource_group" {
  type = object({
    name        = string
    location    = string
  })
}

I initialize them in terraform.tfvars files per the following code snippet:

environment = "Dev"
resource_group = {
  name = "mytestresourcegroup"
  location = "Canada Central"
}

I have a build pipeline in Azure DevOps that runs my terraform implementation and creates the azure resources successfully. This is great, but it's not a scalable solution to create the resources in another environment e.g. production.

How can I initialize environment and resource_group variables' values int he Azure DevOps pipeline to something else so that for e.g. environment becomes "prod" or "uat", etc.? More importantly the resource_group is a more complex object and the question is how to initialize the name and the location.

答案1

得分: 1

以下是翻译好的部分:

为实现这一点,一种方法是为每个环境创建一个单独的 tf.vars 文件,其名称将与您的 ADO 流水线环境匹配。一旦配置完成,ADO 环境 devuatprd 将通过参数替换传递到您的 ADO 流水线,然后映射到正确的环境变量文件。

我建议为每个环境创建一个独立的 tf.vars 文件,而不是一个会被覆盖的文件,因为这将在您的 ADO 流水线上创建一个 Terraform 依赖关系。通过为每个环境创建单独的 .tfvars 文件,您的 Terraform 将更独立于构建/部署过程。

这里有一篇博客文章详细介绍了如何实现这一点,并提供了示例代码。

英文:

One way to achieve this is to have a separate tf.vars file for each environment whose name will match you ADO pipeline environments. Once this is configured the ADO environment dev, uat, prd will be passed through your ADO pipeline to your terraform step via parameter substitution and map to the correct environment variable file.

I'd recommend a separate tf.vars file per environment as opposed to one that is overwritten as this will create a terraform dependency on your ADO pipelines. By creating a separate .tfvars for each environment then your terraform is more agnostic from your build/deployment process.

Here is a blog post detailing in depth how to achieve this and provides sample code.

huangapple
  • 本文由 发表于 2023年6月11日 22:03:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定