brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Dec 06. 2022

19탄-23. 테라폼-AWS-EC2 생성, LB생성

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

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



<1>  작업 환경

<2>  ec2 생성하기

<3>  ec2 , lb  생성하기




<1>  작업 환경


참고 링크

https://github.com/brikis98/terraform-up-and-running-code


테라폼 버전 관리

https://github.com/tfutils/tfenv


1

영문 - 개정3판 내용 실습

리눅스 서버에서 작업한다.

미국 동부 오하이오 리전,  us-east-2

테라폼 v1.2.3 버전으로 실습

wget https://releases.hashicorp.com/terraform/1.2.3/terraform_1.2.3_linux_386.zip

unzip 


[root@ip-172-31-61-209 bin]# ./terraform  -version

Terraform v1.2.3

on linux_386



테라폼 버전 관리 툴

https://dev.classmethod.jp/articles/managing-terraform-version-with-tfenv/



2

# aws configure

us-east-2



or

export AWS_DEFAULT_REGION=us-east-2


#

소스 다운로드

git clone https://github.com/brikis98/terraform-up-and-running-code.git

cd terraform-up-and-running-code/code/terraform

tree





<2>  ec2 생성하기


1

터미널2 에서 ec2 생성 모니터링


export AWS_PAGER="" 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



2

터미널 1에서 


cd /root/terraform-up-and-running-code/code/terraform/00-preface/hello-world


[root@ip-172-31-61-209 hello-world]# more main.tf

terraform {

  required_version = ">= 1.0.0, < 2.0.0"

  required_providers {

    aws = {

      source  = "hashicorp/aws"

      version = "~> 4.0"

    }

  }

}

provider "aws" {

  region = "us-east-2"

}

resource "aws_instance" "example" {

  ami           = "ami-0fb653ca2d3203ac1"

  instance_type = "t2.micro"

}

[root@ip-172-31-61-209 hello-world]#



terraform init

terraform plan

terraform apply

yes



3

터미널 2에서 ec2 생성 확인

None    3.142.91.196    running

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

None    3.142.91.196    running

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

None    3.142.91.196    running

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



4

삭제 후 확인

terraform destroy -auto-approve

cd ~/terraform-up-and-running-code/code/terraform





<3>  ec2 , lb  생성하기


1

# [터미널2] 

cd /root/terraform-up-and-running-code/code/terraform/02-intro-to-terraform-syntax/webserver-cluster



# more main.tf

terraform {

  required_version = ">= 1.0.0, < 2.0.0"

  required_providers {

    aws = {

      source  = "hashicorp/aws"

      version = "~> 4.0"

    }

  }

}

provider "aws" {

  region = "us-east-2"

}

resource "aws_launch_configuration" "example" {

  image_id        = "ami-0fb653ca2d3203ac1"

  instance_type   = "t2.micro"

  security_groups = [aws_security_group.instance.id]

  user_data = <<-EOF

              #!/bin/bash

              echo "Hello, World" > index.html

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

              EOF

  # Required when using a launch configuration with an auto scaling group.

  lifecycle {

    create_before_destroy = true

  }

}

resource "aws_autoscaling_group" "example" {

  launch_configuration = aws_launch_configuration.example.name

  vpc_zone_identifier  = data.aws_subnets.default.ids

  target_group_arns = [aws_lb_target_group.asg.arn]

  health_check_type = "ELB"

  min_size = 2

  max_size = 10

  tag {

    key                 = "Name"

    value               = "terraform-asg-example"

    propagate_at_launch = true

  }

}

resource "aws_security_group" "instance" {

  name = var.instance_security_group_name

  ingress {

    from_port   = var.server_port

    to_port     = var.server_port

    protocol    = "tcp"

    cidr_blocks = ["0.0.0.0/0"]

  }

}

data "aws_vpc" "default" {

  default = true

}

data "aws_subnets" "default" {

  filter {

    name   = "vpc-id"

    values = [data.aws_vpc.default.id]

  }

}

resource "aws_lb" "example" {

  name               = var.alb_name

  load_balancer_type = "application"

  subnets            = data.aws_subnets.default.ids

  security_groups    = [aws_security_group.alb.id]

}

resource "aws_lb_listener" "http" {

  load_balancer_arn = aws_lb.example.arn

  port              = 80

  protocol          = "HTTP"

  # By default, return a simple 404 page

  default_action {

    type = "fixed-response"

    fixed_response {

      content_type = "text/plain"

      message_body = "404: page not found"

      status_code  = 404

    }

  }

}

resource "aws_lb_target_group" "asg" {

  name = var.alb_name

  port     = var.server_port

  protocol = "HTTP"

  vpc_id   = data.aws_vpc.default.id

  health_check {

    path                = "/"

    protocol            = "HTTP"

    matcher             = "200"

    interval            = 15

    timeout             = 3

    healthy_threshold   = 2

    unhealthy_threshold = 2

  }

}

resource "aws_lb_listener_rule" "asg" {

  listener_arn = aws_lb_listener.http.arn

  priority     = 100

  condition {

    path_pattern {

      values = ["*"]

    }

  }

  action {

    type             = "forward"

    target_group_arn = aws_lb_target_group.asg.arn

  }

}

resource "aws_security_group" "alb" {

  name = var.alb_security_group_name

  # Allow inbound HTTP requests

  ingress {

    from_port   = 80

    to_port     = 80

    protocol    = "tcp"

    cidr_blocks = ["0.0.0.0/0"]

  }

  # Allow all outbound requests

  egress {

    from_port   = 0

    to_port     = 0

    protocol    = "-1"

    cidr_blocks = ["0.0.0.0/0"]

  }

}




[root@ip-172-31-61-209 webserver-cluster]# more variables.tf

variable "server_port" {

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

  type        = number

  default     = 8080

}

variable "alb_name" {

  description = "The name of the ALB"

  type        = string

  default     = "terraform-asg-example"

}

variable "instance_security_group_name" {

  description = "The name of the security group for the EC2 Instances"

  type        = string

  default     = "terraform-example-instance"

}

variable "alb_security_group_name" {

  description = "The name of the security group for the ALB"

  type        = string

  default     = "terraform-example-alb"

}




[root@ip-172-31-61-209 webserver-cluster]# more outputs.tf

output "alb_dns_name" {

  value       = aws_lb.example.dns_name

  description = "The domain name of the load balancer"

}



# 배포

terraform init

terraform plan

terraform apply -auto-approve



2

다른 터미널에서  ec2 2개 생성 확인

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

terraform-asg-example   None    running

terraform-asg-example   None    running



3

테라폼 실행후 아웃풋 파일 결과

Outputs:

alb_dns_name = "terraform-asg-example-723538014.us-east-2.elb.amazonaws.com"


# 배포 완료 후 ALB 접속 확인

ALBDNS=$(terraform output -raw alb_dns_name)

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


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

Tue Dec  6 08:01:18 UTC 2022

Hello, World





# 삭제

terraform destroy -auto-approve


cd ~/terraform-up-and-running-code/code/terraform




다음 과정

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




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

감사합니다.

매거진의 이전글 19탄-22. 테라폼-AWS-민감 정보 안전하게 관리
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari