env Function
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.
Why can't I use environment variables elsewhere? User variables are the
single source of configurable input. We felt that having environment variables
used anywhere in a configuration would confuse the user about the possible inputs
to a template. By allowing environment variables only within default values for
input variables, input variables remain as the single source of input to a
template that a user can easily discover using packer inspect
.
When the environment variable is not set at all -- not even with the empty
string -- the value returned by env
will be 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: