Terraform AWS環境構築方法
以下のような形でリソース種別にファイル分割します。
TF-WORK
|– ec2.tf
|– main.tf
`– network.tf
1.main.tfの定義
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-northeast-1"
}
2.network.tfの定義
VPC構成要素
名前タグ
IPV4 CIDR ブロック
テナンシー
# ======VPC======
resource "aws_vpc" "tf-vpc-01" {
cidr_block = "192.168.0.0/16"
instance_tenancy = "default"
enable_dns_hostnames = "true"
tags = {
Name = "TF-VPC-01"
Env = "TF-DEV"
}
}
サブネット作成要素
VPC指定
関連付けられた VPC CIDR
アベイラビリティーゾーン
# ======Subnet======
resource "aws_subnet""tf-vpc-01-pub-01-a" {
vpc_id = aws_vpc.tf-vpc-01.id
cidr_block = "192.168.0.0/24"
availability_zone = "ap-northeast-1a"
map_public_ip_on_launch = "true"
tags = {
Name = "TF-VPC-01-Pub-01-a"
Env = "TF-DEV"
}
}
resource "aws_subnet" "tf-vpc-01-pri-01-a" {
vpc_id = aws_vpc.tf-vpc-01.id
cidr_block = "192.168.1.0/24"
availability_zone = "ap-northeast-1a"
tags = {
Name = "TF-VPC-01-Pri-01-a"
Env = "TF-DEV"
}
}
インターネットゲートウェイの作成
VPC ID
# ======IGW======
resource "aws_internet_gateway" "tf-vpc-01-igw-01" {
vpc_id = aws_vpc.tf-vpc-01.id
tags = {
Name = "TF-VPC-01-IGW-01"
Env = "TF-DEV"
}
}
ルートテーブルを作成
名前オプション
VPC
# ======RouteTable======
resource "aws_route_table" "tf-vpc-01-rtb-pub-01" {
vpc_id = aws_vpc.tf-vpc-01.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.tf-vpc-01-igw-01.id
}
tags = {
Name = "TF-VPC-01-RTB-Pub-01"
Env = "TF-DEV"
}
}
resource "aws_route_table" "tf-vpc-01-rtb-pri-01" {
vpc_id = aws_vpc.tf-vpc-01.id
tags = {
Name = "TF-VPC-01-RTB-Pri-01"
Env = "TF-WORK"
}
}
パブリックサブネットの関連付け
内容
サブネット:
tf-vpc-01-pub-01-a(パブリックサブネット)
ルートテーブル:
tf-vpc-01-rtb-pub-01
resource "aws_route_table_association" "tf-vpc-01-rtb-at-pub" {
subnet_id = aws_subnet.tf-vpc-01-pub-01-a.id
route_table_id = aws_route_table.tf-vpc-01-rtb-pub-01.id
}
プライベートサブネットの関連付け
内容
サブネット:
tf-vpc-01-pri-01-a(プライベートサブネット)
ルートテーブル:
tf-vpc-01-rtb-pri-01
resource "aws_route_table_association" "tf-vpc-01-rtb-at-pri" {
subnet_id = aws_subnet.tf-vpc-01-pri-01-a.id
route_table_id = aws_route_table.tf-vpc-01-rtb-pri-01.id
}
3.ec2.tfの定義
resource "aws_instance" "tf-ec2-01" {
ami = "ami-089jggg7b2adad"
instance_type = "t2.micro"
subnet_id = aws_subnet.tf-vpc-01-pub-01-a.id
key_name = "TF-AWS-KEY"
tags = {
Name = "TF-EC2-01"
Env = "TF-DEV"
}
}
実行方法
1.構文チェック
$ terraform validate
2.実行プラン確認
$terraform plan
3.適用
$terraform apply