You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于公共Terraform模块创建本地模块并仅传递所需参数

基于公共模块构建Terraform本地模块(AWS Hub-Spoke场景)

1. 本地模块基础目录结构

先搭建最基础的本地模块目录,以Hub网络模块为例:

modules/
└── aws_hub_network/
    ├── main.tf
    ├── variables.tf
    └── outputs.tf

2. 在main.tf中调用公共模块

直接复用Terraform Registry上的AWS公共模块,仅传递Hub架构所需的必要参数,无需编写完整资源块。以VPC模块为例:

# 调用AWS官方VPC公共模块
module "hub_vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0" # 固定版本避免兼容性问题

  # 仅传入Hub VPC核心参数
  name = var.hub_vpc_name
  cidr = var.hub_vpc_cidr

  azs             = var.hub_azs
  private_subnets = var.hub_private_subnets
  public_subnets  = var.hub_public_subnets

  enable_nat_gateway = true
  single_nat_gateway = true # Hub场景下单NAT网关降低成本
}

3. 定义本地模块的变量(variables.tf)

只把需要外部传入的参数定义为变量,不重复公共模块的全部变量:

variable "hub_vpc_name" {
  description = "Hub VPC名称"
  type        = string
}

variable "hub_vpc_cidr" {
  description = "Hub VPC的CIDR段"
  type        = string
  default     = "10.0.0.0/16"
}

variable "hub_azs" {
  description = "Hub VPC使用的可用区列表"
  type        = list(string)
}

variable "hub_private_subnets" {
  description = "Hub VPC私有子网CIDR列表"
  type        = list(string)
}

variable "hub_public_subnets" {
  description = "Hub VPC公有子网CIDR列表"
  type        = list(string)
}

4. 定义本地模块的输出(outputs.tf)

将公共模块的关键资源属性暴露出来,供根模块或其他模块调用:

output "hub_vpc_id" {
  description = "Hub VPC的ID"
  value       = module.hub_vpc.vpc_id
}

output "hub_private_subnet_ids" {
  description = "Hub VPC私有子网ID列表"
  value       = module.hub_vpc.private_subnets
}

output "hub_public_subnet_ids" {
  description = "Hub VPC公有子网ID列表"
  value       = module.hub_vpc.public_subnets
}

5. 根模块调用本地模块

回到项目根目录的main.tf,直接引用本地模块并传入参数:

module "hub_network" {
  source = "./modules/aws_hub_network"

  hub_vpc_name = "my-hub-vpc"
  hub_azs      = ["us-east-1a", "us-east-1b"]
  hub_private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  hub_public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
}

6. Spoke模块的同理实现

创建aws_spoke_network本地模块时,同样复用公共VPC模块,仅传递Spoke架构的专属参数(比如无需自建NAT网关):

# modules/aws_spoke_network/main.tf
module "spoke_vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = var.spoke_vpc_name
  cidr = var.spoke_vpc_cidr

  azs             = var.spoke_azs
  private_subnets = var.spoke_private_subnets

  enable_nat_gateway = false # Spoke复用Hub的NAT网关,无需自建
}

核心注意事项

  • 始终固定公共模块的版本,避免自动更新引发的兼容性问题
  • 本地模块只封装必要参数,保持精简,不冗余定义公共模块已有的变量
  • 输出仅暴露上层模块需要使用的资源属性,减少不必要的信息传递

内容的提问来源于stack exchange,提问作者niko gher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 19:15:02