HCL2 Environment Variables

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