How to use the AWS availability zone in a template block

What would be the way to get the AWS availability zone directly in the template block?

The following doesn’t work, but just to show what I have tried so far. :frowning:

job "redis" {
  region = "us-east-1"
  datacenters = ["us-east-1"]

  group "cache" {

    network {
      port "db" {
        to = 6379
      }
    }

    task "redis" {
      template {
        data = <<EOT
your DC is [${NOMAD_DC}]
your DC is [${MY_DC}]
your AZ is [${attr.platform.aws.placement.availability-zone}]
EOT
        destination = "local/one.txt"
      }

      template {
        data = <<EOT
your DC is [${NOMAD_DC}]
your DC is [${MY_DC}]
your AZ is [${MY_AZ}]
EOT
        destination = "local/two.txt"
      }

      driver = "docker"

      config {
        image = "redis:3.2"
        auth_soft_fail = true

        ports = ["db"]

      }
      env {
        MY_DC="${NOMAD_DC}"
        MY_AZ="${attr.platform.aws.placement.availability-zone}"
      }

      resources {
        cpu    = 500
        memory = 256
      }
    }
  }
}

never mind, the following works, will involve a bit of jugglery, but it works:

job "az2" {
  region = "us-east-1"
  datacenters = ["us-east-1"]

  group "cache" {

    task "redis" {

      template {
        data = <<EOT
#!/bin/bash

set -u
set -e

env | sort

echo "Done"
sleep infinity
EOT
        destination = "local/runme.bash"
      }

      driver = "raw_exec"

      config {
        command = "/bin/bash"
        args = ["local/runme.bash"]
      }

      env {
        MY_DC="${NOMAD_DC}"
        MY_AZ="${attr.platform.aws.placement.availability-zone}"
      }

      resources {
        cpu    = 500
        memory = 256
      }
    }
  }
}

Howdy @shantanugadgil :wave:

You should be able to get use the env function inside of the template to get that value.

template {
  data = <<EOT
{{ env "attr.platform.aws.placement.availability-zone" }}
EOT
  destination = "local/out.txt"
}

Hopefully this helps future template adventurers.

Best,
Charlie

1 Like

This works as expected, this usage of {{ env "...." }} should be in more examples!!! :+1: :+1: