在Terraform中映射AWS安全组的端口范围

问题描述 投票:0回答:1

我正在尝试遍历端口和端口范围的映射以在Terraform中创建一个AWS安全组。对于Ingress端口,它们提供from_port字段和to_port字段。这应该为安全组中的特定规则定义端口范围。当规则是单个端口时,我可以进行映射,因为从端口到端口都相同。但是当规则要求一定范围的端口时,我不知道该怎么做。这是我一直在测试的代码。我认为我对此有正确的想法,但遇到类型错误。

我本质上是试图使用from_port的索引值来查找哪个端口应映射到to_port

provider "aws" {
  region  = "us-east-2"
  profile = "default"
}

locals {
  start = [22, 33, 44] # from_ports
  end   = [25, 35, 45] # to_ports
  vpcid = "vpc-xxxxxxxxxxxx"
}

resource "aws_security_group" "traffic_secgrp" {
  name        = "traffic_sec_grp"
  description = "Allows traffic"
  vpc_id      = local.vpcid

  dynamic "ingress" {
    for_each = local.start
    content {
      from_port   = ingress.value
      to_port     = element(local.end, [index(local.start, ingress.value)])
      protocol    = "UDP"
      cidr_blocks = ["10.2.0.0/20"]
    }
  }
}

这是我从to_port行收到的错误:

Error: Invalid function argument

  on main.tf line 21, in resource "aws_security_group" "traffic_secgrp":
  21:       to_port     = element(local.end, [index(local.start, ingress.value)])
    |----------------
    | ingress.value is 44
    | local.start is tuple with 3 elements

Invalid value for "index" parameter: number required.
amazon-web-services terraform
1个回答
0
投票

我发现了以上代码的问题。在to_port行中,我将element函数的索引包装在引起类型问题的方括号中。一旦卸下这些支架,它就可以正常工作。

工作to_port

to_port     = element(local.end, index(local.start, ingress.value))
© www.soinside.com 2019 - 2024. All rights reserved.