brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Dec 07. 2022

19탄-25. 테라폼-AWS-모듈 이용한 배포

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

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


<1> 공통은 모듈을 사용해 리소스를 만들자.

<2> 환경 설정 구성

<3> Staging RDS 배포

<4> 모듈을 활용하여 Staging 웹서버 클러스터 배포

<5> Production 환경의 “RDS + 웹 서버 클러스터”를 배포해보자!




<1> 공통은 모듈을 사용해 리소스를 만들자.


stage - service- webserver-cluster - main.tf

prod - service- webserver-cluster - main.tf

module - service - webserver-cluster - main.tf




<2> 환경 설정 구성


S3/DynamoDB 생성을 위한 환경변수 지정


1

# 환경변수에 지정

export TF_VAR_bucket_name=masterseo-t101-tfstate

export TF_VAR_table_name=masterseo-t101-locks


# 환경변수 확인

export | grep TF_VAR_


# (옵션) 환경변수 지정 삭제

unset TF_VAR_bucket_name

unset TF_VAR_table_name


2

S3 생성을 위한 배포


#

 cd /root/terraform-up-and-running-code/code/terraform/03-terraform-state/file-layout-example/global/s3


[root@ip-172-31-61-209 mysql]# ls

main.tf  outputs.tf  README.md  variables.tf



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

terraform {

  required_version = ">= 1.0.0, < 2.0.0"

  required_providers {

    aws = {

      source  = "hashicorp/aws"

      version = "~> 4.0"

    }

  }

  backend "s3" {

    # This backend configuration is filled in automatically at test time by Terratest. If you wish to run this example

    # manually, uncomment and fill in the config below.

    bucket         = "masterseo-t101-tfstate"

    key            = "stage/data-stores/mysql/terraform.tfstate"

    region         = "us-east-2"

    dynamodb_table = "masterseo-t101-locks"

    # encrypt        = true

  }

}

provider "aws" {

  region = "us-east-2"

}

resource "aws_db_instance" "example" {

  identifier_prefix   = "terraform-up-and-running"

  engine              = "mysql"

  allocated_storage   = 10

  instance_class      = "db.t2.micro"

  db_name             = var.db_name

  username            = var.db_username

  password            = var.db_password

  skip_final_snapshot = true

}



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

# ---------------------------------------------------------------------------------------------------------------------

# REQUIRED PARAMETERS

# You must provide a value for each of these parameters.

# ---------------------------------------------------------------------------------------------------------------------

variable "db_username" {

  description = "The username for the database"

  type        = string

  sensitive   = true

}

variable "db_password" {

  description = "The password for the database"

  type        = string

  sensitive   = true

}

# ---------------------------------------------------------------------------------------------------------------------

# OPTIONAL PARAMETERS

# These parameters have reasonable defaults.

# ---------------------------------------------------------------------------------------------------------------------

variable "db_name" {

  description = "The name to use for the database"

  type        = string

  default     = "example_database_stage"

}

[root@ip-172-31-61-209 mysql]#





# 초기화 및 검증 : 환경변수 적용 확인

terraform init && terraform plan


# 배포

terraform apply -auto-approve


# 확인

aws s3 ls

aws dynamodb list-tables --output text





<3> Staging RDS 배포


1

# [터미널 1] RDS 생성 모니터링

while true; do aws rds describe-db-instances --query "*[].[Endpoint.Address,Endpoint.Port,MasterUsername]" --output text  ; echo "------------------------------" ; sleep 1; done


2

# [터미널2]

cd /root/terraform-up-and-running-code/code/terraform/04-terraform-module/module-example/stage/data-stores/mysql


cat main.tf variables.tf


# 환경변수에 지정

export TF_VAR_db_username='cloudneta'

export TF_VAR_db_password='cloudnetaQ!'


# 환경변수 확인

export | grep TF_VAR_


# main.tf 에 백엔드 부분 수정

vi main.tf

  backend "s3" {

    # This backend configuration is filled in automatically at test time by Terratest. If you wish to run this example

    # manually, uncomment and fill in the config below.

    bucket         = "masterseo-t101-tfstate"

    key            = "stage/data-stores/mysql/terraform.tfstate"

    region         = "us-east-2"

    dynamodb_table = "masterseo-t101-locks"

    # encrypt        = true

  }


# 초기화 및 검증 : 환경변수 적용 확인

terraform init && terraform plan


# 배포 : RDS는 생성 시 6분 정도 시간 소요

terraform apply -auto-approve

terraform output



3

다른 터미널에서 모니터링 결과  RDS 만들어짐

None    None    cloudneta

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

terraform-up-and-running2022x0001.c7aitcdywcyg.us-east-2.rds.amazonaws.com     3306    cloudneta

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

terraform-up-and-running202x000001.c7aitcdywcyg.us-east-2.rds.amazonaws.com     3306    cloudneta

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

terraform-up-and-running2022x0000001.c7aitcdywcyg.us-east-2.rds.amazonaws.com     3306    cloudneta



4

aws s3 ls s3://$TF_VAR_bucket_name --recursive --human-readable --summarize


[root@ip-172-31-61-209 mysql]# aws s3 ls s3://$TF_VAR_bucket_name --recursive --human-readable --summarize

2022-12-07 04:51:31    4.3 KiB stage/data-stores/mysql/terraform.tfstate




<4> 모듈을 활용하여 Staging 웹서버 클러스터 배포


1

#

cd ..

cd ..

cd services/webserver-cluster

cat main.tf variables.tf


[root@ip-172-31-61-209 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"

}

module "webserver_cluster" {

  source = "../../../modules/services/webserver-cluster"

  # (parameters hidden for clarity)

  cluster_name           = var.cluster_name

  db_remote_state_bucket = var.db_remote_state_bucket

  db_remote_state_key    = var.db_remote_state_key

  instance_type = "t2.micro"

  min_size      = 2

  max_size      = 2

}

resource "aws_security_group_rule" "allow_testing_inbound" {

  type              = "ingress"

  security_group_id = module.webserver_cluster.alb_security_group_id

  from_port   = 12345

  to_port     = 12345

  protocol    = "tcp"

  cidr_blocks = ["0.0.0.0/0"]

}


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

# ---------------------------------------------------------------------------------------------------------------------

# REQUIRED PARAMETERS

# You must provide a value for each of these parameters.

# ---------------------------------------------------------------------------------------------------------------------

variable "db_remote_state_bucket" {

  description = "The name of the S3 bucket used for the database's remote state storage"

  type        = string

}

variable "db_remote_state_key" {

  description = "The name of the key in the S3 bucket used for the database's remote state storage"

  type        = string

}

# ---------------------------------------------------------------------------------------------------------------------

# OPTIONAL PARAMETERS

# These parameters have reasonable defaults.

# ---------------------------------------------------------------------------------------------------------------------

variable "cluster_name" {

  description = "The name to use to namespace all the resources in the cluster"

  type        = string

  default     = "webservers-stage"

}

[root@ip-172-31-61-209 webserver-cluster]#



2

# 환경변수에 지정

export TF_VAR_db_remote_state_bucket=$TF_VAR_bucket_name                       # description = "The name of the S3 bucket used for the database's remote state storage"

export TF_VAR_db_remote_state_key='stage/data-stores/mysql/terraform.tfstate'  # description = "The name of the key in the S3 bucket used for the database's remote state storage" 


# 환경변수 확인

export | grep TF_VAR_



3

# 초기화 및 검증 : 환경변수 적용 확인

terraform init && terraform plan



4

# 배포

terraform apply -auto-approve


5

# ALB DNS주소로 curl 접속 확인 

ALBDNS=$(terraform output -raw alb_dns_name)

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


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

Wed Dec  7 06:29:50 UTC 2022

<h1>Hello, World</h1>

<p>DB address: terraform-up-and-running202000001.c7aitcdywcyg.us-east-2.rds.amazonaws.com</p>

<p>DB port: 3306</p>

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



curl -s http://$ALBDNS



6

# 삭제

# 각 폴더에서 리소스 삭제

stage/services/webserver-cluster$ terraform destroy -auto-approve

stage/data-stores/mysql$ terraform destroy -auto-approve

03-terraform-state/file-layout-example/global/s3$ terraform destroy -auto-approve 





<5> Production 환경의 “RDS + 웹 서버 클러스터”를 배포해보자!




다음

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



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

감사합니다.

매거진의 이전글 19탄-24. 테라폼-AWS-RDS 생성

작품 선택

키워드 선택 0 / 3 0

댓글여부

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