Terraform 스터디그룹 T101 2주차 - 2

DevOps Engineer·2023년 10월 7일
0

T101-2week

목록 보기
2/2

Variable

variable "<이름>" {
 <인수> = <>
}

variable "image_id" {
 type = string
}

예약 변수로 사용 불가능한 것

  • source, version, provider, count, for_each, lifecycle, depends_on, locals

변수 정의 시 사용 가능한 인수

  • default: 기본값으로 전달됨, 기본값이 없을 시 변수에 대한 정보를 작성해줘야 함
  • type: 변수에 허용되는 유형 정의
  • description: 변수에 대한 설명
  • validation: 유효성 검사 규칙을 정의
  • sensitive: 민감한 변수 값임을 알려주고 노출을 제한
  • nullable: 변수에 대한 값이 없어도 됨을 설정하는 인수

변수 유형

기본유형

  • string: 글자 유형
  • number: 숫자 유형
  • bool: true / false
  • any: 모든 유형

집합 유형

  • list: 인덱스 기반 집합
  • map: 속성 기반 집합 키값 기준 정렬
  • set: 값 기반 집합 정렬 키값 기준 정렬
  • object: 인수 이름 = 유형
  • tuple: 유형

변수의 전달 값에 따른 예시

variable "number_example" {
  description = "An example of a number variable in Terraform"
  type        = number
  default     = 42
}
variable "list_example" {
  description = "An example of a list in Terraform"
  type        = list
  default     = ["a", "b", "c"]
}

조건결합

  • list / number
variable "list_numeric_example" {
  description = "An example of a numeric list in Terraform"
  type        = list(number)
  default     = [1, 2, 3]
}
  • map / string
variable "map_example" {
  description = "An example of a map in Terraform"
  type        = map(string)

  default = {
    key1 = "value1"
    key2 = "value2"
    key3 = "value3"
  }
}
  • object / tuple 제약 조건
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
  }
}
  • 각 유형 별 작성 방법
variable "string" {
  type        = string
  description = "var String"
  default     = "myString"
}

variable "number" {
  type    = number
  default = 123
}

variable "boolean" {
  default = true
}

variable "list" {
  default = [
    "google",
    "vmware",
    "amazon",
    "microsoft"
  ]
}

output "list_index_0" {
  value = var.list.0
}

output "list_all" {
  value = [
    for name in var.list : upper(name)
  ]
}

variable "map" { # Sorting
  default = {
    aws   = "amazon",
    azure = "microsoft",
    gcp   = "google"
  }
}

variable "set" { # Sorting
  type = set(string)
  default = [
    "google",
    "vmware",
    "amazon",
    "microsoft"
  ]
}

variable "object" {
  type = object({ name = string, age = number })
  default = {
    name = "abc"
    age  = 12
  }
}

variable "tuple" {
  type    = tuple([string, number, bool])
  default = ["abc", 123, true]
}

variable "ingress_rules" { # optional ( >= terraform 1.3.0)
  type = list(object({
    port        = number,
    description = optional(string),
    protocol    = optional(string, "tcp"),
  }))
  default = [
    { port = 80, description = "web" },
  { port = 53, protocol = "udp" }]
}

유효성 검사

변수 블록 내에 validation 블록에서 조건인 condition에 지정되는 규칙이 true 또는 false를 반환해야 하며, error_message는 condition 값의 결과가 false 인 경우 출력되는 메시지를 정의한다

variable "image_id" {
  type        = string
  description = "The id of the machine image (AMI) to use for the server."

  validation {
    condition     = length(var.image_id) > 4
    error_message = "The image_id value must exceed 4."
  }

  validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("^ami-", var.image_id))
    error_message = "The image_id value must starting with \"ami-\"."
  }
}
  • ami만 칠 경우

  • ami- 까지 칠 경우

  • ami-12345678 인 경우

변수 참조

variable "my_password" {}

resource "local_file" "abc" {
  content  = var.my_password
  filename = "${path.module}/abc.txt"
}
terraform init -upgrade && terraform apply -auto-approve
terraform state list
terraform state show local_file.abc

  • sensitve 적용 후

변수 입력방식과 우선순위


우선순위가 낮은 순

  • 실행 후 입력
# 실행
terraform apply -auto-approve
var.my_var
  Enter a value: var1
...

# 확인
terraform state show local_file.abc
cat abc.txt ; echo
  • variable 블록의 default 값
variable "my_var" {
  default = "var2"
}

resource "local_file" "abc" {
  content  = var.my_var
  filename = "${path.module}/abc.txt"
}
  • 환경변수 TF_VAR값
# Linux/macOS
export TF_VAR_my_var=var3
terraform apply -auto-approve

# 확인
cat abc.txt ; echo
  • terraform.tfvars 에 정의된 변수 선언
#
echo 'my_var="var4"' > terraform.tfvars
cat terraform.tfvars

#
terraform apply -auto-approve

# 확인
cat abc.txt ; echo
  • *.auto.tfvars에 정의된 변수 선언
# a.auto.tfvars 파일 생성
echo 'my_var="var5_a"' > a.auto.tfvars
ls *.tfvars

#
terraform apply -auto-approve

# 확인
cat abc.txt ; echo


# b.auto.tfvars 파일 생성
echo 'my_var="var5_b"' > b.auto.tfvars
ls *.tfvars

#
terraform apply -auto-approve

# 확인
cat abc.txt ; echo
  • *.auto.tfvars.json에 정의된 변수 선언
# a.auto.tfvars.json 파일 생성
cat <<EOF > a.auto.tfvars.json
{
  "my_var" : "var6_a"
}
EOF
ls *.tfvars ; ls *.json

#
terraform apply -auto-approve

# 확인
cat abc.txt ; echo


# c.auto.tfvars.json 파일 생성
cat <<EOF > c.auto.tfvars.json
{
  "my_var" : "var6_c"
}
EOF
ls *.tfvars ; ls *.json

#
terraform apply -auto-approve

# 확인
cat abc.txt ; echo
  • cli 실행 시 -var 인수에 지정 또는 파일지정
#
terraform apply -auto-approve -var=my_var=var7
cat abc.txt ; echo

#
terraform apply -auto-approve -var=my_var=var7 -var=my_var=var8
cat abc.txt ; echo

# var9.txt 파일 생성
echo 'my_var="var9"' > var9.txt

#
terraform apply -auto-approve -var=my_var=var7 -var-file="var9.txt"
cat abc.txt ; echo
profile
madame의 Techblog

0개의 댓글