Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform resource inheritance

Tags:

terraform

Is there a way to declare an abstract resource to inherit from?

Example:

resource "digitalocean_droplet" "worker_abstract" {
  abstract = true // ???

  name = "swarm-worker-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
  ]

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}

And then use declared resource with overridden variables:

resource "worker_abstract" "worker_foo" {
  count = 2
  name = "swarm-worker-foo-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

resource "worker_abstract" "worker_bar" {
  count = 5
  name = "swarm-worker-bar-${count.index}"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}
like image 273
Alex T Avatar asked Apr 29 '18 05:04

Alex T


1 Answers

This might be a little more "verbose" of a solution than what you're proposing, but this sounds like a perfect use-case for modules in 0.12.

You could create a module, say in the file worker/main.tf

variable "instances" {
  type = number
}

variable "name" {
  type = string
}

variable "tags" {
  type    = list(string)
  default = []
}

resource "digitalocean_droplet" "worker" {
  count = var.instances

  name = "swarm-worker-${var.name}-${count.index}"
  tags = var.tags

  // other config stuff

  provisioner "remote-exec" {
    //...
  }
}

then you could consume your module almost exactly like your example (let's say from the directory above worker)

module "worker_foo" {
  source = "./worker"

  instances = 2
  name = "foo"
  tags = [
    "${digitalocean_tag.swarm_worker.id}",
    "${digitalocean_tag.foo.id}"
  ]
}

module "worker_bar" {
  source = "./worker"

  instances = 5
  name = "bar"
  tags = [
    "${digitalocean_tag.swarm_worker.id}"
    "${digitalocean_tag.bar.id}"
  ]
}
like image 148
mjgpy3 Avatar answered Sep 22 '22 15:09

mjgpy3