수업 68일차 테라폼 VPC , Web server cluster 구성 및 배포

유동우·2022년 12월 31일
1

■ vpc 구성

1 provider "aws" {
2 region = "ap-northeast-2"
3 }
4
5 data "aws_vpc" "default" {
6 default = true
7 }
8
9 data "aws_subnets" "example" {
10 filter {
11 name = "vpc-id"
12 values = [data.aws_vpc.default.id]
13 }
14 }
15
16 data "aws_subnet" "example" {
17 for_each = toset(data.aws_subnets.example.ids) // for_each 뒤에는 리스트는 못씀 집합,맵만 가능
18 id = each.value
19 }
20
21
22 output "vpc-id" {
23 value = data.aws_vpc.default.id
24 }
25
26 output "subnet-cidr_blocks" {
27 value = [for s in data.aws_subnet.example : s.cidr_block]
28 }

■ web-cluster의 main.tf

1 terraform {
2 # 테라폼 버전 지정
3 required_version = ">=1.0.0, <2.0.0"
4
5 # 공급자 버전 지정
6 required_providers {
7 aws = {
8 source = "hashicorp/aws"
9 version = "~> 4.0"
10 }
11 }
12 }
13
14 provider "aws" {
15 region = "ap-northeast-2"
16 }
17
18 # 시작 템플릿 설정
19 resource "aws_launch_template" "example" {
20 image_id = "ami-0ab04b3ccbadfae1f" # Ubuntu 20.04 version
21 instance_type = "t2.micro"
22 key_name = "aws08-key"
23 vpc_security_group_ids = [aws_security_group.instance.id]
24
25 user_data = base64encode(data.template_file.web_output.rendered)
26
27 lifecycle {
28 create_before_destroy = true
29 }
30
31 }
32
33 # 오토스케일링 생성
34 resource "aws_autoscaling_group" "example" {
35 availability_zones = ["ap-northeast-2a", "ap-northeast-2c"]
36
37 desired_capacity = 1
38 min_size = 1
39 max_size = 2
40
41 launch_template {
42 id = aws_launch_template.example.id
43 version = "Latest" 44 } 45 tag { 46 key = "Name" 47 value = "aws08-terraform-asg-example" 48 propagate_at_launch = true 49 } 50 } 51 52 53 # 보안그룹 설정 8080포트 Open 54 resource "aws_security_group" "instance" { 55 name = "aws08-terraform-example-instance" 56 57 # 인바운드 규칙 설정 58 ingress { 59 from_port = var.server_port # 출발 포트 60 to_port = var.server_port # 도착 포트 61 protocol = "tcp" # 프로토콜 62 cidr_blocks = ["0.0.0.0/0"] # # 송신지 63 64 } 65 } 66 67 # Default VPC 정보 가지고 오기 68 data "aws_vpc" "default" { 69 default = true 70 } 71 72 # Subnet 정보 가지고 오기 73 data "aws_subnets" "default" { 74 filter { 75 name = "vpc-id" 76 values = [data.aws_vpc.default.id] 77 } 78 } 79 80 data "template_file" "web_output" { 81 template = file("{path.module}/web.sh")
82 vars = {
83 server_port = "${var.server_port}"
84 }
85 }

:e web.sh

1 #!/bin/bash
2
3 cat > index.html <<EOF
4

Hello, World


5 EOF
6
7 nohup busybox httpd -f -p ${server_port} &

인스턴스 퍼블릭 주소 :8080해서 웹 브라우저에 검색

인스턴스 만들고 인스턴스에 보안그룹에 ssh 22번포트 ipv4로 보안그룹 추가

우분투로와서
ssh -i ~/.ssh/aws08-key.pem ubuntu@15.164.218.148

ps -ef | grep busybox

vim variables.tf

1 variable "server_port" {
2 description = "The port will use for HTTP requests"
3 type = number
4 default = 8080
5 }
6
7 variable "sercurity_group_name" {
8 type = string
9 default = "aws08-terraform-example-instance"
10 }

vim outputs.tf

1 # outputs.tf
2 output "alb_dns_name" {
3 value = aws_lb.example.dns_name
4 description = "The domain name of the load balancer"
5 }

■ 로드밸런서

vim main.tf

1 terraform {
2 # 테라폼 버전 지정
3 required_version = ">=1.0.0, <2.0.0"
4
5 # 공급자 버전 지정
6 required_providers {
7 aws = {
8 source = "hashicorp/aws"
9 version = "~> 4.0"
10 }
11 }
12 }
13
14 provider "aws" {
15 region = "ap-northeast-2"
16 }
17
18 # 시작 템플릿 설정
19 resource "aws_launch_template" "example" {
20 image_id = "ami-0ab04b3ccbadfae1f" # Ubuntu 20.04 version
21 instance_type = "t2.micro"
22 key_name = "aws08-key"
23 vpc_security_group_ids = [aws_security_group.instance.id]
24
25 user_data = base64encode(data.template_file.web_output.rendered)
26
27 lifecycle {
28 create_before_destroy = true
29 }
30
31 }
32
33 # 오토스케일링 생성
34 resource "aws_autoscaling_group" "example" {
35 availability_zones = ["ap-northeast-2a", "ap-northeast-2c"]
36
37 name = "aws08-terraform-asg-example"
38 desired_capacity = 1
39 min_size = 1
40 max_size = 2
41
42 target_group_arns = [aws_lb_target_group.asg.arn]
43 health_check_type = "ELB"
44
45 launch_template {
46 id = aws_launch_template.example.id
47 version = "$Latest"
48 }
49 tag {
50 key = "Name"
51 value = "aws08-terraform-asg-example"
52 propagate_at_launch = true
53 }
54 }
55
56 # 로드밸런서
57 resource "aws_lb" "example" {
58 name = "aws08-terraform-asg-example"
59 load_balancer_type = "application"
60 subnets = data.aws_subnets.default.ids
61 security_groups = [aws_security_group.alb.id]
62 }
63
64
65 # 로드밸런서 리스너
66 resource "aws_lb_listener" "http" {
67 load_balancer_arn = aws_lb.example.arn
68 port = 80
69 protocol = "HTTP"
70
71 # 기본값으로 단순한 404 페이지 오류를 반환한다.
72 default_action {
73 type = "fixed-response"
74 fixed_response {
75 content_type = "text/plain"
76 message_body = "404: page not found"
77 status_code = 404
78 }
79 }
80 }
81
82 # 로드 밸런서 리스너 룰 구성
83
84 resource "aws_lb_listener_rule" "asg" {
85 listener_arn = aws_lb_listener.http.arn
86 priority = 100
87
88 condition {
89 path_pattern {
90 values = ["*"]
91 }
92 }
93 action {
94 type = "forward"
95 target_group_arn = aws_lb_target_group.asg.arn
96 }
97 }
98
99
100
101 # 로드밸런서 대상그룹
102
103 resource "aws_lb_target_group" "asg" {
104 name = "aws08-terraform-asg-example"
105 port = var.server_port
106 protocol = "HTTP"
107 vpc_id = data.aws_vpc.default.id
108
109 health_check {
110 path = "/"
111 protocol = "HTTP"
112 matcher = "200"
113 interval = 15
114 timeout = 3
115 healthy_threshold = 2
116 unhealthy_threshold = 2
117 }
118 }
119
120
121 # 보안그룹 - instance
122 resource "aws_security_group" "instance" {
123 name = "var.security_group_name"
124
125 ingress {
126 from_port = var.server_port
127 to_port = var.server_port
128 protocol = "tcp"
129 cidr_blocks = ["0.0.0.0/0"]
130 }
131 }
132
133
134
135 # 보안 그룹 - ALB
136 resource "aws_security_group" "alb" {
137 name = "aws08-terraform-example-alb"
138
139
140 # 인바운드 HTTP 트래픽 허용
141 ingress {
142 from_port = 80 # 출발 포트
143 to_port = 80 # 도착 포트
144 protocol = "tcp" # 프로토콜
145 cidr_blocks = ["0.0.0.0/0"] # # 송신지
146 }
147
148 # 모든 아웃바운드 트래픽 허용
149 egress {
150 from_port = 0 # 출발 포트
151 to_port = 0 # 도착 포트
152 protocol = "-1" # 프로토콜
153 cidr_blocks = ["0.0.0.0/0"] # # 송신지
154 }
155 }

■ 테라폼 상태관리하기

mkdir terraform-state

cd terraform-state

vim main.tf

1 terraform {
2 required_version = ">= 1.0.0, < 2.0.0"
3
4 required_providers {
5 aws = {
6 source = "hashicorp/aws"
7 version = "~> 4.0"
8 }
9 }
10 }
11 provider "aws" {
12 region = "ap-northeast-2"
13 }
14
15 resource "aws_s3_bucket" "terraform_state" {
16 bucket = "aws08-terraform-state"
17
18 # 실수로 S3 버킷을 삭제하는 것을 방지한다.
19 lifecycle {
20 prevent_destroy = true
21 }
22
23 # 코드 이력을 관리하기 위해 상태 파일의 버전 관리를 활성화한다.
24
25 versioning {
26 enabled = true
27 }
28
29 # 서버측 암호화를 활성화한다.
30
31 server_side_encryption_configuration {
32 rule {
33 apply_server_side_encryption_by_default {
34 sse_algorithm = "AES256"
35 }
36 }
37 }
38 }

※ 삭제방지하고싶지않을때

18 # 실수로 S3 버킷을 삭제하는 것을 방지한다.
19 # lifecycle {
20 # prevent_destroy = true
21 # }
22
23 lifecycle {
24 prevent_destroy = false
25 }
26 force_destroy = true

=============================

※ dynamodb 리소스추가

46 resource "aws_dynamodb_table" "terraform_locks" {
47 name = "aws-08-terraform-locks"
48 billing_mode = "PAY_PER_REQUEST"
49 hash_key = "LockID"
50
51 attribute {
52 name = "LockID"
53 type = "S"
54 }
55 }

================

※ 파일위치정리

mkdir global

mkdir global/s3

mv . global/s3

mv .* global/s3/

=> global에 main.tf에는 S3 버킷이랑 dynamodb 구성

==================

mkdir stage

mkdir stage/services

mkdir stage/services/webserver-cluster

cd stage/services/webserver-cluster

vim main.tf

1 terraform {
2 required_version = ">= 1.0.0, < 2.0.0"
3
4 required_providers {
5 aws = {
6 source = "hashicorp/aws"
7 version = "~> 4.0"
8 }
9 }
10 backend "s3" {
11
12 # 이전에 생성한 버킷 이름으로 변경
13 bucket = "aws08-terraform-state"
14 key = "global/s3/terraform.tfstate"
15 region = "ap-northeast-2"
16
17 # 이전에 생성한 다이나모DB 테이블 이름으로 변경
18 dynamodb_table = "terraform-locks"
19 encrypt = true
20 }
21 }
22
23 provider "aws" {
24 region = "ap-northeast-2"
25 }

=> webserver-cluster에 main.tf에는 S3버킷에 대한 backend 구성

profile
클라우드 엔지니어가 되고싶은 클린이

0개의 댓글