env 함수
env 함수
env 함수는 입력 변수 안에서 환경 변수의 값을 가져와요. variable 블록에서 호출할 수 있는 유일한 함수이고, 기본 입력(default)에서만 사용할 수 있어요.
출처: Packer 공식 문서
본문
The env function gets the value for an environment variable inside input variables. This is the only function that is callable from a variable block. You can only use the env function in the default input.
variable "aws_region" {
default = env("AWS_DEFAULT_REGION")
}
위 예시에서 aws_region의 값은, aws_region이 우선순위를 가지는 방식으로 별도로 설정되지 않는 한, AWS_DEFAULT_REGION 환경 변수에 저장된 값이 돼요.
왜 다른 곳에서는 환경 변수를 못 쓰나요? 사용자 변수는 설정 가능한 입력의 단일 출처(single source)예요. 환경 변수가 설정 어디서든 쓰일 수 있게 하면 템플릿에 넣을 수 있는 입력이 무엇인지 사용자가 혼란스러워질 거라고 판단했어요. 환경 변수를 입력 변수의 기본값 안에서만 허용함으로써, 입력 변수가 템플릿의 유일한 입력 출처로 남고, 사용자는 packer inspect로 쉽게 그 입력들을 발견할 수 있게 되는 거예요.
환경 변수가 전혀 설정되지 않았을 때 — 빈 문자열조차 아닐 때 — env가 돌려주는 값은 빈 문자열이에요. 다른 방법으로는 여전히 설정할 수 있지만, 그 경우엔 사용자 지정 검증 규칙(custom validation rules)을 써서 반드시 설정되도록 오류를 내게 할 수 있어요. 예를 들면:
variable "aws_region" {
default = env("AWS_DEFAULT_REGION")
validation {
condition = length(var.aws_region) > 0
error_message = <<EOF
The aws_region var is not set: make sure to at least set the AWS_DEFAULT_REGION env var.
To fix this you could also set the aws_region variable from the arguments, for example:
$ packer build -var=aws_region=us-something-1...
EOF
}
}