Home
home

0장 실습 - Terraform으로 AWS 자원 배포하기

1. 기본 환경 구성

이번 실습은 Terraform 도구로 AWS 자원을 배포하는 실습으로 사용자 PC에서 기본 환경 구성을 진행합니다.
또한, IAM 사용자 계정을 통해 관리 콘솔에 접근하고 액세스 키를 활용해 awscli 도구를 사용합니다.
해당 작업을 수행하지 않았다면 아래 토글을 확장해 작업을 선행하고 본격적인 실습에 들어갑니다.
IAM 사용자 생성 및 액세스 키 생성

1.1. 실습 도구 설치

실습 진행을 위해 terraformawscliv2를 설치하고 환경 구성을 합니다.
Mac OS 환경과 Windows OS 환경을 구분해서 실습 도구 설치 방법을 정의합니다.
[사용자 PC - Mac OS] Terraform 설치
brew install tfenv
Bash
복사
# tfenv 설치
tfenv list-remote
Bash
복사
# 설치 가능 버전 리스트 확인
tfenv install 1.11.2
Bash
복사
# Terraform 1.11.2 버전 설치
tfenv use 1.11.2
Bash
복사
# Terraform 1.11.2 버전 사용 설정
tfenv list
Bash
복사
# tfenv로 설치한 버전 확인
terraform version
Bash
복사
# Terraform 버전 확인
[사용자 PC - Mac OS] awscliv2 설치
brew install awscli
Bash
복사
# brew로 awscli 설치
which aws
Bash
복사
# awscli가 설치된 경로
aws --version
Bash
복사
# awscli 버전 확인
aws configure
Bash
복사
# awscli 인증 설정
Note:
aws configure 명령으로 IAM User에 대한 Credential을 정의합니다.
(AWS Access Key ID, AWS Secret Access Key, Default Region)
aws sts get-caller-identity --query Arn aws s3 ls
Bash
복사
# awscli 명령 확인
[사용자 PC - Windows OS] Terraform 설치
2.
다운로드 받은 파일을 압축 해제 합니다.
3.
해당 경로에 대해 환경 변수를 수정하여 추가합니다.
내 PC → (마우스 우측) 속성 → 고급 시스템 설정 → 환경 변수 → 시스템 환경 변수 편집 → 경로 추가
[사용자 PC - Windows OS] Cygwin64 설치
Install from Internet → 다음
Root Directory (경로 지정 후) → 다음
Local Package Directory (경로 지정 후) → 다음
Direct Connection → 다음
https://ftp.kr.freebsd.org 선택 → 다음
별도의 패키지를 선택하지 않고 기본 상태로 설치합니다.
마침
[사용자 PC - Windows OS] awscliv2 설치
https://awscli.amazonaws.com/AWSCLIV2.msi를 다운로드하고 설치합니다.
[사용자 PC - Windows OS] git 설치
Standalone Installer에서 적절한 파일을 다운로드하고 설치합니다.
[사용자 PC - Windows OS] 설치 확인 및 설정
terraform version
Bash
복사
# [cygwin64] Terraform 버전 확인
aws --version
Bash
복사
# [cygwin64] awscli 버전 확인
aws configure
Bash
복사
# [cygwin64] awscli 인증 설정
Note:
aws configure 명령으로 IAM User에 대한 Credential을 정의합니다.
(AWS Access Key ID, AWS Secret Access Key, Default Region)
aws sts get-caller-identity --query Arn aws s3 ls
Bash
복사
# [cygwin64] awscli 명령 확인
git version
Bash
복사
# [cygwin64] git 버전 확인

1.2. 실습 코드 다운로드

Amazon EKS 확장판 강의의 실습을 위한 코드를 다운로드합니다.
git clone - 실습 코드
git clone https://github.com/cloudneta/cnaee_class_tf
Bash
복사
# git clone - cnaee_class_tf
cd cnaee_class_tf
Bash
복사
# 실습 코드 경로 진입
ls -al
Bash
복사
# 실습 코드 경로 확인

2. Terraform 자원 배포 및 확인

2.1. 기본 사용법

Terraform 코드로 VPC와 보안 그룹과 EC2 인스턴스를 배포하고 확인하는 실습입니다.
1.
vpc.tf 생성
vpc.tf 파일 생성
mkdir my-vpc-ec2 cd my-vpc-ec2
Bash
복사
# 신규 디렉터리 생성
cat << EOF > vpc.tf provider "aws" { region = "ap-northeast-2" } resource "aws_vpc" "myvpc" { cidr_block = "10.10.0.0/16" tags = { Name = "t101-study" } } EOF cat vpc.tf
Bash
복사
# vpc.tf 파일 생성 및 확인
Terraform 배포 및 확인
terraform init
Bash
복사
# terraform init
terraform plan
Bash
복사
# terraform plan
terraform apply -auto-approve
Bash
복사
# terraform apply
terraform state list
Bash
복사
# terraform state list
terraform state show aws_vpc.myvpc
Bash
복사
# state 확인 (aws_vpc.myvpc)
export AWS_PAGER="" aws ec2 describe-vpcs aws ec2 describe-vpcs --filter 'Name=isDefault,Values=false' aws ec2 describe-vpcs --filter 'Name=isDefault,Values=false' --output yaml
Bash
복사
# awscli로 VPC 확인
AWS 관리 콘솔에서 VPC 생성 정보를 확인하고, DNS 옵션 값을 확인합니다.
2.
vpc.tf 수정 - VPC DNS 옵션 활성화
vpc.tf 파일 수정 - VPC DNS 옵션 활성화
cat << EOF > vpc.tf provider "aws" { region = "ap-northeast-2" } resource "aws_vpc" "myvpc" { cidr_block = "10.10.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "t101-study" } } EOF cat vpc.tf
Bash
복사
# vpc.tf 수정 및 확인
terraform plan && terraform apply -auto-approve
Bash
복사
# Terraform 배포
AWS 관리 콘솔에서 VPC 생성 정보를 확인하고, DNS 옵션 값을 확인합니다.
3.
vpc.tf 수정 - 서브넷 2개 생성
vpc.tf 파일 수정 - 서브넷 2개 생성
cat << EOF > vpc.tf provider "aws" { region = "ap-northeast-2" } resource "aws_vpc" "myvpc" { cidr_block = "10.10.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "t101-study" } } resource "aws_subnet" "mysubnet1" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.1.0/24" availability_zone = "ap-northeast-2a" tags = { Name = "t101-subnet1" } } resource "aws_subnet" "mysubnet2" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.2.0/24" availability_zone = "ap-northeast-2c" tags = { Name = "t101-subnet2" } } output "aws_vpc_id" { value = aws_vpc.myvpc.id } EOF cat vpc.tf
Bash
복사
# vpc.tf 수정 및 확인
terraform plan && terraform apply -auto-approve terraform state list terraform state show aws_subnet.mysubnet1
Bash
복사
# Terraform 배포 및 State 확인
terraform output terraform output aws_vpc_id terraform output -raw aws_vpc_id
Bash
복사
# terraform output 확인
aws ec2 describe-subnets --output text
Bash
복사
# awscli로 서브넷 확인
VPCID=$(terraform output -raw aws_vpc_id); echo $VPCID aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPCID" aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPCID" --output table
Bash
복사
# VPCID 변수 선언 및 awscli로 VPC 정보 확인
4.
vpc.tf 수정 - 인터넷 게이트웨이 생성
vpc.tf 파일 수정 - 인터넷 게이트웨이 생성
cat << EOF > vpc.tf provider "aws" { region = "ap-northeast-2" } resource "aws_vpc" "myvpc" { cidr_block = "10.10.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "t101-study" } } resource "aws_subnet" "mysubnet1" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.1.0/24" availability_zone = "ap-northeast-2a" tags = { Name = "t101-subnet1" } } resource "aws_subnet" "mysubnet2" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.2.0/24" availability_zone = "ap-northeast-2c" tags = { Name = "t101-subnet2" } } resource "aws_internet_gateway" "myigw" { vpc_id = aws_vpc.myvpc.id tags = { Name = "t101-igw" } } output "aws_vpc_id" { value = aws_vpc.myvpc.id } EOF cat vpc.tf
Bash
복사
# vpc.tf 수정 및 확인
terraform plan && terraform apply -auto-approve terraform state list terraform state show aws_internet_gateway.myigw
Bash
복사
# Terraform 배포 및 State 확인
5.
vpc.tf 수정 - 디폴트 라우팅 추가
vpc.tf 파일 수정 - 디폴트 라우팅 생성
cat << EOF > vpc.tf provider "aws" { region = "ap-northeast-2" } resource "aws_vpc" "myvpc" { cidr_block = "10.10.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "t101-study" } } resource "aws_subnet" "mysubnet1" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.1.0/24" availability_zone = "ap-northeast-2a" tags = { Name = "t101-subnet1" } } resource "aws_subnet" "mysubnet2" { vpc_id = aws_vpc.myvpc.id cidr_block = "10.10.2.0/24" availability_zone = "ap-northeast-2c" tags = { Name = "t101-subnet2" } } resource "aws_internet_gateway" "myigw" { vpc_id = aws_vpc.myvpc.id tags = { Name = "t101-igw" } } resource "aws_route_table" "myrt" { vpc_id = aws_vpc.myvpc.id tags = { Name = "t101-rt" } } resource "aws_route_table_association" "myrtassociation1" { subnet_id = aws_subnet.mysubnet1.id route_table_id = aws_route_table.myrt.id } resource "aws_route_table_association" "myrtassociation2" { subnet_id = aws_subnet.mysubnet2.id route_table_id = aws_route_table.myrt.id } resource "aws_route" "mydefaultroute" { route_table_id = aws_route_table.myrt.id destination_cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.myigw.id } output "aws_vpc_id" { value = aws_vpc.myvpc.id } EOF cat vpc.tf
Bash
복사
# vpc.tf 수정 및 확인
terraform plan && terraform apply -auto-approve terraform state list terraform state show aws_route.mydefaultroute
Bash
복사
# Terraform 배포 및 State 확인
aws ec2 describe-route-tables --filters 'Name=tag:Name,Values=t101-rt' --output table
Bash
복사
# awscli로 라우팅 테이블 확인
6.
sg.tf 생성
sg.tf 파일 생성 및 확인
cat << EOF > sg.tf resource "aws_security_group" "mysg" { vpc_id = aws_vpc.myvpc.id name = "T101 SG" description = "T101 Study SG" } resource "aws_security_group_rule" "mysginbound" { type = "ingress" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] security_group_id = aws_security_group.mysg.id } resource "aws_security_group_rule" "mysgoutbound" { type = "egress" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] security_group_id = aws_security_group.mysg.id } output "aws_security_group_id" { value = aws_security_group.mysg.id } EOF cat sg.tf
Bash
복사
# sg.tf 파일 생성 및 확인
ls *.tf terraform plan && terraform apply -auto-approve terraform state list terraform state show aws_security_group.mysg terraform state show aws_security_group_rule.mysginbound
Bash
복사
# Terraform 배포 및 State 확인
terraform output -raw aws_security_group_id aws ec2 describe-security-groups --group-ids $(terraform output -raw aws_security_group_id)
Bash
복사
# awscli로 생성한 보안 그룹 확인
7.
ec2.tf 생성
ec2.tf 파일 생성 및 확인
cat << EOF > ec2.tf data "aws_ami" "my_amazonlinux2" { most_recent = true filter { name = "owner-alias" values = ["amazon"] } filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-ebs"] } owners = ["amazon"] } resource "aws_instance" "myec2" { depends_on = [ aws_internet_gateway.myigw ] ami = data.aws_ami.my_amazonlinux2.id associate_public_ip_address = true instance_type = "t2.micro" vpc_security_group_ids = ["\${aws_security_group.mysg.id}"] subnet_id = aws_subnet.mysubnet1.id user_data = <<-EOF2 #!/bin/bash wget https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-x86_64 mv busybox-x86_64 busybox chmod +x busybox echo "<h1>Web Server</h1>" > index.html nohup ./busybox httpd -f -p 80 & EOF2 user_data_replace_on_change = true tags = { Name = "t101-myec2" } } output "myec2_public_ip" { value = aws_instance.myec2.public_ip description = "The public IP of the Instance" } EOF cat ec2.tf
Bash
복사
# ec2.tf 파일 생성 및 확인
ls *.tf terraform plan && terraform apply -auto-approve terraform state list terraform state show data.aws_ami.my_amazonlinux2 terraform state show aws_instance.myec2
Bash
복사
# Terraform 배포 및 State 확인
terraform console
Bash
복사
# 데이터소스 값 확인
data.aws_ami.my_amazonlinux2 data.aws_ami.my_amazonlinux2.id data.aws_ami.my_amazonlinux2.image_id data.aws_ami.my_amazonlinux2.name data.aws_ami.my_amazonlinux2.owners data.aws_ami.my_amazonlinux2.platform_details data.aws_ami.my_amazonlinux2.hypervisor data.aws_ami.my_amazonlinux2.architecture exit
Bash
복사
terraform output -raw myec2_public_ip MYIP=$(terraform output -raw myec2_public_ip); echo $MYIP curl http://$MYIP
Bash
복사
# 출력된 EC2 퍼블릭IP로 cul 접속 확인
8.
Terraform 배포 자원 삭제
Terraform 배포 자원 삭제
terraform destroy -auto-approve
Bash
복사
# terraform destroy

2.2. Terraform 배포 및 확인

다운로드한 실습 코드를 통해 Terraform 배포 및 확인 작업을 수행합니다.
실습 경로 진입 및 확인
cd .. cd ch0
Bash
복사
# 실습 경로 진입
ls -al
Bash
복사
# 실습 경로에 terraform 코드 확인
Note: 구성된 .tf 파일을 확인 합니다. (var.tf, ec2.tf, vpc.tf, out.tf)
terraform init
terraform init
Bash
복사
# terraform init 명령 수행
ls -al
Bash
복사
# 실습 경로 확인 (숨은 파일/디렉터리 포함)
terraform plan
terraform plan
Bash
복사
# terraform plan 명령 수행
Note:
KeyName과 SgIngressSshcidr([사용자 PC의 퍼블릭 IP 주소]/32)를 입력합니다.
사용자 PC의 퍼블릭 IP 주소는 curl -s ipinfo.io/ip로 확인합니다.
terraform apply
export TF_VAR_KeyName=[각자 SSH 키 페어] export TF_VAR_SgIngressSshCidr=$(curl -s ipinfo.io/ip)/32
Bash
복사
# TF_VAR 변수 선언
terraform apply -auto-approve
Bash
복사
# terraform apply 명령 수행
Note:
terraform apply 명령을 수행하면 Terraform이 실행할 변경 사항에 대한 승인을 물어봅니다. (yes!)
Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value:
Bash
복사
-auto-approve 옵션을 추가하면 자동으로 승인을 처리합니다.
ls -al
Bash
복사
# 실습 경로 확인 (숨은 파일/디렉터리 포함)
생성된 자원 확인
terraform state list
Bash
복사
# terraform state list 확인
terraform state show 'module.vpc.aws_vpc.this[0]' | grep -w 'id' | awk '{print $3}' | tr -d '"' VPC_ID=$(terraform state show 'module.vpc.aws_vpc.this[0]' | grep -w 'id' | awk '{print $3}' | tr -d '"'); echo $VPC_ID
Bash
복사
# VPC_ID 변수 선언
aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" \ --query "Subnets[*].[SubnetId, CidrBlock, AvailabilityZone]" \ --output table
Bash
복사
# VPC 내 서브넷 정보 확인
aws ec2 describe-security-groups --filters "Name=vpc-id,Values=$VPC_ID" \ --query "SecurityGroups[*].[GroupId, GroupName, Description]" \ --output table
Bash
복사
# VPC 내 보안 그룹 정보 확인
terraform output -raw public_ip BASTION_IP=$(terraform output -raw public_ip); echo $BASTION_IP curl http://$BASTION_IP
Bash
복사
# EC2 인스턴스 퍼블릭 IP 변수 선언 및 접속

3. 실습 환경 삭제

Terraform 배포 자원 삭제
terraform destroy -auto-approve
Bash
복사
# terraform destroy 명령
기본 사용법 테스트 삭제
cd .. rm -rf my-vpc-ec2 ls -al
Bash
복사
# my-vpc-ec2 경로 삭제
여기까지 Terraform으로 AWS 자원 배포 실습을 마칩니다.
수고하셨습니다 :)