Packer validate throws Error: Unset variable

just want to ask on what I’m missing here. when I tried to issue the command “packer validate .” it gives me this message.

# packer validate .
Error: Unset variable "env"

A used variable must be set or have a default value; see
https://packer.io/docs/templates/hcl_templates/syntax for details.

main.pkr.hcl code:

packer {
  required_plugins {
    amazon = {
      version = ">= 0.0.2"
      source  = "github.com/hashicorp/amazon"
    }
  }
}

source "amazon-ebs" "ec2" {
  ami_name      = "${lookup(var.ami_name, var.env)}-${local.timestamp}-ami"
  instance_type = "${var.instance_type}"
  ...
  ...
  ...
}
build {
  name = "builder"
  sources = [
    "source.amazon-ebs.ec2"
  ]
  provisioner "file" {
    ...
    ...
  }
}

variables.pkr.hcl code:

variable "env" {}
variable "ami_name" {
  type = map(string)
  default = {
    playground = "123"
    production = "890"
  }
 variable "instance_type" {
   type    = string
   default = "t3a.nano"
  }
  ...
  ...
}

I have tried to place default value on env but it still gives much more error, not sure …

Hi @lagot.ako.talaga,

From what I can see, you are defining the variable, but indeed are not setting its value, so when trying to validate it, Packer points out that the template cannot be run as-is, since env does not have a default value, nor one set through the -var command-line argument.

If you do set a default value this error should go away, I would also suggest adding a type for this variable.

Let us know if you need more help with this, good luck with your template!