这是一个简单的例子。Azure 是这里的提供者,但这不会改变模块的组织方式。
这假设您正在使用本地 TF 状态(可能您想要设置远程状态)。
此处还从本地文件系统中引用了模块。您可以将它们存储在单独的 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"
}
要部署该特定模块(与我的示例不同,它可能具有多个资源),您terragrunt apply
从project/test/resource_group
.
terragrunt apply-all
或者,您可以通过从运行来执行多个模块project/test
。
老实说,如果你打算将它用于生产项目,你最好阅读 Terragrunt 文档,它非常好。