Devops/Iac

[Terraform] VPC 환경 구축해보기

은하윤슬 2023. 7. 26. 23:23

VPC 환경 구축해보기

저번에 테라폼 키 설정과 간단한 EC2 구축을 실습했었습니다.

클라우드 환경에서의 VPC는 서브넷이나 네트워크 게이트웨이 등 네트워킹 환경을 가상으로 완벽하게 제어할 수 있는, 한마디로 가상 네트워크 구축 센터라고 볼 수 있습니다.

 

VPC는 클라우드 환경 구축에 있어 매우 중요한 요소에 해당하는데, 하나의 VPC 환경을 테라폼으로 간단하게 자동화시켜 동작하게 구현해보려고 합니다.

 

provider "aws"{
    region = "ap-northeast-2" // 제공자 리전 정보
    alias = "vpc"
}

resource "aws_vpc" "main" {
    cidr_block = "10.0.0.0/16"

    tags = {
        Name = "terraform-vpc"
    }
}

resource "aws_subnet" "terraform_sub1"{
    vpc_id = aws_vpc.main.id
    cidr_block = "10.0.1.0/24"

    availability_zone = "ap-northeast-2a"

    tags = {
        Name = "terraform_sub1"
    }
}

resource "aws_subnet" "terraform_sub2"{
    vpc_id = aws_vpc.main.id
    cidr_block = "10.0.2.0/24"

    availability_zone = "ap-northeast-2b"

    tags = {
        Name = "terraform_sub2"
    }
}

// igw 구성

resource "aws_internet_gateway" "main_igw" {
    vpc_id = aws_vpc.main.id

    tags = {
        Name = "main-igw"
    }
}

// Route Table 구성

resource "aws_route_table" "main_route_table"{
    vpc_id = aws_vpc.main.id

    tags = {
        Name = "main-rt"
    }
}

resource "aws_route_table_association" "route_table_association_1"{
    subnet_id = aws_subnet.terraform_sub1.id
    route_table_id = aws_route_table.main_route_table.id
}

resource "aws_route_table_association" "route_table_association_2"{
    subnet_id = aws_subnet.terraform_sub2.id
    route_table_id = aws_route_table.main_route_table.id
}

// Private Subnet 구성

resource "aws_subnet" "terraform_private_sub1"{
    vpc_id = aws_vpc.main.id
    cidr_block = "1.0.3.0/24"

    availability_zone = "ap-northeast-2a"

    tags = {
        Name = "terraform-private-sub1"
    }
}

resource "aws_subnet" "terraform_private_sub2"{
    vpc_id = aws_vpc.main.id
    cidr_block = "1.0.4.0/24"

    availability_zone = "ap-northeast-2b"

    tags = {
        Name = "terraform-private-sub2"
    }
}

// private subnet 연결을 위한 eip 구성

resource "aws_eip" "nat1" {
    vpc = true

    lifecycle {
        create_before_destroy = true
    }
}

resource "aws_eip" "nat2" {
    vpc = true

    lifecycle {
        create_before_destroy = true
    }
}

// nat gateway 구성

resource "aws_nat_gateway" "nat_gateway_1"{
    allocation_id = aws_eip.nat1.id

    subnet_id = aws_subnet.terraform_sub1.id

    tags = {
        Name = "nat-gateway-1"
    }
}

resource "aws_nat_gateway" "nat_gateway_2"{
    allocation_id = aws_eip.nat2.id

    subnet_id = aws_subnet.terraform_sub2.id

    tags = {
        Name = "nat-gateway-2"
    }
}

Terraform 왜 쓰는거지?

AWS 플랫폼을 이용하여 서울 리전에서 하나의 VPC를 구축한 코드입니다.

테라폼을 처음 사용하여 코드를 작성하고 VPC를 구축하다보니 서로간의 연결이 미흡하고 부족할 수 있습니다.

처음엔 테라폼이 무엇인지 알지 못했고, 기존 AWS를 이용하며 클릭과 무한 복사 붙이기를 통해 환경을 사용하는데 급급했습니다.

테라폼 코드를 작성하고 실제로 동작해본결과 해당 VPC란에 각각의 구성요소들이 연결되는 것을 볼 수 있었고, 클릭클릭으로 인한 aws 서비스 사용이 아닌 코드로 인해 간편하게 자동화하여 구축하는데 있어 기존보다 편리함을 느낄 수 있었습니다.