HCL2 Environment Variables

I am trying to use an env var AWS_REGION but not too sure how to do it using HCL2. I am looking at the guide here https://www.packer.io/guides/hcl/variables/

I am tried using “${var.PKR_VAR_AWS_REGION}” and PKR_VAR_AWS_REGION in my hcl script, but it doesn’t seem to recognize the variable. Can someone help?

Hi @brianpham thanks for reaching out. The use of environment variables with HCL can be a little tricky because they are referenced differently from what they are named. More specifically, the PKR_VAR prefix is needed to tell Packer that it is an environment variable it should know about, but when you reference the variable you have to drop the PKR_VAR prefix. Below is an example HCL file to illustrate the usage.

variable "AWS_REGION" {                                                                                                                            
  type = string                                                                                                                                    
source "null" "nullbuilder" {                                                                                                                      
  communicator = "none"                                                                                                                            
build {                                                                                                                                            
  sources = ["source.null.nullbuilder"]                                                                                                            
  provisioner "shell-local" {                                                                                                                      
    inline = ["echo ${var.AWS_REGION}"]                                                                                                            

To set the AWS_REGION variable within the HCL file you can then run (using Shell env variable reference)

PKR_VAR_AWS_REGION=$AWS_REGION packer build template.pkr.hcl

Please let me know if this helps you move forward with the build or if you have any other questions. In the meantime, I’ll see about adding a few more examples to the HCL variables documentation. Cheers!

1 Like