AWS VPC
AWS의 기본이 되는 서비스로 AWS의 수 많은 서비스 중 제일 중요한 서비스이다
provider = "aws" {
region = "ap-northeast-2"
}
terraform init으로 테라폼 디렉터리로 만들어줌
### vpc
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "terraform-vpc-test"
}
}
### public subnet
resource "aws_subnet" "public_subnet" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.10.0/24"
availability_zone = "ap-northeast-2a"
tags = {
Name = "terraform-public-test"
}
}
### private subnet
resource "aws_subnet" "private_subnet" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.20.0/24"
availability_zone = "ap-northeast-2c"
tags = {
Name = "terraform-private-test"
}
}
### internet gateway
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
tags = {
Name = "terraform-igw-test"
}
}
### eip for nat gateway
resource "aws_eip" "nat" {
vpc = true
lifecycle {
create_before_destroy = true
}
}
### nat gateway
resource "aws_nat_gateway" "ngw" {
allocation_id = aws_eip.nat.id
subnet_id = aws_subnet.public_subnet.id
tags = {
Name = "terraform-natgw-test"
}
}
### public routing table
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
## inner rule
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id // 0.0.0.0/0으로 가는 경로는 igw를 거쳐서 나감
}
tags = {
Name = "terraform-public-rt-test"
}
}
### routing table public subnet에 연결
resource "aws_route_table_association" "route_table_association_public" {
subnet_id = aws_subnet.public_subnet.id
route_table_id = aws_route_table.public.id
}
### private routing table
resource "aws_route_table" "private"{
vpc_id = aws_vpc.main.id
tags = {
Name = "terraform-private-rt-test"
}
}
### routing table public subnet에 연결
resource "aws_route_table_association" "route_table_association_private" {
subnet_id = aws_subnet.private_subnet.id
route_table_id = aws_route_table.private.id
}
### inner rule이 아닌 외부에서 리소스 정의 → 추후 확장성이 좋고 유연하게 코드를 관리할 수 있음
resource "aws_route" "private_nat" {
route_table_id = aws_route_table.private.id
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.ngw.id // 0.0.0.0/0은 nat를 통함
}
이렇게 작성하고 terraform apply하면 실제 aws 리소스가 생성된다.
만약 테라폼으로 작성한 리소스를 콘솔에서 변경하거나 삭제한 후 terraform plan을 하면 삭제된 리소스에 대해서 추가or변경한다고 나옴
왜냐하면 테라폼은 tfstate 파일에 테라폼으로 생성한 리소스가 정의되어 있고 tfstate 파일을 기준으로 하기에 콘솔에서 삭제하더라도 다시 복구가 가능하다는 굉장히 큰 장점이 있다.