Terraform资源继承

时间:2018-04-29 05:15:27

标签: terraform

有没有办法声明要从中继承的抽象资源?

示例:

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

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

  // other config stuff

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

然后使用已覆盖变量的声明资源:

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

1 个答案:

答案 0 :(得分:2)

这可能比您提出的解决方案更为“冗长”,但这听起来像是modules in 0.12的完美用例。

您可以创建一个模块,例如在文件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" {
    //...
  }
}

然后您可以像使用示例一样完全使用模块(例如,从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}"
  ]
}