hashicorp / packer

Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
http://www.packer.io
Other
15.12k stars 3.33k forks source link

Unable to set variable from environment variable #13123

Closed DarrenDotmatics closed 3 months ago

DarrenDotmatics commented 3 months ago

Community Note

Overview of the Issue

Following documentation here https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/contextual/env to try to set a variable with the value of a local environment variable.

Eventually found this discussion https://discuss.hashicorp.com/t/hcl2-environment-variables/9290 which did work, but is not what is in the documentation.

Reproduction Steps

Run the template using PKR_VAR_AWS_REGION="eu-west-1" PACKER_LOG=1 packer build ./ Out put should be: null.nullbuilder: [eu-west-1] [] []

Packer version

Packer v1.11.1

Simplified Packer Template

variable "AWS_REGION" { type = string }

variable "test_aws_region" { type = string default = env("AWS_REGION") }

variable "test_aws_region2" { type = string default = "${env("AWS_REGION")}" }

source "null" "nullbuilder" { communicator = "none" }

build { sources = ["source.null.nullbuilder"] provisioner "shell-local" { inline = ["echo [${var.AWS_REGION}] [${var.test_aws_region}] [${var.test_aws_region2}]"] } }

Operating system and Environment details

MacOs(x64) and also ran in hashicorp/packer docker container on docker desktop.

Log Fragments and crash.log files

https://gist.github.com/DarrenDotmatics/6b42ea10b55ef8ef478d1c432d5ad2b0

lbajolet-hashicorp commented 3 months ago

Hi @DarrenDotmatics,

This seems like a usage error in this case? If the variable is undefined, the env("AWS_REGION") will be empty, which I suspect is what happens here.

If you define AWS_REGION in your environment, that does what you'd expect

$ PKR_VAR_AWS_REGION="eu-west-1" AWS_REGION="us-east-1" packer build ./
null.nullbuilder: output will be in this color.

==> null.nullbuilder: Running local shell script: /tmp/packer-shell2326167547
    null.nullbuilder: [eu-west-1] [us-east-1] [us-east-1]
Build 'null.nullbuilder' finished after 3 milliseconds 989 microseconds.

==> Wait completed after 4 milliseconds 6 microseconds

==> Builds finished. The artifacts of successful builds are:
--> null.nullbuilder: Did not export anything. This is the null builder
DarrenDotmatics commented 3 months ago

OK thank you. Not sure why this was not working in my production script, will have to look at my script again.

github-actions[bot] commented 2 months ago

I'm going to lock this issue because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues. If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.