main.tf
//aws vpc를 생성하는 역할의 resource이다.
resource "aws_vpc" "test_vpc" {
cidr_block = var.vpc.cidr
tags = {
Name = var.vpc.Name
terraform = var.vpc.terraform
}
}
// 위에서 생성하는 vpc의 id를 참조하여 참조한 vpc내부에 서브넷을 생성한다.
resource "aws_subnet" "test_subnet" {
//참조할 vpc id를 넣어준다.
vpc_id = aws_vpc.test_vpc.id
// for_each를 통해서 여러개의 서브넷을 동시에 만들어준다.
for_each = { for k, v in var.subnet_variables.subnet : k => v }
cidr_block = each.value
tags = {
Name = var.subnet_variables.name[each.key]
terraform = var.subnet_variables.terraform[0]
}
}
//참조한 vpc에 인터넷 통신을 위한 게이트웨이를 만들어준다.
resource "aws_internet_gateway" "gw" {
//참조할 vpc id를 넣어줍니다.
vpc_id = aws_vpc.test_vpc.id
tags = {
Name = var.Internet_gw.Name
terraform = var.Internet_gw.terraform
}
}
// 위에서 생성한 게이트웨이를 vpc내부의 routetable에서 누구나(0.0.0.0/0) 접근할 수 있게 설정해준다.
resource "aws_route" "r" {
route_table_id = aws_vpc.test_vpc.default_route_table_id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
variable.tf
//main.tf에서 쓰이는 resource들에서 쓰이는 변수들을 모아놓은 맵 형식의 변수이다.
variable "vpc" {
type = map(any)
default = {
cidr = "10.1.0.0/16"
Name = "test_vpc"
terraform = "madeByTerraform_jj"
}
}
variable "subnet_variables" {
type = map(any)
default = {
subnet = ["10.1.1.0/24", "10.1.2.0/24", "10.1.3.0/24", "10.1.4.0/24"],
name = ["test_subnet1", "test_subnet2", "test_subnet3", "test_subnet4"],
terraform = ["madeByTerraform_jj"],
}
}
variable "test_route_table" {
type = map(any)
default = {
Name = "test_route_table"
terraform = "madeByTerraform_jj"
}
}
variable "Internet_gw" {
type = map(any)
default = {
Name = "test_gateway"
terraform = "madeByTerraform_jj"
}
}
provider.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.22.0"
}
}
}
provider "aws" {
region = "ap-northeast-2"
}
output.tf
output "vpc_id" {
value = {
VPC_ID = aws_vpc.test_vpc.id,
default_RouteTable_id = aws_vpc.test_vpc.default_route_table_id
}
}
output "subnet_id" {
value = [
aws_subnet.test_subnet
]
}
output "gateway_id" {
value = aws_internet_gateway.gw.id
}
aws 인증정보 확인'
aws configure
디렉토리 생성 및 테라폼 파일 생성
테라폼이 작업할 디렉토리와 코드가 담길 파일을 생성해주고 위에 있는 sample code를 각 파일 이름에 맞게 옮겨줍니다.
귀찮으면 한 파일에 넣어놔도 무방함
확장자는 .tf를 지킬 것
mkdir test1
vi main.tf
vi variable.tf
vi provider.tf
vi output.tf
terraform init, plan, apply
각 역할은 다음과 같습니다.
terraform init
terraform plan
terraform apply -auto-approve
결과 화면
다음과 같은 결과화면이 나오면 성공적으로 생성이 된 것이다.
aws_route.r: Creation complete after 1s [id=********id가려놓았어요******]
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
Outputs:
....
output.tf에서 작성한 내용에 따라 json형식으로 내용이 출력된다.
작성한 파일대로 진행을 했다면 AWS console에서 새로 생성된 vpc의 tag를 확인해보면 "terraform=madeByTerraform_jj"라고 태깅된 vpc, 서브넷 등을 확인할 수 있을 것이다.
인프라 삭제
terraform destroy
....