»env Function

variable "aws_region" {
  default = env("AWS_DEFAULT_REGION")
}
variable "aws_region" {  default = env("AWS_DEFAULT_REGION")}

env allows you to get the value for an environment variable inside input variables only. This is the only function that is callable from a variable block and it can only be used in the default input. env cannot be called from other places.

In the previous example, the value of aws_region will be what's stored in the AWS_DEFAULT_REGION env var, unless aws_region is also set in a manner that takes precedence.

When the environment variable is not set at all -- not even with the empty string -- the value returned by env will be an an empty string. It will still be possible to set it using other means but you could use custom validation rules to error in that case to make sure it is set, for example:

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
  }
}
variable "aws_region" {  default = env("AWS_DEFAULT_REGION")
  validation {    condition     = length(var.aws_region) > 0    error_message = <<EOFThe 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  }}