【问题标题】:Cycle through Terraform list循环浏览 Terraform 列表
【发布时间】:2020-10-14 07:23:38
【问题描述】:

如果我们创建多个aws_instance资源:

variable "cluster_size" {
  type = number
  default = 4
}

variable "private_subnets" {
  type = list(string)
  default = ["subnet-a", "subnet-b", "subnet-c"]
}

resource "aws_instance" "cassandra" {
  instance_type = var.instance_type
  count         = var.cluster_size
  ami           = var.ami
  key_name      = var.security_key.name
  subnet_id     = var.private_subnets[count.index]
}

如您所见,我有 3 个私有子网,但要运行 4 个主机。如何循环浏览private_subnets的列表?

所以

  • 主机 0 = 子网-a
  • 主机 1 = 子网-b
  • 主机 2 = 子网-c
  • host 3 = subnet-a (即循环到第一个元素)。

例如 Python 有 itertools.cycle

如何在 Terraform 的声明式语言中实现循环?

【问题讨论】:

  • 我不确定是否有循环函数,但会使用 var.private_subnets[count.index % length(private_subnets)] 工作 - 即使用计数除以子网数的余数) ?

标签: terraform terraform-provider-aws


【解决方案1】:

element function 自动执行此操作,在序列末尾环绕。这几乎是该函数的主要用途,因为他们引入了带有方括号的切片表示法,您在那里使用。

variable "cluster_size" {
  type = number
  default = 4
}

variable "private_subnets" {
  type = list(string)
  default = ["subnet-a", "subnet-b", "subnet-c"]
}

resource "aws_instance" "cassandra" {
  instance_type = var.instance_type
  count         = var.cluster_size
  ami           = var.ami
  key_name      = var.security_key.name
  subnet_id     = element(var.private_subnets, count.index)
}

或者,您可以像在其他编程语言中一样使用 % 运算符来取模:

variable "cluster_size" {
  type = number
  default = 4
}

variable "private_subnets" {
  type = list(string)
  default = ["subnet-a", "subnet-b", "subnet-c"]
}

resource "aws_instance" "cassandra" {
  instance_type = var.instance_type
  count         = var.cluster_size
  ami           = var.ami
  key_name      = var.security_key.name
  subnet_id     = var.private_subnets[count.index % length(var.private_subnets)]
}

第一个选项在需要环绕时更常见,当您不需要环绕时,方括号切片表示法更常见。

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 2020-01-02
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多