在Terraform中使用带有偏移量的计数

时间:2019-09-03 12:48:40

标签: terraform

我想用Terraform创建一些资源,并将count.index包含在var.tf文件中定义的偏移量中,例如:

vm-app-04

vm-app-05

vm-app-06

vm-app-04-nic-01

vm-app-05-nic-01

vm-app-06-nic-01

每当我尝试添加$ {var.count_offset}时,都会收到“错误:无效字符”或“错误:无效表达式”。有什么方法可以创建这种行为?

P1_DATE

这是我得到的输出:

resource "azurerm_network_interface" "nic" {
  count                     = "${var.nb_instances}"
  name                      = "${var.vm_hostname}-${format("%02d", count.index + 1 + ${var.count_offset})}-nic-01"
  location                  = "${module.global_variables.location}"
  resource_group_name       = "${module.global_variables.resource_group_name}"

  ip_configuration {
    name                          = "ipconfig01"
    subnet_id                     = "${var.subnet_id}"
    private_ip_address_allocation = "dynamic"
  }
  tags = {
    environment = "${var.environment}}"
  }
}


resource "azurerm_dns_a_record" "add_A_record" {
  count               = "${var.nb_instances}"
  name                = "${var.vm_hostname}-${format("%02d", count.index + 1 + ${var.count_offset})}"
  zone_name           = "${module.global_variables.dns_zone}"
  resource_group_name = "${module.global_variables.resource_group_name}"
  ttl                 = 300
  records             = ["${element(azurerm_network_interface.nic.*.private_ip_address, count.index + 1 + ${var.count_offset})}"]
  tags = {
    environment = "${var.environment}"
  }
}

1 个答案:

答案 0 :(得分:0)

您不应该嵌套${},因为它只是用来告诉Terraform在其内部进行插值,因此您可以将${}放在var.count_offset周围。

进行此更改后,您的代码应为:

resource "azurerm_network_interface" "nic" {
  count                     = "${var.nb_instances}"
  name                      = "${var.vm_hostname}-${format("%02d", count.index + 1 + var.count_offset)}-nic-01"
  location                  = "${module.global_variables.location}"
  resource_group_name       = "${module.global_variables.resource_group_name}"

  ip_configuration {
    name                          = "ipconfig01"
    subnet_id                     = "${var.subnet_id}"
    private_ip_address_allocation = "dynamic"
  }
  tags = {
    environment = "${var.environment}}"
  }
}


resource "azurerm_dns_a_record" "add_A_record" {
  count               = "${var.nb_instances}"
  name                = "${var.vm_hostname}-${format("%02d", count.index + 1 + ${var.count_offset})}"
  zone_name           = "${module.global_variables.dns_zone}"
  resource_group_name = "${module.global_variables.resource_group_name}"
  ttl                 = 300
  records             = ["${element(azurerm_network_interface.nic.*.private_ip_address, count.index + 1 + var.count_offset)}"]
  tags = {
    environment = "${var.environment}"
  }
}