variable 블록

variable 블록

variable 블록에 대한 레퍼런스 정보를 제공하는 문서예요. Packer 설정 안에서 변수를 선언하고 값을 할당하는 방법을 다룹니다.

출처: Packer 공식 문서

본문

설명 (Description)

variable 및 input-variable 블록은 Packer 구성 안에서 변수를 정의해요. input-variable 블록을 다른 input-variable 블록 안에서 사용할 수는 없습니다. 변수를 중첩하려면 locals를 사용하는 것을 권장해요.

# variables.pkr.hcl
variable "foo" {
    type        = string
    default     = "the default value of the `foo` variable"
    description = "description of the `foo` variable"
    sensitive   = false
    # When a variable is sensitive all string-values from that variable will be
    # obfuscated from Packer's output.
}

기본값 (Default value)

기본값이 설정되면 그 변수는 선택 사항이에요. 그렇지 않으면 변수를 반드시 설정해야 합니다.

입력 변수에 값 할당하기

구성에서 변수를 선언한 뒤 다음 방법으로 설정할 수 있어요.

  • 개별적으로, -var foo=bar 커맨드라인 옵션으로.
  • 변수 정의 파일에서, 커맨드라인에서 -var-files values.pkrvars.hcl로 지정하거나 자동으로 로드(*.auto.pkrvars.hcl)해서.
  • 환경 변수로, 예: PKR_VAR_foo=bar

사용자 정의 검증 규칙 (Custom Validation Rules)

타입 제약(Type Constraints)에 더해, 해당 variable 블록 안에 중첩된 하나 이상의 validation 블록을 사용해 특정 변수에 대한 임의의 사용자 정의 검증 규칙을 지정할 수 있어요.

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 && substr(var.image_id, 0, 4) == "ami-"
    error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"."
  }
}

condition 인자는 값이 유효하면 true를, 유효하지 않으면 false를 반환하기 위해 반드시 변수의 값을 사용해야 하는 표현식이에요. 이 표현식은 조건이 적용되는 변수만 참조할 수 있으며, 오류를 발생시키면 안 됩니다.

표현식의 실패가 검증 결정의 근거라면 can 함수를 사용해 그런 오류를 감지하세요. 예를 들면 다음과 같습니다.

variable "image_id" {
  type        = string
  description = "The ID of the machine image (AMI) to use for the server."
  validation {
    # regex(...) fails if it cannot find a match
    condition     = can(regex("^ami-", var.image_id))
    error_message = "The image_id value must be a valid AMI ID, starting with \"ami-\"."
  }
}

condition이 false로 평가되면 error_message에 주어진 문장들을 포함하는 오류 메시지가 만들어져요. 오류 메시지 문자열은 위 예시들과 비슷한 문장 구조로, 실패한 제약을 설명하는 완전한 문장 하나 이상이어야 합니다.

검증은 더 복잡한 경우에도 동작해요.

variable "image_metadata" {
  default = {
    key: "value",
    something: {
      foo: "bar",
    }
  }
  validation {
    condition     = length(var.image_metadata.key) > 4
    error_message = "The image_metadata.key field must be more than 4 runes."
  }
  validation {
    condition     = can(var.image_metadata.something.foo)
    error_message = "The image_metadata.something.foo field must exist."
  }
  validation {
    condition     = substr(var.image_metadata.something.foo, 0, 3) == "bar"
    error_message = "The image_metadata.something.foo field must start with \"bar\"."
  }
}

파일에서 변수를 할당하는 예시:

# foo.pkrvars.hcl
foo = "value"

변수 값은 알려져 있어야 해요 (A variable value must be known):

다음 변수를 예로 들어 볼게요.

variable "foo" {
  type = string
}

여기서 foo는 알려진 값을 가져야 하지만, null로 기본값을 설정하면 이 동작을 선택 사항으로 만들 수 있어요.

no default default = null default = "xy"
foo unused error, "foo needs to be set" - -
var.foo error, "foo needs to be set" null¹ xy
PKR_VAR_foo=yz var.foo yz yz yz
-var foo=yz var.foo yz yz yz

1: Null은 유효한 값이에요. Packer는 받는 필드가 값을 필요로 할 때만 오류를 냅니다. 예:

variable "example" {
  type = string
  default = null
}
source "example" "foo" {
  arg = var.example
}

위의 경우 "example" 소스에서 "arg"가 선택 사항인 한 오류가 없고 arg는 설정되지 않아요.

민감한 변수 숨기기 (Suppressing Sensitive Variables)

변수가 민감(sensitive)하면 그 변수의 모든 문자열 값이 Packer 출력에서 난독 처리(obfuscated)돼요.

# var-foo.pkr.hcl
variable "foo" {
    sensitive = true
    default   = {
        key = "SECR3TP4SSW0RD"
    }
}
$ packer inspect var-foo.pkr.hcl
Packer Inspect: HCL2 mode
> input-variables:
var.foo: "{\n  \"key\" = \"<sensitive>\"\n }"
...

변수에 대해 더 알아보기

  • 더 철저하게 읽으려면 전체 변수 설명(variables description)을 읽어 보세요.
  • 더 많은 예시는 변수 가이드(variables guide)를 읽어 보세요.