模块注册表与共享

学习如何使用 Terraform Registry 和发布自己的模块。

一、Terraform Registry 介绍

1.1 什么是 Registry

Terraform Registry 是官方的模块和 Provider 仓库。

访问地址: https://registry.terraform.io/

功能:

  • 📦 浏览和搜索模块
  • 📖 查看文档和示例
  • ⬇️ 下载和使用模块
  • ⭐ 查看使用统计和评分
  • 🔍 查看源代码和版本历史

1.2 Registry 分类

公共 Registry:

  • 官方 Registry(registry.terraform.io)
  • 免费使用
  • 社区贡献

私有 Registry:

  • Terraform Cloud/Enterprise
  • 企业内部模块
  • 访问控制

二、使用 Registry 模块

2.1 浏览和搜索

在 Registry 上搜索 VPC 模块:

https://registry.terraform.io/search/modules?q=vpc

热门模块示例:

  • terraform-aws-modules/vpc/aws - AWS VPC
  • terraform-aws-modules/eks/aws - Amazon EKS
  • terraform-azurerm-modules/network/azurerm - Azure 网络

2.2 使用官方模块

AWS VPC 模块:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"
  
  name = "my-vpc"
  cidr = "10.0.0.0/16"
  
  azs             = ["us-west-2a", "us-west-2b", "us-west-2c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
  
  enable_nat_gateway = true
  enable_vpn_gateway = true
  
  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

output "vpc_id" {
  value = module.vpc.vpc_id
}

2.3 查看模块文档

模块页面包含:

  • README:使用说明
  • Inputs:输入变量列表
  • Outputs:输出值列表
  • Dependencies:依赖的 Provider
  • Resources:创建的资源列表
  • Examples:使用示例
  • Versions:版本历史

2.4 版本约束

# 精确版本
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"
}

# 版本范围
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = ">= 5.0.0, < 6.0.0"
}

# 悲观约束(推荐)
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"  # >= 5.0.0 且 < 6.0.0
}

三、发布模块到 Registry

3.1 准备工作

要求:

  1. ✅ GitHub 仓库(公开)
  2. ✅ 遵循命名规范:terraform-<PROVIDER>-<NAME>
  3. ✅ 包含标准文件结构
  4. ✅ 使用语义化版本标签
  5. ✅ 完善的文档

仓库命名示例:

terraform-aws-vpc
terraform-azure-network
terraform-google-gke

3.2 模块结构

标准结构:

terraform-aws-vpc/
├── main.tf              # 主要资源定义
├── variables.tf         # 输入变量
├── outputs.tf           # 输出值
├── versions.tf          # Provider 版本约束
├── README.md            # 文档
├── LICENSE              # 许可证
├── CHANGELOG.md         # 变更日志
├── .gitignore
├── examples/            # 使用示例
│   ├── basic/
│   │   ├── main.tf
│   │   └── README.md
│   └── complete/
│       ├── main.tf
│       └── README.md
└── modules/             # 子模块(可选)
    └── vpc-endpoints/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

3.3 versions.tf

terraform {
  required_version = ">= 1.0"
  
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

3.4 README.md

必需内容:

# AWS VPC Terraform Module

创建 AWS VPC,包含子网、路由表和 NAT 网关。

## 功能特性

- ✅ 创建 VPC 和子网
- ✅ 配置 Internet Gateway
- ✅ 可选 NAT Gateway
- ✅ 自动创建路由表

## 使用示例

\`\`\`hcl
module "vpc" {
  source = "github.com/username/terraform-aws-vpc"
  
  vpc_name = "my-vpc"
  vpc_cidr = "10.0.0.0/16"
}
\`\`\`

## 要求

| 名称 | 版本 |
|------|------|
| terraform | >= 1.0 |
| aws | >= 5.0 |

## 输入变量

| 名称 | 描述 | 类型 | 默认值 | 必需 |
|------|------|------|--------|------|
| vpc_name | VPC 名称 | string | - | 是 |
| vpc_cidr | VPC CIDR 块 | string | 10.0.0.0/16 | 否 |

## 输出

| 名称 | 描述 |
|------|------|
| vpc_id | VPC ID |
| public_subnet_ids | 公有子网 ID 列表 |

## 许可证

MIT

3.5 发布步骤

1. 创建 GitHub 仓库

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/username/terraform-aws-vpc.git
git push -u origin main

2. 创建版本标签

git tag -a v1.0.0 -m "First release"
git push origin v1.0.0

3. 发布到 Registry

访问 https://registry.terraform.io/publish

  • 点击 "Publish" → "Module"
  • 使用 GitHub 账号登录
  • 选择仓库
  • 点击 "Publish Module"

4. 验证发布

https://registry.terraform.io/modules/username/vpc/aws

3.6 更新模块

# 修改代码
git add .
git commit -m "Add new feature"

# 创建新版本标签
git tag -a v1.1.0 -m "Add NAT Gateway support"
git push origin v1.1.0

Registry 会自动检测新标签并发布。

四、私有 Registry

4.1 Terraform Cloud

配置私有 Registry:

  1. 在 Terraform Cloud 创建组织
  2. 上传模块代码
  3. 发布模块

使用私有模块:

module "vpc" {
  source  = "app.terraform.io/my-org/vpc/aws"
  version = "1.0.0"
  
  vpc_name = "my-vpc"
}

4.2 Git 作为 Registry

使用 Git 标签:

module "vpc" {
  source = "git::https://github.com/company/terraform-modules.git//vpc?ref=v1.0.0"
}

# SSH
module "vpc" {
  source = "git::ssh://git@github.com/company/terraform-modules.git//vpc?ref=v1.0.0"
}

# 分支
module "vpc" {
  source = "git::https://github.com/company/terraform-modules.git//vpc?ref=main"
}

五、模块文档最佳实践

5.1 自动生成文档

使用 terraform-docs:

# 安装
brew install terraform-docs

# 生成文档
terraform-docs markdown table . > README.md

# 自动更新
terraform-docs markdown table . \
  --output-file README.md \
  --output-mode inject

配置文件 .terraform-docs.yml

formatter: "markdown table"

sections:
  show:
    - header
    - requirements
    - providers
    - inputs
    - outputs
    - resources

output:
  file: README.md
  mode: inject
  template: |-
    <!-- BEGIN_TF_DOCS -->
    {{ .Content }}
    <!-- END_TF_DOCS -->

sort:
  enabled: true
  by: name

5.2 README 模板

完整 README 结构:

# 模块名称

简短描述。

## 功能特性

- ✅ 功能 1
- ✅ 功能 2

## 架构图

\`\`\`
[架构示意图]
\`\`\`

## 使用示例

### 基础用法

\`\`\`hcl
[基础示例代码]
\`\`\`

### 高级用法

\`\`\`hcl
[高级示例代码]
\`\`\`

## 要求

[自动生成的要求表格]

## 输入变量

[自动生成的变量表格]

## 输出

[自动生成的输出表格]

## 注意事项

- ⚠️ 注意事项 1
- ⚠️ 注意事项 2

## 许可证

MIT

5.3 CHANGELOG.md

使用 Keep a Changelog 格式:

# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.1.0] - 2024-01-10

### Added
- NAT Gateway 支持
- VPC Endpoints 支持

### Changed
- 更新 AWS Provider 到 5.0

### Fixed
- 修复子网 CIDR 计算错误

## [1.0.0] - 2024-01-01

### Added
- 初始发布
- VPC 和子网创建
- Internet Gateway

六、模块质量标准

6.1 质量检查清单

代码质量:

  • ✅ 使用 terraform fmt 格式化
  • ✅ 使用 terraform validate 验证
  • ✅ 通过 tflint 检查
  • ✅ 通过安全扫描(如 tfsec)

文档质量:

  • ✅ README 完整
  • ✅ 所有变量有描述
  • ✅ 提供使用示例
  • ✅ 有 CHANGELOG

测试质量:

  • ✅ 提供示例配置
  • ✅ 有自动化测试(可选)
  • ✅ 测试多个场景

6.2 CI/CD 集成

GitHub Actions 示例:

name: Terraform Module CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_version: 1.6.0
      
      - name: Terraform Format
        run: terraform fmt -check -recursive
      
      - name: Terraform Init
        run: terraform init
      
      - name: Terraform Validate
        run: terraform validate
      
      - name: Run tflint
        uses: terraform-linters/setup-tflint@v3
        with:
          tflint_version: latest
      
      - name: TFLint
        run: tflint --recursive
      
      - name: Run tfsec
        uses: aquasecurity/tfsec-action@v1.0.0
  
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Generate docs
        uses: terraform-docs/gh-actions@v1.0.0
        with:
          working-dir: .
          output-file: README.md
          output-method: inject

6.3 版本发布自动化

自动创建 Release:

name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Create Release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          body_path: CHANGELOG.md
          draft: false
          prerelease: false

七、模块发现和选择

7.1 评估模块质量

检查清单:

  • 使用统计:下载量、星标数
  • 📅 更新频率:最近更新时间
  • 📖 文档完整性:README、示例
  • 🐛 Issue 处理:响应速度
  • 🔒 安全性:是否有已知漏洞
  • 🏷️ 版本管理:是否使用语义化版本

7.2 常用模块推荐

AWS:

# VPC
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"
}

# EKS
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 19.0"
}

# RDS
module "db" {
  source  = "terraform-aws-modules/rds/aws"
  version = "~> 6.0"
}

# S3
module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "~> 3.0"
}

Azure:

# Network
module "network" {
  source  = "Azure/network/azurerm"
  version = "~> 5.0"
}

# AKS
module "aks" {
  source  = "Azure/aks/azurerm"
  version = "~> 7.0"
}

Google Cloud:

# Network
module "vpc" {
  source  = "terraform-google-modules/network/google"
  version = "~> 7.0"
}

# GKE
module "gke" {
  source  = "terraform-google-modules/kubernetes-engine/google"
  version = "~> 27.0"
}

八、模块安全性

8.1 安全扫描

使用 tfsec:

# 安装
brew install tfsec

# 扫描
tfsec .

# 特定检查
tfsec --minimum-severity HIGH .

使用 Checkov:

# 安装
pip install checkov

# 扫描
checkov -d .

# 输出 JSON
checkov -d . -o json

8.2 安全最佳实践

# ✅ 默认加密
resource "aws_s3_bucket" "data" {
  bucket = var.bucket_name
  
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
}

# ✅ 阻止公开访问
resource "aws_s3_bucket_public_access_block" "data" {
  bucket = aws_s3_bucket.data.id
  
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# ✅ 启用日志
resource "aws_s3_bucket_logging" "data" {
  bucket = aws_s3_bucket.data.id
  
  target_bucket = aws_s3_bucket.logs.id
  target_prefix = "data-bucket/"
}

小结

模块注册表和共享的关键要点:

  • 使用 Registry:浏览、搜索、使用官方模块
  • 发布模块:遵循规范、完善文档、语义化版本
  • 私有 Registry:Terraform Cloud 或 Git
  • 质量保证:CI/CD、测试、安全扫描
  • 文档生成:terraform-docs 自动化
  • 版本管理:语义化版本、CHANGELOG

下一章我们将学习模块组合和高级设计模式。