Simplify Terraform Configuration

0

is there any way in terraform to 'simplify' the configuration of things that need to be done to every created resource?

I need to attach every server (hcloud_server.swm01_managers) to the network (hcloud_server_network.swm01_managers). Right now I am using one variable for the number of servers I need and then use that variable for both the server creation and the attaching to the network. Now I am wondering if there is a way to simplify this?

Here's my example:

variable "env" {
  type = string
}

variable "swm01_managers_count" {
  type = number
}

# ─── CREATE THE DOCKER SWARM INTERNAL NETWORK ───────────────────────────────────

resource "hcloud_network" "swm01" {
  name = "swm01"
  ip_range = "10.0.0.0/8"
}

resource "hcloud_network_subnet" "swm01" {
  network_id = "${hcloud_network.swm01.id}"
  type = "server"
  ip_range = "10.0.1.0/24"
  network_zone = "eu-central"
}

# ─── CREATE DOCKER SWARM MANAGER NODES ──────────────────────────────────────────

resource "hcloud_server" "swm01_managers" {
  count = "${var.swm01_managers_count}"

  name = "mgr${format("%02d", count.index + 1)}"
  image = "ubuntu-18.04"
  server_type = "cx11"
  ssh_keys = "${var.ssh_keys}"
  labels = {
    "env" = "prd"
    "docker_swarm_role" = "manager"
  }

}

# ─── ATTACH DOCKER SWARM MANAGER NODES TO THE INTERNAL NETWORK ──────────────────

resource "hcloud_server_network" "swm01_managers" {
  count = "${var.swm01_managers_count}"

  server_id = "${hcloud_server.swm01_managers[count.index].id}"
  network_id = "${hcloud_network.swm01.id}"
}

Now I know the following does not work, but I was thinking about something like this:

# ─── CREATE DOCKER SWARM MANAGER NODES ──────────────────────────────────────────

resource "hcloud_server" "swm01_managers" {
  count = "${var.swm01_managers_count}"

  name = "mgr${format("%02d", count.index + 1)}"
  image = "ubuntu-18.04"
  server_type = "cx11"
  ssh_keys = "${var.ssh_keys}"
  labels = {
    "env" = "prd"
    "docker_swarm_role" = "manager"
  }

  resource "hcloud_server_network" "swm01_managers" {
  server_id = "${hcloud_server.swm01_managers[count.index].id}"
  network_id = "${hcloud_network.swm01.id}"
  }

}

Thanks!

Rick McClatchie

Posted 2019-08-14T07:30:29.890

Reputation: 3

No answers