brunch
매거진 테라폼 AWS

32탄-2. 1주 차 - 테라폼 -EC2-2023

by Master Seo


목표

테라폼으로 EC2 생성 , 웹서비스 올리기

웹서버에 보안 그룹 적용하기

웹 서비스 포트 변경하기


선수조건

사전에 명령을 내릴 EC2가 1대 있어야 한다.




<1> 테라폼으로 웹서버 EC2 생성 , 웹서비스 하기

<2> 웹 서버 보안 그룹 적용

<3> 웹 서비스 포트 변경



<1> 테라폼으로 웹서버 EC2 생성 , 웹서비스 하기


0

터미널2에서 ec2 모니터링


while true; do aws ec2 describe-instances --query "Reservations[*].Instances[*].{PublicIPAdd:PublicIpAddress,InstanceName:Tags[?Key=='Name']|[0].Value,Status:State.Name}" --filters Name=instance-state-name,Values=running --output text ; echo "------------------------------" ; sleep 2; done



1

명령서버 에서


cd workspace

mkdir 1w

cd 1w



2

cat <<EOT > main.tf

provider "aws" {

region = "ap-northeast-2"

}


resource "aws_instance" "example" {

ami = "ami-0c9c942bd7bf113a2"

instance_type = "t2.micro"


user_data = <<-EOF

#!/bin/bash

echo "Hello, T101 Study" > index.html

nohup busybox httpd -f -p 8080 &

EOF


tags = {

Name = "terraform-Study-101"

}

}

EOT



//provider = aws

// resource = aws언더바 인스턴스 , 이름

// user_data = web 데몬으로 8080 띠우는 설정임, 웹서버

// 테그 설정함.




3

terraform init

terraform plan

terraform apply



4

다른 터미널에서 접근 시도 ?


# [터미널3] 변수 지정

PIP=<각자 자신의 EC2 Public IP>


PIP=54.180.29.38

while true; do curl --connect-timeout 1 http://$PIP:8080/ ; echo "------------------------------"; date; sleep 1; done


안됨



5

해결?

보안그룹 추가




<2> 웹 서버 보안 그룹 적용


1


cat <<EOT > main.tf

provider "aws" {

region = "ap-northeast-2"

}

resource "aws_instance" "example" {

ami = "ami-0e9bfdb247cc8de84"

instance_type = "t2.micro"

vpc_security_group_ids = [aws_security_group.instance.id]

user_data = <<-EOF

#!/bin/bash

echo "Hello, T101 Study" > index.html

nohup busybox httpd -f -p 8080 &

EOF

tags = {

Name = "aws-tts-seou-web02"

}

}

resource "aws_security_group" "instance" {

name = var.security_group_name

ingress {

from_port = 8080

to_port = 8080

protocol = "tcp"

cidr_blocks = ["0.0.0.0/0"]

}

}

variable "security_group_name" {

description = "The name of the security group"

type = string

default = "terraform-aws-tts-seoul-web02-sg"

}

output "public_ip" {

value = aws_instance.example.public_ip

description = "The public IP of the Instance"

}

EOT


// 인스턴스가 생성되면, 보안 그룹이 추가됨.

// var 변수 , 지정하지 않았다. 그래서 디폴트 값으로 사용한다.

//



2

# plan/apply


terraform plan

terraform apply -auto-approve




3

# 모니터링 : EC2 정보와 curl 접속 확인


# 새 EC2는 ip가 달라진다.


PIP=54.180.29.38

while true; do curl --connect-timeout 1 http://$PIP:8080/ ; echo "------------------------------"; date; sleep 1; done


(보안 그룹 적용되는데 1분 걸린다. 기다리자)




4

# (옵션) 리소스 생성 그래프 확인

terraform graph


# graph 확인 > 파일 선택 후 오른쪽 상단 DOT 클릭

terraform graph > graph.dot




<3> 웹 서비스 포트 변경


웹서비스 포트 8080을 9090 포트로 변경



1

userdata 값을 변경시에는 ec2 replace 해야 한다.

새로 띠우면서 적용하겠다.



cat <<EOT > main.tf

provider "aws" {

region = "ap-northeast-2"

}

resource "aws_instance" "example" {

ami = "ami-0e9bfdb247cc8de84"

instance_type = "t2.micro"

vpc_security_group_ids = [aws_security_group.instance.id]

user_data = <<-EOF

#!/bin/bash

echo "Hello, T101 Study 9090" > index.html

nohup busybox httpd -f -p 9090 &

EOF

user_data_replace_on_change = true

tags = {

Name = "Single-WebSrv9090"

}

}

resource "aws_security_group" "instance" {

name = var.security_group_name

ingress {

from_port = 9090

to_port = 9090

protocol = "tcp"

cidr_blocks = ["0.0.0.0/0"]

}

}

variable "security_group_name" {

description = "The name of the security group"

type = string

default = "terraform-example-instance"

}

output "public_ip" {

value = aws_instance.example.public_ip

description = "The public IP of the Instance"

}

EOT




2

# 모니터링


while true; do aws ec2 describe-instances --query "Reservations[*].Instances[*].{PublicIPAdd:PublicIpAddress,InstanceName:Tags[?Key=='Name']|[0].Value,Status:State.Name}" --filters Name=instance-state-name,Values=running --output text ; echo "------------------------------" ; sleep 1; done



# plan

terraform plan


# aws_instance.example must be replaced

-/+ resource "aws_instance" "example" {

...

~ user_data = "d91ca31904077f0b641b5dd5a783401396ffbf3f" -> "f1a1c16060740d7be18475c067c120a0eed366da"

# forces replacement

...

Changes to Outputs:

~ public_ip = "43.201.8.225" -> (known after apply)


# apply

terraform apply -auto-approve




3

# 웹 서버 접속 시도 : 터미널3에서 실행

# process 올라오는데 시간이 1~2분 정도 소요되어서, ec2 생성되면 1~2분 정도 후에 curl 접속이 가능하다

# EC2 Public IP가 어떻게 되나요? 유지? 변경?

PIP=<각자 자신의 EC2 IP>


PIP=54.180.123.229

while true; do curl --connect-timeout 1 http://$PIP:9090/ ; echo "------------------------------"; date; sleep 1; done



terraform output

terraform output public_ip

terraform output -raw public_ip

PIP=$(terraform output -raw public_ip)

echo $PIP

curl $PIP:9090

while true; do curl --connect-timeout 1 http://$PIP:9090/ ; echo "------------------------------"; date; sleep 1; done



# 아웃풋 블럭을 만들어 놓았다.

# 변수 값으로 만들었다.



4

테라폼의 기본 속성은 이뮤터블 하다. = 새로 생성 된다.



5

삭제

# 리소스 삭제

terraform destroy -auto-approve





6

(참고)

앤서블과 연동 가능

https://github.com/ansible/terraform-provider-ansible/tree/main


테라폼은 기본 구축을 하고, 서버 상세 변경은 앤서블로 하라.






15분 휴식


https://vclock.kr/timer/#countdown=00:10:00&enabled=0&seconds=0&sound=xylophone&loop=1



다음 자료

https://brunch.co.kr/@topasvga/3346




참고자료

2023 자료 - 몰아 보기

https://brunch.co.kr/@topasvga/3347


terraform.png

다음은 주말 CloudNet 테라폼 스터디 내용 참고하여 정리한 부분입니다.

https://gasidaseo.notion.site/gasidaseo/CloudNet-Blog-c9dfa44a27ff431dafdd2edacc8a1863



감사합니다.




keyword
매거진의 이전글32탄-1. 1주 차 - 테라폼-사용환경-2023