brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Sep 19. 2024

AWS 53탄-17.테라폼으로 EC2 1대 -2024

<1> 클라우드 포메이션으로 명령서버 1대 만들기

<2> 디폴트 VPC에  테라폼으로 EC2 1대 만들어보자.

<3> 서버명 설정하기

<4> 보안그룹

<5> EC2 접속용  pem키 만들기

<6> 10.대 VPC에  테라폼으로 EC2 1대 만들어보자.



<1> 클라우드 포메이션으로 명령서버 1대 만들기


1


구성도







2

테라폼 명령서버 1대 만들기


명령서버 1대 생성을 위한 준비물

ec2 키페어 필요  

서울리전

EC2 > Network & Security > Key Pairs >  CREATE Key pair   

PPK   - 내 pc는 windows , putty로 접속 할 예정이라 ppk 사용

agame-dev-2024-09-23



access-key, secret-key 필요  

IAM

agame-dev-2024-09-23-user

admin

access-key 생성





3

진행 ?

cloudformation으로 명령서버 1대 만들자.

자동으로 만들어보자.

서울리전 선택





<2> 디폴트 VPC에  테라폼으로 EC2 1대 만들어보자.



1

명령 ec2 로그인



2

아마존 리눅스에 테라폼 설치

amazon linux 테라폼 설치


sudo yum install -y yum-utils

sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo

sudo yum -y install terraform

terraform version




3

aws의 디폴트 vpc로 사용함.

삭제 하지 않았다면 디폴트 VPC는 있습니다.



4

디폴트 vpc 없다면?

AWS 콘솔에서 디폴트 vpc 생성가능함.

AWS CLI 로 디폴트 vpc 생성 가능함.



5

콘솔에서 디폴트 네트워크 생성법 ?


aws 콘솔 로그인

https://console.aws.amazon.com/


VPC > Your VPCs > 오른쪽위 ACTION > CREATE DEFAULT VPC  클릭




6

테라폼으로 EC2 1대  생성해 보자.


cat <<EOT > main.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami           = "ami-0a0064415cdedc552"

  instance_type = "t2.micro"

}

EOT


terraform init

#초기화 , 각종 라이블러리를 불러옴.


terraform plan

#계획



terraform apply -auto-approve




<3> 서버명 설정하기



1

서버명 설정


cat <<EOT > main.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami           = "ami-0a0064415cdedc552"

  instance_type = "t2.micro"

  tags = {

    Name = "t101-study"

  }

}

EOT


terraform apply -auto-approve




2

삭제 ?


삭제 자동 승인

terraform destroy -auto-approve





<4> 보안그룹



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 80 &

              EOF

  tags = {

    Name = "aws-tts-seou-web02"

  }

}

resource "aws_security_group" "instance" {

  name = var.security_group_name

  ingress {

    from_port   = 80

    to_port     = 80

    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



terraform apply -auto-approve




2

aws0tts-seou-web02



새로 생성하면 ip가 변경된다.

PIP=<새로 만들어진  EC2 Public IP>  = 콘솔에서 확인하자!!



PIP=13.124.123.216

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

sleep 1; done





<5> EC2 접속용  pem키 만들기


1

[root@myeks2-bastion-EC2 seo]#

[root@myeks2-bastion-EC2 seo]# ls

1backup  create_key.tf  main.tf  terraform_key.pem  terraform.tfstate  terraform.tfstate.backup

[root@myeks2-bastion-EC2 seo]#

[root@myeks2-bastion-EC2 seo]# more *.tf

::::::::::::::

create_key.tf

::::::::::::::

# RSA key of size 4096 bits

resource "tls_private_key" "terraform_make_key" {

  algorithm = "RSA"

  rsa_bits  = 4096

}

resource "aws_key_pair" "terraform_make_keypair" {

  key_name = "terraform_key"

  public_key=tls_private_key.terraform_make_key.public_key_openssh

}

resource "local_file" "terraform_downloads_key" {

  filename = "terraform_key.pem"

  content = tls_private_key.terraform_make_key.private_key_pem

}

::::::::::::::

main.tf

::::::::::::::

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-0c031a79ffb01a803"

  instance_type          = "t3.medium"

  key_name = aws_key_pair.terraform_make_keypair.key_name

  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 80 &

              EOF

  tags = {

    Name = "aws-tts-seou-web02"

  }

}

resource "aws_security_group" "instance" {

  name = var.security_group_name

  ingress {

    from_port   = 22

    to_port     = 22

    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"

}

[root@myeks2-bastion-EC2 seo]



다운로드



2

ssh -i terraform_key.pem ec2-user@13.125.57.190






3

삭제

terraform destroy -auto-approve



4

콘솔에서 디폴트 VPC 삭제하기






참고 자료

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






<6> 10.대 VPC에  테라폼으로 EC2 1대 만들어보자.




cd

mkdir vpc

cd vpc



vi  vpc.tf


provider "aws" {

  region  = "ap-northeast-2"

}


resource "aws_vpc" "myvpc" {

  cidr_block       = "10.10.0.0/16"


  tags = {

    Name = "t101-study-vpc"

  }

}



2

# 배포, 확인

 terraform init && terraform plan && terraform apply -auto-approve




# 혹, lock 걸린다고 나오면 테라폼 프로세스를  kill  하고 사용하기 바란다.


[root@myeks2-bastion-EC2 vpc]# ps -ef |grep terraform

root     23765 20220  0 09:01 pts/0    00:00:04 terraform console

root     26841 20220  0 09:32 pts/0    00:00:00 grep --color=auto terraform


[root@myeks2-bastion-EC2 vpc]# kill -9 23765



아래는 임시 조치법

 terraform apply -auto-approve -lock=false




terraform state list

aws_vpc.myvpc



terraform state show aws_vpc.myvpc



3

테리폼 콘솔 명령어로 보기


terraform console


// aws_vpc.myvpc.id   로 정보를 볼수 있다.


aws_vpc.myvpc.id

"vpc-0ebc8fe6e0d524570"



4

# VPC 확인

export AWS_PAGER=""

aws ec2 describe-vpcs | jq

aws ec2 describe-vpcs --filter 'Name=isDefault,Values=false' | jq

aws ec2 describe-vpcs --filter 'Name=isDefault,Values=false' --output yaml


// default vpc  는  조회 안하도록 필터링해서 조회하자.






5

rm -rf vpc.tf



vpc dns 옵션 수정


vi main.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-vpc"

  }

}


terraform init && terraform plan && terraform apply -auto-approve




// 콘솔   vpc 에서 확인하자.

// 콘솔   vpc  >  Resource map에서 확인하자.  서브넷이 없다.




6

//  VCP + Subnet 만들기

// vpc 1개, 서브넷 1, 서브넷 2



provider "aws" {

  region  = "ap-northeast-2"oo

}


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-pub1"

  }

}


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-pub2"

  }

}


output "aws_vpc_id" {

  value = aws_vpc.myvpc.id

}


// vpc_id 는  aws_vpc.myvpc,id 를 가져와서 사용한다.

// 콘솔 >  vpc  Resource map에서 확인하자.




7

# 배포

terraform plan && terraform apply -auto-approve


terraform state list

aws_subnet.mysubnet1

aws_subnet.mysubnet2

aws_vpc.myvpc


// vpc 1개, 서브넷 1, 서브넷 2




terraform state show aws_subnet.mysubnet1


terraform output

terraform output aws_vpc_id

terraform output -raw aws_vpc_id


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

terraform graph > graph.dot


# 서브넷 확인

aws ec2 describe-subnets --output text


# 참고 : 

aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-<자신의 VPC ID>"

VPCID=$(terraform output -raw aws_vpc_id)

aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPCID" | jq

aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPCID" --output table




8

igw 추가  ?


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

}




9

# 배포

terraform plan && terraform apply -auto-approve

terraform state list

aws_internet_gateway.myigw

aws_subnet.mysubnet1

aws_subnet.mysubnet2

aws_vpc.myvpc




10

디폴트 라우팅 추가  ?


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

}



// 라우팅 테이블을 만들고,  연결 한다.





11

# 배포

terraform plan && terraform apply -auto-approve




terraform state list


aws_internet_gateway.myigw

aws_route.mydefaultroute

aws_route_table.myrt

aws_route_table_association.myrtassociation1

aws_route_table_association.myrtassociation2

aws_subnet.mysubnet1

aws_subnet.mysubnet2

aws_vpc.myvpc




terraform state show aws_route.mydefaultroute


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

terraform graph > graph.dot


# 라우팅 테이블 확인

#aws ec2 describe-route-tables --filters 'Name=tag:Name,Values=t101-rt' --query 'RouteTables[].Associations[].SubnetId'

aws ec2 describe-route-tables --filters 'Name=tag:Name,Values=t101-rt' --output table




12

보안그룹  = sg.tf  

ec2  = ec2.tf



vi 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

}



# 배포

ls *.tf

terraform plan && terraform apply -auto-approve

terraform state list

aws_security_group.mysg

aws_security_group_rule.mysginbound

aws_security_group_rule.mysgoutbound

...


terraform state show aws_security_group.mysg

terraform state show aws_security_group_rule.mysginbound


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

terraform graph > graph.dot





13

ec2 배포


vi 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 = <<-EOF

              #!/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

              RZAZ=$(curl http://169.254.169.254/latest/meta-data/placement/availability-zone-id)

              IID=$(curl 169.254.169.254/latest/meta-data/instance-id)

              LIP=$(curl 169.254.169.254/latest/meta-data/local-ipv4)

              echo "<h1>RegionAz($RZAZ) : Instance ID($IID) : Private IP($LIP) : Web Server</h1>" > index.html

              nohup ./busybox httpd -f -p 80 &

              EOF


  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"

}





t101-myec2가 생성된다.




# 다음은 설명 


//   ami                         = data.aws_ami.my_amazonlinux2.id 

ami를 가져 온다.


//  subnet_id                   = aws_subnet.mysubnet1.id  

서브넷 id를 확인한다.





ls *.tf

terraform plan && terraform apply -auto-approve

terraform state list

data.aws_ami.my_amazonlinux2

aws_instance.myec2

...


terraform state show data.aws_ami.my_amazonlinux2

terraform state show aws_instance.myec2




# 데이터소스 값 확인

terraform console

data.aws_ami.my_amazonlinux2.id

"ami-01c81850a6167bb81"


// ami 정보가 나온다.




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




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

terraform graph > graph.dot


# 출력된 EC2 퍼블릭IP로 cul 접속 확인

terraform output -raw myec2_public_ip

52.79.154.3



MYIP=$(terraform output -raw myec2_public_ip)

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


Mon Jul 10 17:03:00 KST 2023

<h1>RegionAz(apne2-az1) : Instance ID(i-064948a0afaa3a969) : Private IP(10.10.1.109) : Web Server</h1>

------------------------------

Mon Jul 10 17:03:01 KST 2023

<h1>RegionAz(apne2-az1) : Instance ID(i-064948a0afaa3a969) : Private IP(10.10.1.109) : Web Server</h1>

------------------------------

Mon Jul 10 17:03:02 KST 2023




14

삭제


terraform destroy -auto-approve





참고자료

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







다음

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


감사합니다.

매거진의 이전글 AWS 53탄-16. 클라우드포메이션-EKS -2024
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari