Skip to content

1. 模块的定义

1.1 什么是module?

module(模块)是一个在Terraform项目中包含一组代码的逻辑分组的文件夹。模块可以调用其他模块,并通过将一个模块的输出值(output.tf)传递到另一个模块的输入值(variable.tf)来实现模块资源数据的相互调用以提升代码的复用性

Terraform模块是编写高质量Terraform代码,提升代码复用性的重要手段。可以说,一个成熟的生产环境应该是由数个可信成熟的模块组装而成的。

主要由 3 个文件组成:

  • main.tf – 定义要创建的资源

  • variables.tf – 定义 main.tf 文件所需的输入变量

  • output.tf – 定义创建的基础设施的输出列表,供其他使用者使用

1.2 Module 工作原理

  • 远程模块:存储到根模块下的.terraform目录中(修改后,必须get/init)
  • 本地模块:将通过软连接的方式引用本地的源目录(修改后,无需操作)

1.3 Module 模块优点

  • 解决代码重复问题;
  • 加强代码可读性,代码整洁性;
  • 资源标准化;
  • 减少人为错误发生频率;

1.4 定义模块

Module 语法
  • name:模块的名称,在terraform中可以使用模块名称进行引用
  • source:模块代码的路径,本地或者远程的仓库
  • version:版本信息;

把不同云产品放在不同的文件夹下,并在根目录下使用关键词module,就可以理解为定义了一个模块。

yaml
vim /root/modules/vpc/main.tf

resource "vpc" {
...
}
vim /root/modules/vpc/main.tf

resource "vpc" {
...
}
yaml
vim /root/main.tf

module "vpc" {
...
}
vim /root/main.tf

module "vpc" {
...
}

1.5 引用模块

引用方式: module.MODULE_NAME.OUTPUT_NAME

yaml
module "vpc" {
	source = "./modules/vpc"
}

module "security_groups" {
	source = "./modules/security_groups"
	vpc_id = module.vpc.vpc_id
}

module "ecs" {
	source = "./modules/ecs"
	security_groups = module.security_groups.security_groups_id
	vswitch_id = module.vpc.vswitch_id
}
module "vpc" {
	source = "./modules/vpc"
}

module "security_groups" {
	source = "./modules/security_groups"
	vpc_id = module.vpc.vpc_id
}

module "ecs" {
	source = "./modules/ecs"
	security_groups = module.security_groups.security_groups_id
	vswitch_id = module.vpc.vswitch_id
}

❌ 注意

每当在代码中新增、删除或者修改一个module块之后,都要执行terraform init

2. 案例

2.1 单云

image-20250718175602350

bash
$ tree 
.
|-- main.tf
|-- modules
|   |-- ecs
|   |   |-- main.tf
|   |   |-- outputs.tf
|   |   |-- variables.tf
|   |   -- versions.tf
|   |-- nsg
|   |   |-- main.tf
|   |   |-- outputs.tf
|   |   |-- variables.tf
|   |   -- versions.tf
|   -- vpc
|       |-- main.tf
|       |-- outputs.tf
|       |-- variables.tf
|       -- versions.tf
|-- output.tf
|-- provider.tf
|-- terraform.tfstate
|-- terraform.tfstate.backup
|-- terraform.tfvars
|-- variables.tf
-- version.tf
$ tree 
.
|-- main.tf
|-- modules
|   |-- ecs
|   |   |-- main.tf
|   |   |-- outputs.tf
|   |   |-- variables.tf
|   |   -- versions.tf
|   |-- nsg
|   |   |-- main.tf
|   |   |-- outputs.tf
|   |   |-- variables.tf
|   |   -- versions.tf
|   -- vpc
|       |-- main.tf
|       |-- outputs.tf
|       |-- variables.tf
|       -- versions.tf
|-- output.tf
|-- provider.tf
|-- terraform.tfstate
|-- terraform.tfstate.backup
|-- terraform.tfvars
|-- variables.tf
-- version.tf

2.2 多云