본문 바로가기
Infrastructure as Code/Terraform

[T101 Study 1주차 도전 과제] 기본 틀 배포

by 코인선물로부자된다 2022. 11. 7.
반응형

소스코드는

https://github.com/idealistchanu/study-T101Study.git

Chapter1 폴더에 있습니다.

어떤 서비스를 배포하는지는 너무나 많기때문에 소개하지 않고, 서비스를 배포할 때 알아두었으면 하는 내용들을 정리합니다.

1. Terraform 변경과 변경 불가능한 속성에 대해서

서비스의 조건에 따라서 결과가 달라진다. (instance type, size, tag 등등은 update되나, ami나 vpc의 변경은 replace가 되어 삭제 후 재생성된다.)

2. 변수에 대해서

# 전달할 값이 number 인지 확인하는 입력 변수의 예
variable "number_example" {
  description = "An example of a number variable in Terraform"
  type        = number
  default     = 42
}

# 전달할 값이 list 인지 확인하는 입력 변수의 예
variable "list_example" {
  description = "An example of a list in Terraform"
  type        = list
  default     = ["a", "b", "c"]
}

# 제약 조건 결합 사용 가능. 다음은 리스트의 모든 항목이 number 인 list 의 예
variable "list_numeric_example" {
  description = "An example of a numeric list in Terraform"
  type        = list(number)
  default     = [1, 2, 3]
}

# 다음은 모든 값이 string 인 map 의 예
variable "map_example" {
  description = "An example of a map in Terraform"
  type        = map(string)

  default = {
    key1 = "value1"
    key2 = "value2"
    key3 = "value3"
  }
}

# 다음은 object 또는 tuple 제약 조건을 사용하여 보다 복잡한 구조적 유형(structural type) 작성 가능
variable "object_example" {
  description = "An example of a structural type in Terraform"
  type        = object({
    name    = string
    age     = number
    tags    = list(string)
    enabled = bool
  })

  default = {
    name    = "value1"
    age     = 42
    tags    = ["a", "b", "c"]
    enabled = true
  }
}

규모가 커지면 커질수록 변수활용을 잘해야하지 않을까 싶다. 

##입력 변수
plan : (방안1) 대화형으로 변수값 입력
terraform plan
var.server_port
  The port the server will use for HTTP requests

  Enter a value: 8080

No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

plan : (방안2) -var 옵션
terraform plan -var "server_port=8080"

plan : (방안3) 환경변수
# 환경변수에 지정
export TF_VAR_server_port=8080
terraform plan

# 환경변수 확인
export | grep TF_VAR_

# 환경변수 지정 삭제
unset TF_VAR_server_port

plan : (방안4) 디폴트값을 미리 지정
cat <<EOT > variables.tf
variable "server_port" {
  description = "The port the server will use for HTTP requests"
  type        = number
  default     = 8080
}
EOT

# plan
terraform plan

## 변수 활용법
var.<VARIABLE_NAME>

resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = var.server_port
    to_port     = var.server_port
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

“${…}”
user_data = <<-EOF
            #!/bin/bash
            echo "Hello, World" > index.html
            nohup busybox httpd -f -p ${var.server_port} &
            EOF