Created
September 5, 2020 23:03
-
-
Save imksoo/a320e70629eb8881208eaca84184210b to your computer and use it in GitHub Desktop.
TerraformでAWS上のSecurity Groupを作るときにポート範囲付きでリスト化してサクッと作る
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module "security_group_rules_with_port_range" { | |
source = "./modules/security_group_rules" | |
security_group_id = "sg-XXXXXXXX" | |
description = "Windows Active Directory ports" | |
type = "ingress" | |
self = true | |
rules = [ | |
# DNS | |
{ protocol = "udp", port = "53" }, | |
{ protocol = "tcp", port = "53" }, | |
# Kerberos authentication | |
{ protocol = "udp", port = "88" }, | |
{ protocol = "tcp", port = "88" }, | |
# NTP | |
{ protocol = "udp", port = "123" }, | |
# RPC | |
{ protocol = "tcp", port = "135" }, | |
# Netlogon | |
{ protocol = "udp", port = "137..138" }, | |
# Netlogon | |
{ protocol = "tcp", port = "139" }, | |
# LDAP | |
{ protocol = "udp", port = "389" }, | |
{ protocol = "tcp", port = "389" }, | |
# SMB | |
{ protocol = "udp", port = "445" }, | |
{ protocol = "tcp", port = "445" }, | |
# Kerberos authentication | |
{ protocol = "udp", port = "464" }, | |
{ protocol = "tcp", port = "464" }, | |
# LDAPS (LDAP over TLS/SSL) | |
{ protocol = "tcp", port = "636" }, | |
# Global Catalog | |
{ protocol = "tcp", port = "3268..3269" }, | |
# Ephemeral ports for RPC | |
{ protocol = "udp", port = "1024..65535" } | |
{ protocol = "tcp", port = "1024..65535" } | |
] | |
} | |
## /modules/security_group_rules/variables.tf | |
variable "rules" { | |
description = "List of allowed protocols and port numbers (like '49152..65535')" | |
type = list(object({ | |
protocol = string | |
port = string | |
})) | |
} | |
## /modules/security_group_rules/main.tf | |
locals { | |
# Expanded security group rules to from_port and to_port | |
rules = [ | |
for r in var.rules : { | |
self = var.self | |
source_security_group_id = var.source_security_group_id | |
cidr_blocks = var.cidr_blocks | |
protocol = r.protocol | |
from_port = element(split("..", r.port), 0) | |
to_port = element(split("..", r.port), 1) | |
} | |
] | |
} | |
resource "aws_security_group_rule" "rules" { | |
security_group_id = var.security_group_id | |
type = var.type | |
description = var.description | |
count = length(local.rules) | |
# Source range | |
self = local.rules[count.index].self | |
source_security_group_id = local.rules[count.index].source_security_group_id | |
cidr_blocks = local.rules[count.index].cidr_blocks | |
# Destination port and protocol | |
protocol = local.rules[count.index].protocol | |
from_port = local.rules[count.index].from_port | |
to_port = local.rules[count.index].to_port | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment