遍历映射变量上的键/值

时间:2019-06-26 14:32:42

标签: terraform

在Terraform中,我正在尝试使用IP和关联注释的映射构建一个SecurityGroup。 我想做的是,遍历允许网络的map键值,并将map值与描述字段相关联。

代码看起来像这样

resource "aws_security_group_rule" "ingress" {
  type              = "ingress"
  (...)
  cidr_blocks       = "${var.ingress_cidr_blocks}"
  description       = "${var.ingress_description}"
  security_group_id = "${aws_security_group.this.id}"
}

module "securitygroup-ssh" {
  source = ""
  (...)
  ingress_from_port = "22"
  ingress_cidr_blocks = ["${var.ipLlist}"]
  ingress_description = "${var.allowed-network}"
}

将此作为变量,

variable "allowed-network" {
    type = "map"
    default = {
        "From Customer1" = "1.1.1.1/32"
        "Network this" = "10.0.0.0/24"
    }
}

已经在使用地图和内置查询功能而没有令人满意的结果。也可以通过网络作为列表进行迭代,但是描述字段似乎被最后一个值覆盖。

有什么想法吗?目前在Terraform中甚至有可能吗?

1 个答案:

答案 0 :(得分:0)

并非完全是地图,但它应该可以完成您想要的操作:

provider "aws" {
    region = "ca-central-1"
    version = "~> 2.7"
}

resource "aws_security_group" "this" {
  name_prefix = "this"
}

resource "aws_security_group_rule" "allowed-network" {
  count = length(var.allowed-network)
  type            = "ingress"
  from_port       = 0
  to_port         = 65535
  protocol        = "tcp"
  description = split(",", var.allowed-network[count.index])[0]
  cidr_blocks = [split(",", var.allowed-network[count.index])[1]]
  security_group_id = aws_security_group.this.id

}

variable "allowed-network" {
    type = "list"
    default = [
        "From Customer1,1.1.1.1/32",
        "Network this,10.0.0.0/24"
    ]
}