Help putting NOMAD_ALLOC_INDEX inside a secret templating common_name

I’m having trouble getting NOMAD_ALLOC_INDEX into the common_name when issuing certificates. I’ve got the following template:

      template {
        destination = "${NOMAD_SECRETS_DIR}/ca.crt"
        change_mode   = "restart"
        data        = <<-EOF
        {{$allocID := env "NOMAD_ALLOC_INDEX" -}}
        {{  with secret "pki/issue/myrole" "common_name=myservice$allocID.services.consul" "ttl=8760h" "ip_sans=127.0.0.1" }}
        {{ .Data.certificate }}
        {{ end }}
        EOF
      }

However, it appears nomad as trying to issue a certificate for myservice$allocID instead of putting the value of NOMAD_ALLOC_INDEX in to it.

I’ve tried this aswell:

"common_name=myservice$NOMAD_ALLOC_INDEX.services.consul"

and this

"common_name=myservice{{ env "NOMAD_ALLOC_INDEX" }}.services.consul"

but this last one is very unhappy with that, as it does not like having curlybraces inside curlybraces.

Is this possible at all?

I also tried

"common_name=myservice${NOMAD_ALLOC_INDEX}.services.consul"

and no luck

Okay I think I worked it out after finding this support article

This

      template {
        destination = "${NOMAD_SECRETS_DIR}/ca.crt"
        change_mode = "restart"
        data        = <<-EOF
        {{- $VAR1 := (printf "common_name=myservice%s.services.consul" (env "NOMAD_ALLOC_INDEX")) -}}
        {{- $VAR2 := (printf "ip_sans=%s" (env "attr.unique.network.ip-address")) -}}
        {{ with secret "pki/issue/myrole" $VAR1 "ttl=8760h" $VAR2 }}
        {{ .Data.certificate }}
        {{ end }}
        EOF
      }