Security Groups
Security groups are used to handle Firewall rules or any other type of access management in AWS.
This exercise will create two security group resource
type of blocks.
You learn how to combine variables and strings together and how to call/use data
blocks in Terraform.
Security Group for Load Balancer
- Create a
resource
block with typeaws_security_group
and name italb
with following parameters:name
="${var.service_name}-alb"
. This is how you can combine string with a variable.description
=Access to ALB
vpc_id
=var.vpc_id
ORdata.aws_vpc.this.id
- Firewall rules:
ingress { protocol = "tcp" from_port = 80 to_port = 80 cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }
Security Group for ECS
- Create a
variable
block with namefrontend_port
to yourvariables.tf
file with following params:type
=number
default
=80
- Create a
resource
block with typeaws_security_group
and name itecs
with following parameters:name
="${var.service_name}-ecs"
description
=allow only inbound access from the ALB
vpc_id
=var.vpc_id
- Firewall rules:
ingress { protocol = "tcp" from_port = var.frontend_port to_port = var.frontend_port security_groups = [aws_security_group.alb.id] } egress { protocol = "-1" from_port = 0 to_port = 0 cidr_blocks = ["0.0.0.0/0"] }
Check your configuration
To check your Terraform configuration run
terraform plan
It will show you the resources that Terraform will create,delete or change. It will not apply anything.
Answer
terraform/security_groups.tf
resource "aws_security_group" "alb" {
name = "${var.service_name}-alb"
description = "Access to ALB"
vpc_id = var.vpc_id
ingress {
protocol = "tcp"
from_port = 80
to_port = 80
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_security_group" "ecs" {
name = "${var.service_name}-ecs"
description = "allow inbound access from the ALB only"
vpc_id = var.vpc_id
ingress {
protocol = "tcp"
from_port = var.frontend_port
to_port = var.frontend_port
security_groups = [aws_security_group.alb.id]
}
egress {
protocol = "-1"
from_port = 0
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}
}