How to add multiple servers to a LoadBalancer in Hetzner Cloud with Terraform?

Viewed 685

Currently trying to get the new Hetzner Load Balancer working with multiple servers using Terraform v0.12.28. Provided documentation shows only case of one sever which is quite weird for a load balancer :)

Servers are created using count like this:

 resource "hcloud_server" "web" {
  count       = var.instances
  name        = "web-server-${count.index}"
...
}

and to add a server to the load balancer one should use the pattern like this:

    target {
    type = "server"
    server_id = hcloud_server.web.id
  }

Yet any kind of for or for_each seems not applicable here to add all created instances.

Could you please show me the direction how to add count-created servers to the load balancer?

Thanks!

2 Answers

I've been trying to do the same and I ended up changing the type of the target from server to label.

On each resource you can set a label, for example "env=dev" and then on your load balancer you use the type label, and then label_selector to match your label.

Example:

resource "hcloud_server" "node1" {
  name = "node1"
  image = "debian-9"
  server_type = "cx11"
  labels = {"env" : "dev"}
}

resource "hcloud_load_balancer" "load_balancer" {
  name       = "my-load-balancer"
  load_balancer_type = "lb11"
  location   = var.instance_location
}

resource "hcloud_load_balancer_target" "load_balancer_target" {
  type             = "label_selector"
  load_balancer_id = hcloud_load_balancer.load_balancer.id
  label_selector   = "env=dev"
}

I think that dynamic blocks could be used in your situation.

You could possibly do something similar to the following (dynamic block is the target; example from docs, so it may require adjustment to your real code):

resource "hcloud_load_balancer" "load_balancer" {

  name       = "my-load-balancer"
  load_balancer_type = "lb11"
  location   = "nbg1"


  dynamic "target" {

    for_each = hcloud_server.web

    content {
        type = "server"
        server_id = target.value["id"]
    }   

  }

}
Related