brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Oct 17. 2022

19탄-2. 테라폼-AWS- userdata 사용

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

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



<1> userdata  사용해 웹서버 만들자.

<2> 과제 1  

<3> 웹서버 설정 변경하기 -  userdata 변경하기

<4> 변수 사용

<5> 확인

<6> 과제 2

<7> 과제 1 풀이

<8> 과제 2 풀이

<9> 코드와 실제 형상이 다른 경우  - 형상 관리하기  (별도 작업)




<1> userdata  사용해 웹서버 만들자.


1

아마존 리눅스 AMI 사용해 만들어 보자.

ami-0425f132103cb3ed8


서울에


cat <<EOT > main.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-0425f132103cb3ed8"

  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




2

오레곤에


ami-08e2d37b6a012992  사용


cat <<EOT > main.tf

provider "aws" {

  region = "us-west-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-08e2d37b6a0129927"

  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




기타)

우분트 22.04 LTS 사용 -  ami-0e9bfdb247cc8de84

ap-northeast-2


백그라운드로 간단한 웹서버 띠우기

              echo "Hello, T101 Study" > index.html

              nohup busybox httpd -f -p 8080 &



2

terraform plan


3

terraform apply -auto-approve



4

# [터미널 3] 띠워 모니터링 하기

콘솔에서 EC2 공인 IP 확인


PIP=<각자 자신의 EC2 IP>

PIP=13.125.57.186

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




5

웹서버 접속 불가.

이유 보안 그룹.

보안 그룹에 허용 포트 8080 추가.



6

서울

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




7

오레곤


cat <<EOT > main.tf

provider "aws" {

  region = "us-west-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-08e2d37b6a0129927"

  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 = "Single-WebSrv"

  }

}

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-example-instance"

}

output "public_ip" {

  value       = aws_instance.example.public_ip

  description = "The public IP of the Instance"

}

EOT


//  aws_security_group.instance.id]   는 aws 보안그룹이 인스턴스에 들어오는것이다.

// resource "aws_instance" 은  AWS  인스턴스를 만드는 것이다.

// resource "aws_security_group"   은  AWS의 보안 그룹을 만드는 것이다.





6

terraform plan

terraform apply --auto-approve



7

보안 그룹은 id라는 정보를 내보내므로 이를 참조하는 표현식은 아래와 같음

aws_security_group.instance.id




<2> 과제 1  


우분트

Userdata 이용 EC2 웹서버 배포

닉네임 포함

테라폼 코드 작성하시요





<3>  웹서버 설정 변경하기 -  userdata 변경하기


1

웹서버 포트를 9090으로 변경해보자.

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

오레곤


cat <<EOT > main.tf

provider "aws" {

  region = "us-west-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-08e2d37b6a0129927"

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

  }

}

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

terraform plan

디스트로이하고 다시 만든다고 나온다. (주의)

아래 옵션으로 인해 다시 만든다.

 user_data_replace_on_change = true  



3

terraform apply -auto-approve


4

PIP=<각자 자신의 EC2 IP>

PIP=54.180.123.229

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



1차 타임아웃

Mon Oct 17 07:11:07 UTC 2022

curl: (28) Connection timeout after 1001 ms



적용후  index 보임


Mon Oct 17 09:58:54 UTC 2022

Hello, T101 Study

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

Mon Oct 17 09:58:55 UTC 2022

Hello, T101 Study

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

Mon Oct 17 09:58:56 UTC 2022

Hello, T101 Study





5

삭제

terraform destroy



6

웹서버 포트 변경 시 , 변수로 처리하기 ?


7

user_data_replace_on_change = no 인 경우 동작은?





<4> 변수 사용


변수 예시

https://github.com/brikis98/terraform-up-and-running-code/blob/master/code/terraform/02-intro-to-terraform-syntax/one-webserver-with-vars/variables.tf


https://github.com/moonjukhim/terraform_up_and_running/blob/master/02.intro-to-terraform-syntax/2.5.one-webserver-with-vars/variables.tf



1

웹서버 포트 변수로 처리하기


cat <<EOT > variables.tf

variable "server_port" {

  description = "The port the server will use for HTTP requests"

  type        = number

}

EOT



2

처리방법 4가지  


1)

변수 값으로 처리 ?

terraform plan


var.server_port

  The port the server will use for HTTP requests

  Enter a value: 8080


No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.


2)

-var 옵션

terraform plan -var "server_port=8080"


3)

환경 변수로 지정

export TF_VAR_server_port=8080

terraform plan


# 환경변수 확인

export | grep TF_VAR_


# 환경변수 지정 삭제

unset TF_VAR_server_port


4)

디폴트 값으로 처리

cat <<EOT > variables.tf

variable "server_port" {

  description = "The port the server will use for HTTP requests"

  type        = number

  default     = 8080

}

EOT


# plan

terraform plan




3

작업


cat <<EOT > variables.tf

variable "server_port" {

  description = "The port the server will use for HTTP requests"

  type        = number

  default     = 8080

}

EOT



4


cat <<EOT > main.tf

provider "aws" {

  region = "us-west-2"

}

resource "aws_instance" "example" {

  ami                    = "ami-08e2d37b6a0129927"

  instance_type          = "t2.micro"

  vpc_security_group_ids = [aws_security_group.instance.id]

  user_data = <<-EOF

              #!/bin/bash

              echo "My Web Server - var test" > index.html

              nohup busybox httpd -f -p \${var.server_port} &

              EOF

  user_data_replace_on_change = true

  tags = {

    Name = "Single-MyWebSrv"

  }

}

resource "aws_security_group" "instance" {

  name = var.security_group_name

  ingress {

    from_port   = var.server_port

    to_port     = var.server_port

    protocol    = "tcp"

    cidr_blocks = ["0.0.0.0/0"]

  }

}

variable "security_group_name" {

  description = "The name of the security group"

  type        = string

  default     = "terraform-my-instance"

}

output "public_ip" {

  value       = aws_instance.example.public_ip

  description = "The public IP of the Instance"

}

EOT


//   nohup busybox httpd -f -p \${var.server_port} &  에서

   \  빼고    nohup busybox httpd -f -p ${var.server_port} &  로 복사 해야 함.

mac에서는 \ 이 필요함.



5

terraform plan

terraform apply -auto-approve




<5> 확인



1


# 리소스 상태 확인

terraform state list

aws_instance.example

aws_security_group.instance


terraform state show aws_instance.example

terraform state show aws_security_group.instance



2

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


# [터미널3] 변수 PIP로 변경

PIP=<각자 자신의 EC2 IP>

PIP=13.125.57.186

PPT=8080

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


3

# 삭제

terraform destroy -auto-approve

terraform init






<6> 과제 2


과제 1에서 변수처리로 변경하세요.

50000번 포트 사용하세요.

테라폼 코드 작성하세요





<7> 과제 1 풀이



우분트

Userdata 이용 EC2 웹서버 배포

닉네임 포함

테라폼 코드 작성하시요




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

apt-get update -y

apt install apache2 -y

sudo systemctl start apache2.service

echo '<html><h1>Master seo  Web Server!</h1></html>' > /var/www/html/index.html              

              EOF

user_data_replace_on_change = true

  tags = {

    Name = "Single-WebSrv4"

  }

}

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

  }

  egress {

    protocol    = "-1"

    from_port   = 0

    to_port     = 0

    cidr_blocks = ["0.0.0.0/0"]

  }

}  

variable "security_group_name" {

  description = "The name of the security group"

  type        = string

  default     = "terraform-example-instance4"

}

output "public_ip" {

  value       = aws_instance.example.public_ip

  description = "The public IP of the Instance"

}

EOT



// userdata라 서버에서 실행이 되어야 해서 외부로 접속이 되어야 한다.

보안그룹 나가는건 모두 허용해야 한다는 뜻이다.

  egress {

    protocol    = "-1"

    from_port   = 0

    to_port     = 0

    cidr_blocks = ["0.0.0.0/0"]

  }






<8> 과제 2 풀이


과제 1에서 변수처리로 변경하세요.

50000번 포트 사용하세요.

테라폼 코드 작성하세요



1

변수


cat <<EOT > variables.tf

variable "server_port" {

  description = "The port the server will use for HTTP requests"

  type        = number

  default     = 50000

}

EOT





2


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

apt-get update -y

apt install apache2 -y

sudo sed -i "s/^Listen 80/Listen 50000/g" /etc/apache2/ports.conf

echo '<html><h1>Master seo 50000 port Web Server!</h1></html>' > /var/www/html/index.html  

sudo systemctl restart apache2.service

EOF

  tags = {

    Name = "Single-MyWebSrv8"

  }

}

resource "aws_security_group" "instance" {

  name = var.security_group_name

  ingress {

    from_port   = var.server_port

    to_port     = var.server_port

    protocol    = "tcp"

    cidr_blocks = ["0.0.0.0/0"]

  }

  egress {

    protocol    = "-1"

    from_port   = 0

    to_port     = 0

    cidr_blocks = ["0.0.0.0/0"]

  }

}

variable "security_group_name" {

  description = "The name of the security group"

  type        = string

  default     = "terraform-my-instance8"

}

output "public_ip" {

  value       = aws_instance.example.public_ip

  description = "The public IP of the Instance"

}

EOT





3

terraform plan

terraform apply -auto-approve



4

PIP=13.125.57.186

PPT=50000

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



5

확인

조금 시간이 걸린다.

e Oct 18 01:36:35 UTC 2022

<html><h1>Master seo 50000 port Web Server!</h1></html>

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

Tue Oct 18 01:36:36 UTC 2022

<html><h1>Master seo 50000 port Web Server!</h1></html>

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

Tue Oct 18 01:36:38 UTC 2022

<html><h1>Master seo 50000 port Web Server!</h1></html>

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

Tue Oct 18 01:36:39 UTC 2022

<html><h1>Master seo 50000 port Web Server!</h1></html>




다음과정

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






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

감사합니다.





매거진의 이전글 19탄-(Start) 1. 테라폼-AWS-설치-2022

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari