Hi Everyone,
Currently, I looking for options to create multiple security groups with different set of rules data driven from a csv file. Assume I have the first 5 rows of rules for security group1 & next 5rows of rules for security group2 or on other case i have multiple sheets in csv file were 1st sheet contains rules of security group1 & second sheet contains rules of security group2. Please help me to achieve my requirement for aws terraform deployment. How can i do it. can someone share sample code.
please share your code so it will me easy for us
You can try this
variable cidr_rules_file {
default = "rules_by_cidr.csv"
}
/*
Considering the contents of cidr_rules_file as follows:
name,security_group,type,from_port,to_port,protocol,cidr_block
rule1,<id-of-sg-web>ingress,80,80,tcp,0.0.0.0/0
rule2,<id-of-sg-web>ingress,443,443,tcp,0.0.0.0/0
*/
variable sg_rules_file {
default = "rules_by_sg.csv"
}
/*
Considering the contents of sg_rules_file as follows:
name,security_group,type,from_port,to_port,protocol,source_security_group_id
rule3,sg-app,ingress,8009,8009,tcp,<id-of-sg-web>
rule4,sg-db,ingress,3006,3006,tcp,<id-of-sg-app>
*/
locals {
rules_by_cidr = csvdecode(file(var.cidr_rules_file))
rules_by_sg = csvdecode(file(var.sg_rules_file))
}
resource "aws_security_group_rule" "rule_by_cidr" {
for_each = { for rule in local.contents : rule.name => rule }
type = each.value.type
from_port = each.value.from_port
to_port = each.value.to_port
protocol = each.value.protocol
cidr_blocks = [each.value.cidr_block]
security_group_id = each.value.security_group
}
resource "aws_security_group_rule" "rule_by_sg" {
for_each = { for rule in local.contents : rule.name => rule }
type = each.value.type
from_port = each.value.from_port
to_port = each.value.to_port
protocol = each.value.protocol
source_security_group_id = each.value.source_security_group_id
security_group_id = each.value.security_group
}