brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Nov 01. 2022

19탄-9. 테라폼-AWS-상태 파일 격리-워크스페이스

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

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

 


개발, 스테이징, 프로덕트 서비스에 대한 상태 파일은 같이 사용하지 못하므로 각각 격리해야 한다.  


테라폼 workspaces = 작업공간 격리  

파일 레이아웃으로 격리 - 폴더로 격리   




<1> 작업 공간을 통한 격리   Workspaces

<2> 기본 workspace 환경에서 ec2 생성 , 워크 스페이스 확인 

<3> 새 작업 공간용  workspace  생성 및 확인 




<1> 작업 공간을 통한 격리   Workspaces


1

기본으로 테라폼은 Default 작업공간을 사용한다.

백엔드 리소스 생성

디폴트 VPC로 사용하자.

aws ec2 create-default-vpc


2

백앤드 저장소를 만들자.

mkdir tf-back

cd tf-back


버킷 하나 만들고

버저닝

다이나모 디비 테이블 하나 만들자

배포

확인

 s3 확인

다이나모 디비 테이블 확인


# S3 버킷 이름은 고유


NICKNAME=masterseo


# 코드 파일 생성


cat <<EOT > backend.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_s3_bucket" "mys3bucket" {

  bucket = "$NICKNAME-t101study-tfstate-week3"

}

# Enable versioning so you can see the full revision history of your state files

resource "aws_s3_bucket_versioning" "mys3bucket_versioning" {

  bucket = aws_s3_bucket.mys3bucket.id

  versioning_configuration {

    status = "Enabled"

  }

}

resource "aws_dynamodb_table" "mydynamodbtable" {

  name         = "terraform-locks-week3"

  billing_mode = "PAY_PER_REQUEST"

  hash_key     = "LockID"

  attribute {

    name = "LockID"

    type = "S"

  }

}

output "s3_bucket_arn" {

  value       = aws_s3_bucket.mys3bucket.arn

  description = "The ARN of the S3 bucket"

}

output "dynamodb_table_name" {

  value       = aws_dynamodb_table.mydynamodbtable.name

  description = "The name of the DynamoDB table"

}

EOT


# 배포

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

Outputs:

dynamodb_table_name = "terraform-locks-week3"

s3_bucket_arn = "arn:aws:s3:::masterseo-t101study-tfstate-week3"



# 배포 확인

terraform state list

[root@ip-172-31-61-209 tf-back]# terraform state list

aws_dynamodb_table.mydynamodbtable

aws_s3_bucket.mys3bucket

aws_s3_bucket_versioning.mys3bucket_versioning


aws s3 ls

masterseo-t101study-tfstate-week3


aws dynamodb list-tables --output text



[root@ip-172-31-61-209 tf-back]# aws dynamodb list-tables --output text

TABLENAMES      terraform-locks

TABLENAMES      terraform-locks-week3


# 기존 작업 디렉터리로 이동

cd ..






<2> 기본 workspace 환경에서 ec2 생성 , 워크 스페이스 확인 


1

기본 workspace 환경에서 ec2 생성 , 워크 스페이스 확인 


NICKNAME=masterseo


cat <<EOT > main.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami           = "ami-0c76973fbe0ee100c"

  instance_type = "t2.micro"

  tags = {

    Name = "t101-week3"

  }

}

terraform {

  backend "s3" {

    bucket = "$NICKNAME-t101study-tfstate-week3"

    key    = "workspaces-default/terraform.tfstate"

    region = "ap-northeast-2"

    dynamodb_table = "terraform-locks-week3"

  }

}

EOT





2

init에서 원격 저장소에 저장되도록 강제 옵션 설정해 실행.

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


terraform state list 

aws_instance.example


3

워크스페이스 확인

terraform workspace show

default







<3> 새 작업 공간용  workspace  생성 및 확인 


1

버킷 모니터링

s3 모니터링

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

EC2 모니터링 

NICKNAME=masterseo

while true; do aws s3 ls s3://$NICKNAME-t101study-tfstate-week3 --recursive --human-readable --summarize ; echo "------------------------------"; date; sleep 1; done





3

새 작업 공간을 만들어보자.


# terraform workspace new mywork1

Created and switched to workspace "mywork1"!

You're now on a new, empty workspace. Workspaces isolate their state,

so if you run "terraform plan" Terraform will not see any existing state

for this configuration.


[root@ip-172-31-61-209 ~]# terraform workspace show

mywork1



4

테라폼 플랜

ec2 하나는 생성한다고 한다.

ec2 1개를 새로 생성한다.

작업 공간이 하나가 분리된 것이다.

mywork1 


# plan 시 어떤 결과 내용?

terraform plan

Plan: 1 to add, 0 to change, 0 to destroy.

// 1개 add한다고 한다.


# apply 해보자!

terraform apply -auto-approve


// EC2 1개가 추가 된다.  다른 workspace 라 추가 되는것이다.

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

t101-week3      3.34.181.163    running

t101-week3      13.209.76.103   running


5

버킷 모니터링 내용이 변경된다.



6

새로운 작업 공간 2를 만들어보자.

terraform workspace new mywork2

terraform plan && terraform apply -auto-approve


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

t101-week3      3.34.181.163    running

t101-week3      13.209.76.103   running

t101-week3      43.201.114.79   running


7

terraform workspace show

mywork2


8

workspace list로 확인해보자.

terraform workspace list

  default

  mywork1

* mywork2


현재 작업 공간 3개

각각 EC2가 만들어진다.


9

작업 공간 간 전환?

terraform workspace select mywork1


terraform workspace show

mywork1


10

콘솔에 s3 가서 확인하자.

디폴트 작업 공간 

env는 워크스페이스를 만들어진 것이다.



11

한 개의 파일로 워크 스페이스의 리소스 사양을 변경해보자.

디폴트 워크 스페이스의 ec2 사양 변경  t2 마이크로를  t2 미디엄으로 변경.

다른 워크스페이스 ec2  사양 변경


cat <<EOT > main.tf

provider "aws" {

  region = "ap-northeast-2"

}

resource "aws_instance" "example" {

  ami           = "ami-0c76973fbe0ee100c"

  instance_type = terraform.workspace == "default" ? "t2.medium" : "t2.micro"

  tags = {

    Name = "t101-week3"

  }

}

terraform {

  backend "s3" {

    bucket = "$NICKNAME-t101study-tfstate-week3"

    key    = "workspaces-default/terraform.tfstate"

    region = "ap-northeast-2"

    dynamodb_table = "terraform-locks-week3"

  }

}

EOT



# plan & apply

terraform plan && terraform apply -auto-approve


# 작업 공간 전환

terraform workspace select mywork1


# plan & apply 

terraform plan && terraform apply -auto-approve


# 작업 공간 전환

terraform workspace select default


# plan & apply 

terraform plan && terraform apply -auto-approve





12

단점?

모두 동일한 백엔드를 사용한다.

동일한 백엔드로 보안 적용 내용이 다 같다.

백앤드 장애 시 모두 장애가 난다.



13

리소스 삭제

terraform workspace select default

terraform destroy -auto-approve

terraform workspace select mywork1

terraform destroy -auto-approve

terraform workspace select mywork2

terraform destroy -auto-approve



14

버킷 삭제

aws s3 rm s3://$NICKNAME-t101study-tfstate-week3 --recursive


15

버킷 버저닝 삭제



다음

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




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



감사합니다.

매거진의 이전글 19탄-8. 테라폼-AWS-DEV,STG 환경
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari