Terraform用例创建多个几乎相同的基础架构副本

Bal*_*Rau 3 terraform

我有TF模板,其目的是创建相同云基础架构的多个副本.例如,您在一个大型组织内部有多个业务部门,并且您希望构建相同的基本网络.或者,您希望开发人员能够轻松地启动他正在处理的堆栈."tf apply"调用之间的唯一区别是变量BUSINESS_UNIT,例如,它作为环境变量传入.

是否有其他人使用这样的系统,如果是这样,你如何管理状态文件?

Yev*_*man 5

您应该使用Terraform模块.创建模块没什么特别之处:只需将任何Terraform模板放在一个文件夹中.模块的特殊之处在于您如何使用它.

假设您将基础架构的Terraform代码放在文件夹中/terraform/modules/common-infra.然后,在实际定义您的实时基础架构的模板中(例如/terraform/live/business-units/main.tf),您可以按如下方式使用该模块:

module "business-unit-a" {
  source = "/terraform/modules/common-infra"
}
Run Code Online (Sandbox Code Playgroud)

要为多个业务单位创建基础结构,可以多次使用同一模块:

module "business-unit-a" {
  source = "/terraform/modules/common-infra"
}

module "business-unit-b" {
  source = "/terraform/modules/common-infra"
}

module "business-unit-c" {
  source = "/terraform/modules/common-infra"
}
Run Code Online (Sandbox Code Playgroud)

如果每个业务部门需要定制一些参数,那么您需要做的就是在模块中定义一个输入变量(例如,在下面/terraform/modules/common-infra/vars.tf):

variable "business_unit_name" {
  description = "The name of the business unit"
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以在每次使用模块时将此变量设置为不同的值:

module "business-unit-a" {
  source = "/terraform/modules/common-infra"
  business_unit_name = "a"
}

module "business-unit-b" {
  source = "/terraform/modules/common-infra"
  business_unit_name = "b"
}

module "business-unit-c" {
  source = "/terraform/modules/common-infra"
  business_unit_name = "c"
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅如何使用Terraform模块Terraform:Up&Running创建可重用的基础架构.