terraform 中的 aws_security_group_rule 嵌套 For_each 或动态计数 [英] Nested For_each or count with dynamic for aws_security_group_rule in terraform
本文介绍了terraform 中的 aws_security_group_rule 嵌套 For_each 或动态计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建具有以下要求的安全组规则.
I have the requirement to create security group rule with below requirement.
Port 22 should have CIDR as [1,2,3]
Port 443 & 80 each should have CIDR as [4,5]
ingress_ports_tcp = [[22], [443,80]]
ingress_cidr_tcp = [[1,2,3], [4,5]]
I am trying below code
resource "aws_security_group_rule" "tcp1" {
type = "ingress"
count = (length(var.ingress_cidr_tcp) == length(var.ingress_ports_tcp)) && ( var.ingress_cidr_tcp != "" || var.ingress_ports_tcp != "" ) ? length(var.ingress_ports_tcp) : 0
dynamic "sg" {
for_each = toset(var.ingress_ports_tcp[count.index])
content {
from_port = each.value
to_port = each.value
cidr_blocks = var.ingress_cidr_tcp[count.index]
}
}
security_group_id = aws_security_group.default-sg[0].id
}
错误:
Error:Missing required argument on security-group.tf line 16, in resource "aws_security_group_rule" "tcp1"resource "aws_security_group_rule" "tcp1" The argument "from_port" is required, but no definition was found.Error: Missing required argument on security-group.tf line 16, in resource "aws_security_group_rule" "tcp1"resource "aws_security_group_rule" "tcp1" The argument "to_port" is required, but no definition was found.Error: Unsupported block type in resource "aws_security_group_rule" "tcp1":
19: dynamic "sg" Blocks of type "sg" are not expected here.
请帮忙.
推荐答案
aws_security_group_rule
中sg
之类的没有这样的块.因此,您不能使用 dynamic
.
There is no such block as sg
in aws_security_group_rule
. Thus, you can't use dynamic
.
您的问题可以通过以下方式解决:
Your issue could be solved as follows:
variable "ingress_ports_tcp" {
default = [[22], [443,80]]
}
# example with some CIDRs
variable "ingress_cidr_tcp" {
default = [["172.31.32.0/20", "172.31.64.0/20", "172.31.96.0/20"],
["172.31.128.0/20", "172.31.160.0/20"]]
}
locals {
my_rules = merge([
for idx_port, ports in var.ingress_ports_tcp:
{ for port in ports:
"${idx_port}-${port}" => {
"port" = port
"cidrs" = var.ingress_cidr_tcp[idx_port]
}
}
]...)
}
给予:
{
"0-22" = {
"cidrs" = [
"172.31.32.0/20",
"172.31.64.0/20",
"172.31.96.0/20",
]
"port" = 22
}
"1-443" = {
"cidrs" = [
"172.31.128.0/20",
"172.31.160.0/20",
]
"port" = 443
}
"1-80" = {
"cidrs" = [
"172.31.128.0/20",
"172.31.160.0/20",
]
"port" = 80
}
}
然后:
resource "aws_security_group_rule" "tcp1" {
for_each = local.my_rules
from_port = each.value.port
to_port = each.value.port
cidr_blocks = each.value.cidrs
protocol = "tcp"
type = "ingress"
security_group_id = "sg-005923c14af064eec"
}
这篇关于terraform 中的 aws_security_group_rule 嵌套 For_each 或动态计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文