这是一个简单的例子。 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 文档,它非常好。