我们构建并开源了Terragrunt 来解决这个问题。 Terragrunt 的功能之一是能够下载远程 Terraform 配置。这个想法是,您只需在一个存储库中为您的基础架构定义一次 Terraform 代码,例如,称为modules:
└── modules
├── app
│ └── main.tf
├── mysql
│ └── main.tf
└── vpc
└── main.tf
这个 repo 包含典型的 Terraform 代码,有一个区别:代码中任何在环境之间应该不同的东西都应该作为输入变量公开。例如,app 模块可能会暴露以下变量:
variable "instance_count" {
description = "How many servers to run"
}
variable "instance_type" {
description = "What kind of servers to run (e.g. t2.large)"
}
在一个单独的 repo 中,例如,live,您为所有环境定义代码,现在每个组件只包含一个 .tfvars 文件(例如 app/terraform.tfvars、mysql/terraform.tfvars 等)。这将为您提供以下文件布局:
└── live
├── prod
│ ├── app
│ │ └── terraform.tfvars
│ ├── mysql
│ │ └── terraform.tfvars
│ └── vpc
│ └── terraform.tfvars
├── qa
│ ├── app
│ │ └── terraform.tfvars
│ ├── mysql
│ │ └── terraform.tfvars
│ └── vpc
│ └── terraform.tfvars
└── stage
├── app
│ └── terraform.tfvars
├── mysql
│ └── terraform.tfvars
└── vpc
└── terraform.tfvars
请注意,任何文件夹中都没有 Terraform 配置(.tf 文件)。相反,每个.tfvars 文件都指定一个terraform { ... } 块,该块指定从何处下载 Terraform 代码,以及该 Terraform 代码中输入变量的环境特定值。例如,stage/app/terraform.tfvars 可能如下所示:
terragrunt = {
terraform {
source = "git::git@github.com:foo/modules.git//app?ref=v0.0.3"
}
}
instance_count = 3
instance_type = "t2.micro"
prod/app/terraform.tfvars 可能看起来像这样:
terragrunt = {
terraform {
source = "git::git@github.com:foo/modules.git//app?ref=v0.0.1"
}
}
instance_count = 10
instance_type = "m2.large"
请参阅Terragrunt documentation 了解更多信息。