【问题标题】:Template for multiple environment terragrunt gcp project?多环境 terragrunt gcp 项目的模板?
【发布时间】:2021-02-22 14:05:55
【问题描述】:

我想启动一个新的 Terraform 项目,该项目将在 GCP 帐户上部署资源。我想使用 Terragrunt 来配置多个环境(测试、开发、生产)。

基本上每个环境都是相同的,只是资源名称带有前缀(环境名称)并且资源位于另一个区域。我也想用 terragrunt 让它保持干燥。

到目前为止,我只有这个所需的文件夹结构:

project
└── env
    └── test
    └── dev
    └── prod
└── resources
    └── vpc
    └── pubsub
    └── cloudrun
    └── resource4

我对 Terragrunt 感到困惑,而 Terraform 是压倒性的。我对此没有什么经验,我主要了解 AWS 上的 CloudFormation。

那么我应该把 terragrunt.hcl 文件放在哪里,里面应该放什么?我在哪里存储资源变量以及如何强制资源使用环境变量(区域和前缀)。部署具体环境应该使用什么命令?

【问题讨论】:

标签: google-cloud-platform terraform terragrunt


【解决方案1】:

这是一个简单的例子。 Azure 是这里的提供者,但这不会改变模块的组织方式。

这假设您使用的是本地 TF 状态(可能您想设置一个remote state)。

这里的本地文件系统也引用了模块。您可以将它们存储在单独的 Git 存储库中(Terragrunt 建议的方式)以进行版本控制。

project/resources/resource_group/main.tf 的可重用模块示例:

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "~> 2.26"
    }
  }
}

resource "azurerm_resource_group" "resource_group" {
  name     = "${var.project}-${var.environment}-resource-group"
  location = var.location

  tags = {
    project     = var.project
    environment = var.environment
    region      = var.location
  }
}

# I've included variables and outputs in the same file, 
# but it's recommended to put them into separate 
# variables.tf and outputs.tf respectively.

variable "project" {
  type        = string
  description = "Project name"
}

variable "environment" {
  type        = string
  description = "Environment (dev / stage / prod)"
}

variable "location" {
  type        = string
  description = "The Azure Region where the Resource Group should exist"
}

output "resource_group_name" {
  value = azurerm_resource_group.resource_group.name
}

模块在给定环境中的示例用法。模块路径为project/test/resource_group/terragrunt.hcl:

generate "provider" {
  path = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents = <<EOF
provider "azurerm" {
  features {}
}
EOF
}

terraform {
  source = "../../resources//resource_group"
}

inputs = {
  project = "myapp"
  environment = "test"
  location = "East US"
}

要部署该特定模块(与我的示例不同,它可能会有多个资源),您从project/test/resource_group 运行terragrunt apply

您也可以通过从project/test 运行terragrunt apply-all 来执行多个模块。

老实说,如果你打算将它用于生产项目,你最好阅读 Terragrunt 文档,它非常好。

【讨论】:

  • 但是为什么我需要在每个环境文件夹中为每个资源创建一个文件夹呢?对于每个环境(前缀和区域),我只需要 2 个不同的变量。
  • 也是 terragrunt.hcl 和 terraform.tfvars 一样吗?语法变了吗?
  • 我正在关注本教程harjot.me/blog/… 可以吗?
  • @KatranPlague 您为每个环境文件夹中的每个可重用模块创建一个文件夹,而不是每个资源。理想情况下,您将拥有(不是很多)模块。例如,您可能有模块:networkdatabasefronend_appbackend_app。每个模块将包含一个或多个 terraform 资源。 terragrunt.hcl 是一种配置可重用模块的方法,它与terraform.tfvars 不同。您不仅可以使用它来传递输入变量,还可以包含依赖项(其他模块)和共享配置。
猜你喜欢
  • 2023-01-17
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2020-01-14
  • 2017-09-25
  • 2020-11-13
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多