From 8e037b228a890508329d12f0c615ce137c3cf4d8 Mon Sep 17 00:00:00 2001 From: xpk Date: Fri, 9 Oct 2020 08:12:40 +0800 Subject: [PATCH] NEW: security group using nested loops --- security_groups/main.tf | 51 ++++++++++++++++++++++++++++++++++++ security_groups/provider.tf | 14 ++++++++++ security_groups/variables.tf | 2 ++ 3 files changed, 67 insertions(+) create mode 100644 security_groups/main.tf create mode 100644 security_groups/provider.tf create mode 100644 security_groups/variables.tf diff --git a/security_groups/main.tf b/security_groups/main.tf new file mode 100644 index 0000000..e810cfe --- /dev/null +++ b/security_groups/main.tf @@ -0,0 +1,51 @@ +resource "aws_security_group" "sg" { + count = length(var.security-groups) + name = lookup(var.security-groups[count.index], "name") + description = lookup(var.security-groups[count.index], "description") + vpc_id = var.vpcid +} + +// see https://www.terraform.io/docs/configuration/functions/flatten.html + +locals { + rules = flatten([ + for sg_key, sg in var.security-groups : [ + for rule_key, rule in lookup(sg, "rules") : { + sg_key = sg_key + rule_key = rule_key + sg_name = sg.name + protocol = rule[0] + cidr_blocks = rule[1] + from_port = rule[2] + to_port = rule[3] + type = rule[4] + description = rule[5] + } + ] + ]) + + +} + +resource "aws_security_group_rule" "rules" { + for_each = { + for rule in local.rules : "${rule.sg_key}.${rule.rule_key}" => rule + } + + security_group_id = matchkeys(aws_security_group.sg.*.id, aws_security_group.sg.*.name, [each.value.sg_name])[0] + protocol = each.value.protocol + cidr_blocks = [each.value.cidr_blocks] + from_port = each.value.from_port + to_port = each.value.to_port + type = each.value.type + description = each.value.description +} + +output sg-id-name { + value = [ + for id, name in zipmap( + sort(aws_security_group.sg.*.id), + sort(aws_security_group.sg.*.name)) : + map("id", id, "name", name) + ] +} \ No newline at end of file diff --git a/security_groups/provider.tf b/security_groups/provider.tf new file mode 100644 index 0000000..b521f6f --- /dev/null +++ b/security_groups/provider.tf @@ -0,0 +1,14 @@ +# In pre-build phase, this terraform script is ran by the TempRackspaceUser with local state file. +# Later on it was adjusted to use assume role +# Ultimately, the state file needs to be moved to s3 + +provider "aws" { + region = "ap-east-1" +} + +terraform { + required_version = "> 0.12, < 0.13" + required_providers { + aws = "~> 3.6.0" + } +} diff --git a/security_groups/variables.tf b/security_groups/variables.tf new file mode 100644 index 0000000..ab463af --- /dev/null +++ b/security_groups/variables.tf @@ -0,0 +1,2 @@ +variable vpcid {} +variable security-groups {} \ No newline at end of file