Share environment variables between tasks

Hello everyone,

I’m looking to share environment variables between several tasks of the same job. I can’t figure out if this is possible or not.

Here’s what I’m trying to do right now:

locals {
  env = {
    a = "a"
    b = "b"
  }
}

job "job" {
  group "group" {
    task "first" {
      env = local.env
    }

    task "second" {
      env = local.env
    }
  }
}

Is there a way to do something like this? For information, I use Terraform to deploy Nomad jobs.

Thank you very much in advance!

Hi @johynpapin :wave:

I don’t think HCL2 is able to handle this. You would need to use some templating tools like Levant.

You mentioned that you are using Terraform, so you could do something like this:

# main.tf
...
resource "nomad_job" "job" {
  jobspec = templatefile("${path.module}/job.nomad.tpl", {
    env = {
      "a" = "a"
      "b" = "b"
    }
  })
}
# job.nomad.tpl

job "job" {
  datacenters = ["dc1"]

  group "group" {
    task "first" {
      driver = "raw_exec"

      config {
        command = "env"
      }

      env {
        %{ for k, v in env }
          ${k} = "${v}",
        %{ endfor }
      }
    }

    task "second" {
      driver = "raw_exec"

      config {
        command = "env"
      }

      env {
        %{ for k, v in env }
          ${k} = "${v}",
        %{ endfor }
      }
    }
  }
}
2 Likes

Hi!

Thank you very much, this is exactly what I was looking for.

1 Like