Skip to content

Instantly share code, notes, and snippets.

@KernelPanicAUS
Last active July 31, 2020 13:40
Show Gist options
  • Save KernelPanicAUS/a5bd52e3fc51a09f108922e4c62dc340 to your computer and use it in GitHub Desktop.
Save KernelPanicAUS/a5bd52e3fc51a09f108922e4c62dc340 to your computer and use it in GitHub Desktop.
Safer handling of resource multiplicity in Terraform
terraform {
required_version = ">= 0.12"
required_providers {
aws = "~> 2.0"
}
}
provider "aws" {
region = "eu-central-1"
}
data "aws_vpc" "selected" {
default = true
}
locals {
ingress_rules = [
{
description = "test-one",
from_port = 443,
to_port = 443,
protocol = "tcp"
cidr_blocks = [data.aws_vpc.selected.cidr_block]
},
{
description = "test-two",
from_port = 444,
to_port = 444,
protocol = "tcp"
cidr_blocks = [data.aws_vpc.selected.cidr_block]
},
{
description = "test-three",
from_port = 445,
to_port = 445,
protocol = "tcp"
cidr_blocks = [data.aws_vpc.selected.cidr_block]
},
{
description = "test-four",
from_port = 446,
to_port = 446,
protocol = "tcp"
cidr_blocks = [data.aws_vpc.selected.cidr_block]
}
]
}
resource "aws_security_group" "test_two" {
name = "test_two"
description = "Allow inbound traffic"
vpc_id = data.aws_vpc.selected.id
}
resource "aws_security_group_rule" "test_two_rules" {
for_each = {
for rule in local.ingress_rules :
"${rule.description}-${rule.protocol}" => rule
}
type = "ingress"
description = lookup(each.value, "description")
from_port = lookup(each.value, "from_port")
to_port = lookup(each.value, "to_port")
protocol = lookup(each.value, "protocol")
cidr_blocks = lookup(each.value, "cidr_blocks")
security_group_id = aws_security_group.test_two.id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment