简体   繁体   中英

Terraform resource inheritance

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}"
  ]
}

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}"
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM