Packer Variables
Packer variables explained with examples
Website Visitors:There are different ways in which you can pass variables into Packer template. In this tutorial, we will explain all different ways you can pass variables in to your Packer template.
Declaring Variables in the template file
If you have AWS cli installed, you can then use aws configure command to store credentials in ~/.aws/configure file. But in your remote servers, you might not have aws cli installed. For this, you can pass the aws access key and secret key in variables section in the Packer script file or in the packer build command directly.
|
|
If the default value is null
, then the user variable will be required. This means that the user must specify a value for this variable or template validation will fail.
User variables are used by calling the {{user}}
function in the form of {{user 'variable'}}
. This function can be used in any value but type
within the template: in builders, provisioners, anywhere outside the variables
section. User variables are available globally within the rest of the template.
When you run the packer build command you have to specify the aws access key and secret key as: packer build -var "aws_access_key=ACCESSKEY" -var "aws_secret_key=SECRETKEY" Template.json
Separating Variables to a file
To separate variables to a file, you should create a file and specify the access key and secret key. Let’s look at how to do it.
Create a file called variables.json (you can name it anything), copy the below code to it and save it.
|
|
In your Packer build command, using the parameter, -var-file
run the command as: packer build -var-file variables.json Template.json
. Packer will read that variables file and run the build.
|
|
Using environment variables
You can also add your variables to environment variables in your system and refer them in the packer template file. With this, you do not have to specify aws credentials in the template file or in the build command or in variable file.
|
|
Along with the above mentioned options, you can also use AWS Secrets Manager or use Hashicorp Vault and read those credentials to your packer template.
Suggested Article
If you’d like to checkout Packer definitions, you can do it here: Packer Definitions. All other DevOps categories are listed here: DevOps Tools. Have a look at the posts as per your topic of interest.
Conclusion
In this tutorial, we’ve explained Packer variables and different ways on how to use them. We’ve also demonstrated examples for all the topics that are discussed. We hope you have learned something new in this article.
Now that you know about variables in Packer, would you use variables or use the values directly in the script? Let us know in the comments section below.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.