You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
packer/website/content/docs/templates/hcl_templates/functions/contextual/env.mdx

54 lines
2.5 KiB

---
page_title: env function reference
description: The `env` function retrieves environment values for input variables. Learn how to use the `env` function in Packer templates.
---
⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
> [!IMPORTANT]
> **Documentation Update:** Product documentation previously located in `/website` has moved to the [`hashicorp/web-unified-docs`](https://github.com/hashicorp/web-unified-docs) repository, where all product documentation is now centralized. Please make contributions directly to `web-unified-docs`, since changes to `/website` in this repository will not appear on developer.hashicorp.com.
⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
# `env` Function
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.
```hcl
variable "aws_region" {
default = env("AWS_DEFAULT_REGION")
}
```
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](/packer/docs/templates/hcl_templates/variables#variable-definition-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](/packer/docs/templates/hcl_templates/variables#custom-validation-rules) to error in that case
to make sure it is set, for example:
```hcl
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
}
}
```