向多个安全组中添加安全组规则



我正在创建一个安全组规则,并希望将其附加到多个安全组。我该怎么做呢?例如:

resource "aws_security_group" "test-sg-1" {
name        = "Test SG 1"
description = "Test Security Group one"
vpc_id = aws_vpc.test_vpc.id
lifecycle {
create_before_destroy = true
}
}
resource "aws_security_group" "test-sg-2" {
name        = "Test SG 2"
description = "Test Security Group two"
vpc_id = aws_vpc.test_vpc.id
lifecycle {
create_before_destroy = true
}
}
resource "aws_security_group_rule" "egress_all" {
from_port         = 0
protocol          = "-1"
security_group_id = [aws_security_group.test-sg-1.id, aws_security_group.test-sg-2.id]
to_port           = 0
type              = "egress"
cidr_blocks      = ["0.0.0.0/0"]
}

我得到错误,如果我尝试上面的方法使用列表。

│ Error: Incorrect attribute value type
│
│   on main.tf line 76, in resource "aws_security_group_rule" "egress_all":
│   76:   security_group_id = [aws_security_group.test-sg-1.id, aws_security_group.test-sg-2.id]
│     ├────────────────
│     │ aws_security_group.test-sg-1.id will be known only after apply
│     │ aws_security_group.test-sg-2.id will be known only after apply
│
│ Inappropriate value for attribute "security_group_id": string required.

在这种情况下,使用for_each元参数[1]可能是避免代码重复的好主意。这就是我要做的:

locals {
sg_names = ["Test SG 1", "Test SG 2"]
}
resource "aws_security_group" "test_sg" {
for_each    = toset(local.sg_names)
name        = each.value
description = each.value
vpc_id = aws_vpc.test_vpc.id
lifecycle {
create_before_destroy = true
}
}
resource "aws_security_group_rule" "egress_all" {
for_each          = aws_security_group.test_sg
from_port         = 0
protocol          = "-1"
security_group_id = each.value.id
to_port           = 0
type              = "egress"
cidr_blocks      = ["0.0.0.0/0"]
}

这里使用了资源链。你可以在[2]中阅读更多内容。


[1] https://www.terraform.io/language/meta-arguments/for_each基本语法

[2] https://www.terraform.io/language/meta-arguments/for_each chaining-for_each-between-resources

相关内容

  • 没有找到相关文章

最新更新