Configuring variables

Variables are used to inject user-specific or environment-specific settings into your templates at build time, which is useful for making your machine image templates more generic and avoids the hardcoding of credentials in your templates.

Back in the previous example, you referenced user variables when defining AWS credential settings, and these must be defined in the variables section of your Packer template, as demonstrated in the previous example:

{
"variables": {
"aws_access_key_id": "{{env `AWS_ACCESS_KEY_ID`}}",
"aws_secret_access_key": "{{env `AWS_SECRET_ACCESS_KEY`}}",
"aws_session_token": "{{env `AWS_SESSION_TOKEN`}}",
"timezone": "US/Eastern"
},
"builders": [
{
"type": "amazon-ebs",
"access_key": "{{user `aws_access_key_id`}}",
"secret_key": "{{user `aws_secret_access_key`}}",
"token": "{{user `aws_session_token`}}",
"region": "us-east-1",
"source_ami": "ami-5e414e24",
"instance_type": "t2.micro",
"ssh_username": "ec2-user",
"associate_public_ip_address": "true",
"ami_name": "docker-in-aws-ecs {{timestamp}}",
"tags": {
"Name": "Docker in AWS ECS Base Image 2017.09.h",
"SourceAMI": "{{ .SourceAMI }}",
"DockerVersion": "17.09.1-ce",
"ECSAgentVersion": "1.17.0-2"
}
}
],
"provisioners": [],
"post-processors": []
}
Defining variables

In the preceding example, notice that you define each of the variables referenced in the user functions for the AWS credential settings in the builders section. For example, the builders section defines the access_key setting as {{user `aws_access_key_id`}}, which in turn references the aws_access_key_id variable defined in the variables section.

Each variable in turn references the env template function, which looks up the value of the environment variable passed to this function. This means you can control the value of each of the variables as follows:

Notice that we haven't defined the timezone variable yet in our Packer template, as you will use this variable later on in this chapter.