Lim Seunghyun Space

[T102] Variable 본문

IaC/Terraform

[T102] Variable

Lim Seung Hyun 2023. 7. 16. 00:28

Variable(입력 변수)

인프라를 구성하는데 필요한 속성 값을 정의해 코드의 변경 없이 여러 이프라를 생성하는데 목적이 있다.
Plan 수행시 값을 입력한다.

 

변수 선언 방식

  • variable로 시작되며, 그 뒤에는 이름이 온다.
    • 이름은 동일 모듈 내 모든 변수 선언에서 고유해야 하며, 다른 코드에서 해당 이름으로 참조한다.
variable "이름" {
  <인수> = <값>
}
  • 변수 정의 시 사용 불가능한 이름
    • source, version, provideres, count, for_each, lifecycle, depends_on, locals
  • 메타 인수 목록
    • default: 변수에 할당되는 기본값
    • type: 변수에 허용되는 값 유형
    • description: 입력 변수의 설명
    • validation: 변수 선언의 제약조건을 추가해 유효성 검사 규칙을 정의
    • sensitive: 민감한 변수 임을 알리고 테라폼 출력문에서 값 노출을 제한
    • nullable: 변수에 값이 없어도 됨

 

변수 유형

  • 기본 유형
    • string: 글자
    • number: 숫자
    • bool: true or false
    • any: 명시적으로 모든 유형이 허용됨
  • 집합 유형
    • list: 인덱스 기반 집합
    • map: 속성 기반 집합이며 키값 기준으로 정렬
    • set: 값 기반 집합이며 키값 기준 정렬
    • object
    • tuple
# string sample
variable "string" {
  type        = string
  description = "글자 유형"
  default     = "my-string"
}

# number sample
variable "number" {
  type        = number
  description = "숫자 유형"
  default     = 1
}

# bool sample
variable "boolean" {
  type        = bool
  description = "true or false (Default, false)"
  default     = false
}

# list sample
variable "list" {
  type        = list(string) # list 내 string 만 허용
  description = "List"
  default     = ["aws", "google cloud", "azure"]
}

# list reference
output "list_first" {
  value = var.list.0 # 인덱스로 접근
}
#''' output
# "list_first": {
#     "value": "aws",
#     "type": "string"
# }
# '''
output "list_all" {
  value = var.list
}
# ''' output
# "list_all": {
#     "value": [
#     "aws",
#     "google cloud",
#     "azure"
# ]
# '''

variable "map" {
  type        = map(string) # 값에 string 만 허용
  description = "map"
  default = {
    amazon    = "aws" # 키 = 값
    microsoft = "azure"
    google    = "google cloud"
  }
}

output "map_amazon" {
  value = var.map.amazon # 키로 접근
}
# ''' output
# "map_amazon": {
#     "value": "aws",
#     "type": "string"
# }
# '''

output "map_all" {
  value = var.map
}
# ''' output
# "map_all": {
#     "value": {
#     "amazon": "aws",
#     "google": "google cloud", # 키 기준으로 정렬되서 출력된다.
#     "microsoft": "azure"
# }
# '''

variable "set" {
  type        = set(string) # 값에 string 만 허용
  description = "set"
  default = [
    "google",
    "amazon",
    "microsoft"
  ]
}

output "set_all" {
  value = var.set
}
# ''' output 
# "set_all": { # list와 다르게 값이 정렬된다.
#     "value": [
#     "amazon",
#     "google",
#     "microsoft"
#     ],
#     "type": [
#     "set",
#     "string"
#     ]
# }
# '''

variable "object" {
  type = object({
    name = string
    age  = number
  })
  description = "object"
  default = {
    name = "임승현"
    age  = 28
  }
}

output "object_all" {
  value = var.object
}
# '''output
# "object_all": {
#     "value": {
#     "age": 28,
#     "name": "임승현"
#     },
#     "type": [
#     "object",
#     {
#         "age": "number",
#         "name": "string"
#     }
#     ]
# }
# '''

variable "tuple" {
  type        = tuple([string, number])
  description = "tuple"
  default     = ["임승현", 28]
}

output "tuple_all" {
  value = var.tuple
}

# '''output
# "tuple_all": {
#     "value": [
#     "임승현",
#     28
#     ],
#     "type": [
#     "tuple",
#     [
#         "string",
#         "number"
#     ]
#   ]
# }
# '''

 

유효성 검사

  • 0.13 버전 이후부터 사용자 지정 유효성 검사가 가능해졌다.
  • validation 블록에서 condition에 지정되는 규칙이 true 혹은 false를 반환하도록 지정해야한다. condition이 false인 경우 출력되는 에러 메시지를 지정한다.
  • regex 함수로 문자열에 정규식을 적용하고 일치하는 문자열을 반환하는데, can 함수와 함께 사용하면 정규식에 일치하지 않은 경우의 오류를 검출한다.
  • validation 블록은 중복으로 선언할 수 있다.

main.tf

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-\"."
  }
}

유효한 값 입력시
유효하지 않는 값 입력시
유효하지 않는 값 입력시

 

변수 참조

  • var.<이름>으로 참조할 수 있다.

main.tf

variable "my_password" {}

resource "local_file" "abc" {
  content  = var.my_password # 변수 참조
  filename = "${path.module}/abc.txt"
}

password 입력
password 입력 완료!

 

민감한 변수 취급

  • 0.14 버전 이후부터 입력 변수에 민감 여부를 선언할 수 있다.
  • sensitive = true를 추가하면 적용이 가능하다.

main.tf

variable "my_password" {
  sensitive = true
}

resource "local_file" "abc" {
  content  = var.my_password # 변수 참조
  filename = "${path.module}/abc.txt"
}

password 입력 (입력 값이 출력되지 않음)
password 가 정상 입력된 것을 확인

 

변수 입력 방식과 우선순위

  • variable은 코드 내용을 수정하지 않고 입력되는 변수를 재사용하는데 있다.
    • 입력되는 변수라는 의미에 맞게 프로비저닝 실행시 원하는 값을 변수에 정의할 수 있다.
  • 선언되는 방식에 따라 변수의 우선순위가 있으므로, 적절히 사용해 로컬 환경과 빌드 서버 환경에서의 정의를 다르게 하거나, 프로비저닝 파이프라인을 구성하는 경우 외부 값을 변수에 지정할 수 있다.

Variable Precedence (https://spacelift.io/blog/terraform-tfvars)

main.tf

variable "my_var" {}

resource "local_file" "abc" {
  content  = var.my_var
  filename = "${path.module}/abc.txt"
}

[우선순위 수준 1] 실행 후 입력 (CLI입력)

terraform apply -auto-approve
var.my_var
  Enter a value: var1 
'''

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var1"
'''

[우선순위 수준 2] variable 블록의 default

  • main.tf 수정
variable "my_var" {
  default = "var2"
}

resource "local_file" "abc" {
  content  = var.my_var
  filename = "${path.module}/abc.txt"
}
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var2"

[우선순위 수준 3] 환경 변수 (TF_VAR 변수 이름)

export TF_VAR_my_var=var3

terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var3"

[우선순위 수준 4] terraform.tfvars에 정의된 변수 선언

terraform.tfvars

my_var="var4"
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var4"

[우선순위 수준 5] *.auto.tfvars에 정의된 변수 선언

  • 파일명의 알파벳 순서에 따라 우선순위가 적용

a.auto.tfvars

my_var="var5"
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var5"

b.auto.tfvars

my_var="var6"
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var6"

[우선순위 수준 6] *.auto.tfvars.json에 정의된 변수 선언

  • *.auto.tfvars와 같이
  • 파일명의 알파벳 순서에 따라 우선순위가 적용

a.auto.tfvars.json

{
    "my_var": "var7"
}
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var7"

b.auto.tfvars.json

{
    "my_var": "var8"
}
terraform apply -auto-approve

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var8"

[우선순위 수준 7] CLI 실행 시 -var 인수에 지정 혹은 -var-file로 파일 지정

# -var=<이름>=<값>
terraform apply -auto-approve -var=my_var=var9

terraform state show local_file.abc           
# local_file.abc:
resource "local_file" "abc" {
    content              = "var9"

# 마지막에 지정한 값이 할당된다.
terraform apply -auto-approve -var=my_var=var9 -var=my_var=var10
terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var10"
# -var_file=<파일명>
terraform apply -auto-approve -var-file=a.auto.tfvars.json

terraform state show local_file.abc
# local_file.abc:
resource "local_file" "abc" {
    content              = "var7"
728x90

'IaC > Terraform' 카테고리의 다른 글

[T102] 반복문  (0) 2023.07.16
[T102] Output  (0) 2023.07.16
[T102] Local  (0) 2023.07.16
[T102] Data Source  (0) 2023.07.15
[T102] Terraform 설치 및 튜토리얼  (0) 2023.07.09