【问题标题】:Terraform issue with using dynamic block for ingress rules on security group使用动态块作为安全组入口规则的 Terraform 问题
【发布时间】:2021-07-08 13:05:24
【问题描述】:

我基本上是在尝试创建一个规则,以允许来自 ip 地址 x.x.x.x/32(其中 x.x.x.x 是真实 IP 地址)的 ssh、rdp 和 http 流量。

这是我的 tf 文件

resource "aws_security_group" "allow_internet" {
name        = "allow_internet"
description = "allow_internet_from_my_connection"
vpc_id      = aws_vpc.dee_vpc.id

dynamic "ingress" {
for_each = var.sg_protocols
iterator = protocol
content {
  from_port   = 0
  to_port     = 0
  protocol    = protocol.value
  cidr_blocks = ["x.x.x.x/32"]
}

}

这是我的变量

  variable "sg_protocols" {
  type        = list(string)
  description = "list of ingress ports"
  default     = ["rdp", "ssh", "rdp"]
  }

我收到以下错误

λ terraform plan
Error: Invalid number literal
on securitygroup.tf line 14, in resource "aws_security_group" "allow_internet":
14:       cidr_blocks = [x.x.x.x/32]
Failed to recognize the value of this number literal.

【问题讨论】:

  • 修正默认 = ["rdp", "ssh", "http"]

标签: terraform-provider-aws aws-security-group


【解决方案1】:

这是错误的用法:

  • to_port
  • from_port
  • 协议

具体用法可以参考https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group

如果你想使用动态块,你需要创建一个更复杂的对象来保存上面提到的 3 个参数的值。

而且动态块的语法也不正确。

试试这个:

resource "aws_security_group" "allow_internet" {
  name        = "allow_internet"
  description = "allow_internet_from_my_connection"
  vpc_id      = aws_vpc.test_vpc.id

  dynamic "ingress" {
    for_each = var.sg_protocols
    content {
      from_port = ingress.value["from_port"]
      to_port = ingress.value["to_port"]
      protocol = ingress.value["protocol"]
      cidr_blocks = ["10.10.10.10/32"]  
    }
  }
}

variable "sg_protocols" {
  type = list(object({
    from_port = number
    to_port = number
    protocol = string
  }))

  default = [
    {
      from_port = 80
      to_port = 80
      protocol = "tcp"
    },
    {
      from_port = 22
      to_port = 22
      protocol = "tcp"
    }
  ]
}

【讨论】:

  • 谢谢@nyxx88,这对我来说更有意义了
  • 或者你可以只使用type = any(而不是定义对象)
猜你喜欢
  • 2020-03-27
  • 2021-08-10
  • 2021-05-14
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2021-03-06
相关资源
最近更新 更多