Dynamic input to template

I’m evaluating switching to packer from some home-grown scripts. Overall it looks very nice, but there are a couple of things I’m not sure how to accomplish:

  1. I want to use a source AMI that is the newest image that matches that filters that is older than a certain amount of time (say a week), because I use a mirrorered apt repo that is sometimes behind the most up-to-date available AMI.
  2. For some AMIs I’d like the root volume to be at least as large as the amount of available RAM plus some base amount, so that heap dumps are guaranteed to fit on disk. I’d like to compute this by looking up the amount of ram for the ec2 instance type being used.

Both of these could be accomplished if there was a way to call out to an external script with something like a shell function, but there doesn’t seem to be any such mechanism. The only way I can think to handle this would be to have something that generates a variables file, but that seems kind of clunky, especially for 2, since the computation itself depends on the instance-type.

Somewhat related, what is the best practice for automating using packer to create AWS AMIs on a schedule? I’d like to use something like a lambda function or maybe a fargate container, but it seems like I’d need to wrap packer with some extra setup as well. Is there any best-practices or guidance on doing something like that.

The way we recommend to find those kinds of dynamic values that aren’t directly related to Packer is to use a wrapping script. Your script can find those values before the packer run, store them as variables, then pass the values in as runtime arguments using Packer’s -var option. So, for example, if your scripts determines that you should use ami-12345, you’d call packer build -var 'myami=ami-12345' mytemplate.json and inside your template set:

"source_ami": "{{ user `myami`}}" if your template is json or

source_ami = var.myami if your template is HCL