引用另一个模块中的计数索引

时间:2018-04-25 06:57:32

标签: terraform

我有这个Terraform模块:

locals {
  name = "${var.counter > 0 ? lower(format("%v-%d", var.name, var.counter+1)) : lower(format("%v", var.name))}"
}

resource "null_resource" "default" {
  count = "${var.enabled == "true" ? 1 : 0}"

  triggers = {
    id         = "${lower(join(var.delimiter, compact(concat(list(var.namespace, var.stage, local.name, var.attributes))))}"
    name       = "${local.name}"
    namespace  = "${lower(format("%v", var.namespace))}"
    stage      = "${lower(format("%v", var.stage))}"
    attributes = "${lower(format("%v", join(var.delimiter, compact(var.attributes))))}"
  }

  lifecycle {
    create_before_destroy = true
  }
}

我正在使用该模块:

module "label" {
  source         = "../modules/tf-label"
  namespace      = "${var.namespace}"
  stage          = "${var.stage}"
  name           = "${var.name}"
  attributes     = "${var.attributes}"
  delimiter      = "${var.delimiter}"
  tags           = "${merge(map("AZ", "${local.availability_zone}"), var.tags)}"
  enabled        = "${local.instance_count > 0 ? "true" : "false"}"
}

我正在使用以下资源:

resource "aws_instance" "default" {
  count = "${var.instance_count}"
  name = "${module.label.id}"
  tags = "${module.label.tags}"
}

由于aws_instance资源可以超过1,如何将count.index值传递给标签模块(例如var.counter),这样我才能处理它并形成适当的标签(例如namespace-stage-name-attributes-counter - > example-prod-app-nginx-1)或者这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

如何处理:使用模块块上的count属性。通过模块块将计数作为变量计数器输入模块。在实例资源块中的模块输出中建立索引-模块块现在将产生一个模块节点数组,而不是单个模块节点,因此我们对其进行索引以获得所需的数组。

module "aws_instance_label" {
    source         = "../modules/tf-label"
    count          = "${var.instance_count}"
    counter        = "${count.index}"
    namespace      = "${var.namespace}"
    stage          = "${var.stage}"
    name           = "${var.name}"
    attributes     = "${var.attributes}"
    delimiter      = "${var.delimiter}"
    tags           = "${merge(map("AZ", "${local.availability_zone}"), var.tags)}"
    enabled        = "${local.instance_count > 0 ? "true" : "false"}"
}

resource "aws_instance" "default" {
    count = "${var.instance_count}"
    name = "${module.aws_instance_label[count.index].id}"
    tags = "${module.aws_instance_label[count.index].tags}"
}
相关问题