Consul service discovery in same datacenter

How would you create a nomad template that ensures connections are made inside the same datacenter?

For example, this works, but if I have dc1 and dc2, It won’t guarantee to resolve a postgres server in the same datacenter as the job

template {
  data = <<EOH
foo = postgres.service.consul
  EOH
  destination = "local/foobar.xml"
}

So far I’ve tried using attr.consul.datacenter

template {
  data = <<EOH
foo = postgres.service.${attr.consul.datacenter}.consul
  EOH
  destination = "local/foobar.xml"
}

and NOMAD_DC

template {
  data = <<EOH
foo = postgres.service.${env["NOMAD_DC"]}-${env["NOMAD_REGION"]}.consul
  EOH
  destination = "local/foobar.xml"
}
template {
  data = <<EOH
foo = postgres.service.${NOMAD_DC}-${NOMAD_REGION}.consul
  EOH
  destination = "local/foobar.xml"
}

By using consul template variable interpolation syntax {{ }} it is possible to rewrite the contents of a config file.

template {
  data = <<EOH
foo = postgres.service.{{ env "NOMAD_DC" }}-{{ env "NOMAD_REGION" }}.consul
  EOH
  destination = "local/foobar.xml"
}

Assuming foobar.xml is mounted at /, you can verify the contents with nomad alloc.

nomad alloc exec <allocId> cat /foobar.xml

1 Like

Yes, in templates you will need to use the {{ env "ENVIRONMENT_VARIABLE_NAME" }} / {{ env "attr.something.value" }} syntax to get the value.

e.g.

{{ env "attr.unique.network.ip-address" }} and {{ env "NOMAD_TASK_NAME" }}