12

I have a packer json like:

"builders": [{...}],
"provisioners": [
          {
                "type": "file",
                "source": "packer/myfile.json",
                "destination": "/tmp/myfile.json"
           }
  ],
"variables": {
        "myvariablename": "value"
 }

and myfile.json is:

{
   "var" : "{{ user `myvariablename`}}"
}

The variable into the file does get replaced, is a sed replacement with shell provisioner after the file the only option available here?

Using packer version 0.12.0

MarMan
  • 328
  • 2
  • 3
  • 9

4 Answers4

12

You have to pass these as environment variables. For example:

  "provisioners": [
    {
      "type": "shell"
      "environment_vars": [
        "http_proxy={{user `proxy`}}",
      ],
      "scripts": [
        "some_script.sh"
      ],
    }
  ],
  "variables": {
    "proxy": null
  }

And in the script you can use $http_proxy

slm
  • 15,396
  • 12
  • 109
  • 124
Rickard von Essen
  • 4,110
  • 2
  • 23
  • 27
  • 1
    environment_vars works just for the shell provisioner, not for the file: https://www.packer.io/docs/provisioners/file.html – MarMan Jun 21 '17 at 14:07
1

So far I've come just with the solution to use file & shell provisioner. Upload file and then replace variables in file via shell provisioner which can be fed from template variables provided by e.g. HashiCorp Vault

aRagornol
  • 235
  • 3
  • 17
0

Yo may use OS export function to set environment and pass it to Packer

Here is a config using OS ENV_NAME value to choose local folder to copy from export ENV_NAME=dev will set local folder to dev

{
  "variables": {
    ...
    "env_folder": "{{env `ENV_NAME`}}",
  },
  "builders": [{...}]
  "provisioners": [
    {
      "type": "file",
      "source": "files/{{user `env_folder`}}/",
      "destination": "/tmp/"
    },
    {...}
  ]
}
Roman Shishkin
  • 2,097
  • 20
  • 21
-3

User variables must first be defined in a variables section within your template. Even if you want a user variable to default to an empty string, it must be defined. This explicitness helps reduce the time it takes for newcomers to understand what can be modified using variables in your template.

The variables section is a key/value mapping of the user variable name to a default value. A default value can be the empty string. An example is shown below:

 {
 "variables": {
"aws_access_key": "",
 "aws_secret_key": ""
 },

"builders": [{
"type": "amazon-ebs",
"access_key": "{{user `aws_access_key`}}",
"secret_key": "{{user `aws_secret_key`}}",
// ...
}]
}

check this link for more information

  • Thanks Favour, but the question is more about how to use the variables in an external file (with file provisioner) used by Packer – MarMan Jun 21 '17 at 10:31