Registering a Service in Consul with Terraform for a Nomad Transit Gateway

I’m trying to register a consul_service using Terraform for a Nomad Terminating Gateway. This works fine when I register the service using the CLI:

consul services register demo-postgresql.hcl

Contents of hcl

service {
  name    = "demo-postgresql"
  address = "some.redacted.address.here"
  port = 5432
  meta = {
    external-node = "true",
    external-probe = "true"
  }
  tags = [ "postgresql", "rds" ]
}

When I try and move this into Terraform, the service keeps getting removed due to anti-entropy. How can I make this stick?

Terraform file

data "consul_service" "consul" {
  name = "consul"
}

resource "consul_service" "demo-postgresql" {
  node    = data.consul_service.consul.service.0.node_name
  name    = "demo-postgresql"
  address = "some.redacted.address.here"
  port    = 5432
  meta = {
    external-node  = "true"
    external-probe = "true"
  }
}

Hi @dwanek,

The docs for the consul_service resource has this notice at the beginning:

If a Consul agent is running on the node where this service is registered, it is not recommended to use this resource as the service will be removed during the next anti-entropy synchronization.

Since you’re using the node(s) that run the consul service (i.e., the servers) to register the Postgres service, these nodes are removing the Postgres service in their anti-entropy cycle.

The solution is to create a non-existent node in the catalog using the consul_node resource and associate the service to that node.

resource "consul_node" "external-node" {
  address = "192.0.2.10"
  name    = "external-node"
}

resource "consul_service" "demo-postgresql" {
  node    = consul_node.external-node.name
  name    = "demo-postgresql"
  address = "some.redacted.address.here"
  port    = 5432
  meta = {
    external-node  = "true"
    external-probe = "true"
  }
}

See the Use Terraform to Register External Services tutorial for more info.

1 Like

Thanks for the tip @blake! The fake node technique worked great. Much appreciated.