카테고리 없음

4-3. workspace 실습

yeongki0944 2024. 7. 6. 16:45

 

1. tf 코드 - main.tf

provider "aws" {
  region = "us-east-2"
}

resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "week4-vpc-${terraform.workspace}-example"
  }
}

resource "aws_subnet" "example" {
  vpc_id     = aws_vpc.example.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "week4-subnet-${terraform.workspace}-example"
  }
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 AMI
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.example.id

  tags = {
    Name = "week4-ec2-${terraform.workspace}-example"
  }
}

variable "instance_type" {
  description = "Type of the instance"
  type        = string
  default     = "t2.micro"
}

output "instance_id" {
  value = aws_instance.example.id
}

output "instance_public_ip" {
  value = aws_instance.example.public_ip
}

 

 

2. terraform init

terraform init

 

3. terraform workspace

terraform workspace new dev
terraform workspace new prod

local backend workspace

 

4. dev 워크스페이스에 배포

terraform workspace select dev
terraform workspace show
terraform apply -auto-approve

terraform.tfstate.d > dev > terraform.tfstate 파일 생성

 

5. prod 워크스페이스에 배포

terraform workspace select prod
terraform workspace show
terraform apply -auto-approve

terraform.tfstate.d > prod > terraform.tfstate 파일 생성

 

6. terraform cli에서 workspace 명시하는 방법

terraform destroy, apply 명령어 옵션에서 직접 워크스페이스를 지정하는 옵션은 없습니다.

cli에서 워크스페이스를 명시하기 위해선, 아래와 같은 && 연산을 통해 확실하게 특정 워크스페이스를 지정하여 apply, destroy가 가능합니다.

terraform workspace select dev && terraform destroy -auto-approve

 

terraform workspace select prod && terraform destroy -auto-approve