Split user variable

Hello,

I have a variable defined like this:

os_version: {{ env `IMAGE_DEBIAN_VERSION` }},

I would like to create another variable with split from the previous one.
I tried this:

"os_version_major": "{{ split {{ user `os_version` }} \".\" 0 }}",

but it does not work …

Hi, good question! Unfortunately, split won’t work on user variables because the template engine can’t nest functions. This is documented here:

Please note that you cannot use the split function on user variables, because we can’t nest the functions currently. This function is indended to be used on builder variables like build_name. If you need a split user variable, the best way to do it is to create a separate variable.

That said, this is possible in the HCL templates, which have better variable handling than the golang text template used by the json versions of the Packer template:

// This example assumes that you have set the environemnt var
// PKR_VAR_os_version. For example: 
// `export PKR_VAR_os_version="10.0"`
// Any variable you want to set via the environment in HCL must be prefixed 
// with PKR_VAR and Packer will automatically load it for you.
variable "os_version" {
  type = string
}

locals {
    split_version = split(".",var.os_version)[0]
}

source "null" "example" {
  communicator = "none"
}

build {
  sources = [
    "source.null.example"
  ]
  provisioner "shell-local" {
    inline           = ["echo '${local.split_version}'"]
  }
}
1 Like