Getting the Source AMI id when using HCL configuration

I’m looking to add the source AMI ID to a tag of a new AMI when using the HCL config format, is there an equivalent to using .SourceAMI yet? If that still works then please let me know how as I’ve not got anything working yet! :slight_smile:

Thanks

1 Like

Anyone know if this is possible yet?

Yes! here’s a working config with several examples:

(This is on v1.6.1 which dropped yesterday)

source "amazon-ebs" "basic-example" {
  region =  "us-east-1"
  source_ami_filter {
    filters = {
       virtualization-type = "hvm"
       name = "ubuntu/images/*ubuntu-xenial-16.04-amd64-server-*"
       root-device-type = "ebs"
    }
    owners = ["099720109477"]
    most_recent = true
  }
  instance_type =  "t2.small"
  ssh_username =  "ubuntu"
  ami_name =  "packer_AWS {{timestamp}}"
}

build {
  sources = [
    "source.amazon-ebs.basic-example"
  ]

  provisioner "shell-local"{
    inline = ["echo '${build.SourceAMIName}'"]
    environment_vars = ["HELLO_USER=packeruser", "SOURCE_AMI_NAME=${build.SourceAMIName}"]
    execute_command = ["/bin/sh", "-c", "echo '${build.SourceAMIName}'", "{{.Vars}} {{.Script}}"]
  }
}

edit: this example use SourceAMIName but it will also work for SourceAMI:

use ${build.SourceAMI} if embedding it in a string (most likely), or build.SourceAMI if you’re setting it as a standalone value in an option

That probably does work, but counter intuitively the tags for the AMI are set in the source definition where .SourceAMI isn’t currently available, https://www.packer.io/docs/builders/amazon/ebs#tag-example shows an example of setting a tag but I get:

This object does not have an attribute named "SourceAMI"

If I try:

  tag {
    key = "ami_id"
    value = "{{ .SourceAMI }}"
  }

Hmm. I think you’re going to have to define any tag that includes these specialized template engines inside the source rather than as standalone variables that you bring into the source. This works for me on v1.6.1:

source "amazon-ebs" "basic-example" {
  region = "us-east-1"
  source_ami_filter {
    filters = {
      virtualization-type = "hvm"
      name                = "ubuntu/images/*ubuntu-xenial-16.04-amd64-server-*"
      root-device-type    = "ebs"
    }
    owners      = ["099720109477"]
    most_recent = true
  }
  instance_type = "t2.small"
  ssh_username  = "ubuntu"
  ami_name      = "packer_AWS {{timestamp}}"
  tags = {
        Base_AMI_ID = "{{ .SourceAMI }}"
        Base_AMI_Name = "{{ .SourceAMIName }}"
    }
}

OK, not sure what I was doing wrong before, but that does work now, strange, but thanks for the help