0

我很难理解如何在一个 GCP 项目中将 terraform-google-modules/terraform-google-kubernetes-engine等模块重用于多个环境,例如生产、登台和开发。

我曾经有这样的结构:

├── backend.tf
├── development
│   └── development.tfvars
├── firewall.tf
├── gcp-apis.tf
├── gke.tf
├── outputs.tf
├── production
│   └── production.tfvars
├── providers.tf
├── staging
│   └── staging.tfvars
├── variables.tf
├── versions.tf
└── vpc.tf

我刚刚用值填写了 .tfvars 文件。现在我不知何故迷失了模块结构。查看terraform-google-modules/terraform-google-kubernetes-engine 示例,我不确定如何为不同类型的机器/磁盘定义多个节点池。

对我来说,README.md 中的示例看起来不像是模板和变量的清晰分离,它似乎是某种混淆(请不要冒犯,我想我只是不明白)。

更具体一点:如果我想拥有多个节点池,我需要在 development.tfvars、staging.tfvars 和 production.tfvars 中定义什么?

希望你能帮助我。干杯

4

2 回答 2

1

我会更好地解释terraform workspace用法。

如果您想跨多个环境重用一个模块或一个资源,terraform workspace是更好的解决方案。您需要遵循一些步骤。

让我们创建 dev 和 prod 工作区:

terraform workspace new prod
terraform workspace new dev

让我们检查一下它们是否是在运行时创建的terraform workspace list,你会看到如下内容:

  default
* dev
  prod

现在我们有两个工作区,我们在dev. 由于我们想重用模块,我们需要使用映射中gke的名称传递我们想要更改的所有内容。workspace

Let's create a file first like settings.tf, see the following examples, and feel free to customize everything you want.

locals {
  env = terraform.workspace

  disk_size_gb = {
    dev  = 50
    prod = 100
  }

  machine_type = {
    dev  = "e2-standard-2"
    prod = "e2-medium"
  }
...
}

Now we need to use our custom configurations in the gke module, and all you need to do is:

module "gke" {
   source = "terraform-google-modules/kubernetes-engine/google"
   project_id = "<PROJECT ID>"
   name = "${local.env}-gke-cluster" #your cluster name will be dev-gke-cluster"
  ...
   disk_size_gb = local.disk_size_gb #50 for dev
   machine_type = local.machine_type #e2-standard-2 for dev
  ...
}

When you are done, let's deploy by:

terraform workspace select dev
terraform apply
terraform workspace select prod
terraform apply

As I said, you can use this approach on modules and resources.. You don't need to duplicate the terraform code, just put the values on the locals block as I did and use it where you want.

于 2022-01-30T05:54:30.840 回答
-1

在 Terraform 中,将模块视为单元块,您可以在不同的状态{环境}中调用它们或使用列表对其进行迭代。

环境/工作区

为每个环境创建工作区,并相应地使用 tfvars 文件,以便将每个环境跟踪到单独的状态文件中

terraform workspace create/list/switch 

迭代法

  • 使用,你只需要相同的环境和几乎没有变化的环境。
  • 在单个 tfvars 文件下统一您的配置并定义列表

使用 for_each 遍历一个列表,例如

module "eks" {
  for_each = var.listed_envs  #where listed envs is a list type variable .
  source = "../path_to_module "

检查 terraform 重要功能,例如 yaml 编码/解码,可以将变量文件更改为基于 yaml 的。

于 2022-01-28T17:19:53.720 回答