🏗️ はじめに
Terraform でインフラ構成を管理していると、
リソース数の増加に伴い、main.tfが肥大化して管理しづらくなることがあります。
そこで重要になるのが モジュール化(Module) です。
本記事では、Terraform における モジュール設計の基本思想 と、 VPC / Subnet / EC2 を分割する実践的な構成例・命名規則 を解説します。
🧩 Terraform モジュールとは?
Terraform の module とは、 複数のリソースを 1つのまとまりとして再利用可能にした構成単位です。
モジュール化することで、次のようなメリットがあります。
- コードの 再利用性 が向上する
- 構成が整理され、可読性・保守性 が高まる
- 環境差分(dev / stg / prod)を吸収しやすい
📁 推奨ディレクトリ構成
まずは、シンプルでよく使われる構成例です。
terraform/
├── main.tf
├── variables.tf
├── outputs.tf
├── modules/
│ ├── vpc/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ ├── subnet/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ └── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
🌐 VPC モジュール例
modules/vpc/main.tf
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
tags = {
Name = var.name
}
}
modules/vpc/variables.tf
variable "cidr_block" {
type = string
}
variable "name" {
type = string
}
modules/vpc/outputs.tf
output "vpc_id" {
value = aws_vpc.this.id
}
🧱 Subnet モジュール例
resource "aws_subnet" "this" {
vpc_id = var.vpc_id
cidr_block = var.cidr_block
availability_zone = var.az
tags = {
Name = var.name
}
}
variable "vpc_id" {
type = string
}
variable "cidr_block" {
type = string
}
variable "az" {
type = string
}
variable "name" {
type = string
}
output "subnet_id" {
value = aws_subnet.this.id
}
🖥️ EC2 モジュール例
resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
subnet_id = var.subnet_id
tags = {
Name = var.name
}
}
variable "ami" {
type = string
}
variable "instance_type" {
type = string
}
variable "subnet_id" {
type = string
}
variable "name" {
type = string
}
output "instance_id" {
value = aws_instance.this.id
}
🔗 呼び出し側(main.tf)例
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
name = "main-vpc"
}
module "subnet" {
source = "./modules/subnet"
vpc_id = module.vpc.vpc_id
cidr_block = "10.0.1.0/24"
az = "ap-northeast-1a"
name = "public-subnet"
}
module "ec2" {
source = "./modules/ec2"
ami = "ami-xxxxxxxx"
instance_type = "t3.micro"
subnet_id = module.subnet.subnet_id
name = "app-server"
}
🏷️ 命名規則のベストプラクティス
- module 名:役割ベース(vpc / subnet / ec2)
- resource 名:
thisまたはmainに統一 - variable / output:意味が分かる名前を使用
- tag の Name:AWS コンソールで識別しやすい名称
🧠 まとめ
- Terraform は module 化 することで真価を発揮する
- VPC / Subnet / EC2 は分離するのが基本
- output を使って module 間を疎結合にする
- 命名規則を統一すると長期運用が楽になる