I am trying to create security groups rules from a map of objects in Terraform, however sometimes terraform delete those roles and this is happening randomly. We are using s3 as backend and dynamodb locks.
This is my security group resource
resource "aws_security_group" "ec2_jumper_sg" {
name = "${var.app_name}-private-sg"
description = "Security Group for Private EC2 instance"
vpc_id = var.vpc_id
egress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.vpc_cidr]
}
}
Those are the rules created with the for_each
attached to the above security group:
resource "aws_security_group_rule" "ec2_jumper_sg_databases_egress" {
for_each = var.databases
security_group_id = aws_security_group.ec2_jumper_sg.id
from_port = each.value.port
to_port = each.value.port
source_security_group_id = each.value.securityGroupId
protocol = "tcp"
type = "egress"
}
And this is my variable map:
variable "databases" {
type = map(object({
id: string
securityGroupId: string
port: number
}))
default = {
"db-1": {
id : "db-1",
securityGroupId : "sg-000000000",
port : 5432
},
"db-2": {
id : "db2",
securityGroupId : "sg-000000000",
port : 3306
}
}
}
When the rules do not exist it will create them, however when they are there it will delete them:
- {
- cidr_blocks = []
- description = ""
- from_port = 3306
- ipv6_cidr_blocks = []
- prefix_list_ids = []
- protocol = "tcp"
- security_groups = [
- "sg-0000000",
]
- self = false
- to_port = 3306
},
- {
- cidr_blocks = []
- description = ""
- from_port = 5432
- ipv6_cidr_blocks = []
- prefix_list_ids = []
- protocol = "tcp"
- security_groups = [
- "sg-00000000",
]
- self = false
- to_port = 5432
},
Why is this happening?
CodePudding user response:
You can't mix egress
defined in aws_security_group
with aws_security_group_rule
resources. From docs:
Terraform currently provides both a standalone Security Group Rule resource (a single ingress or egress rule), and a Security Group resource with ingress and egress rules defined in-line. At this time you cannot use a Security Group with in-line rules in conjunction with any Security Group Rule resources. Doing so will cause a conflict of rule settings and will overwrite rules.
You can only use one of those, not both.