Jit- announcement icon

Announcing our bidirectional integration with Wiz to level-up contextual prioritization!

Learn more

In this article

Developer's Tutorial to Managing AWS Security Groups through Terraform

Charlie Klein - Director of Product Marketing at Jit
By Charlie Klein

Updated November 5, 2024.

a cloud with the text, developing aws security groups through terraformm

Managing complex AWS Security Groups across different environments can be overwhelming, but Terraform and Infrastructure as Code (IaC) changes the game. Tools like Terraform let you define and manage your infrastructure through code, maintaining consistency and reducing the risk of human error.

So why haven't more people made the switch? Nearly 38% of AWS users still perform critical actions manually. Many simply don't know how to leverage tools like Terraform to automate these processes. By adopting Terraform, you can automate your AWS security configurations, making them uniform and reliable. This boosts security and frees up your team to focus on strategic initiatives.

a man sitting in front of a laptop computer


What are AWS Security Groups and how can they be managed with Terraform?

AWS Security Groups act as virtual firewalls for your AWS service instances, controlling inbound and outbound traffic. They secure your AWS resources by defining allowed and denied traffic rules based on IP protocols, ports, and source/destination IP addresses.

Terraform is an open-source Infrastructure as Code (IaC) tool for defining and provisioning cloud infrastructure using a declarative configuration language. It simplifies managing infrastructure by allowing you to write, plan, and create configurations as code.

To manage AWS Security Groups with Terraform, you write configuration files that specify the desired security group settings. Configurations are applied using Terraform commands, which automate the creation and updates of security groups in AWS. Terraform's state management maintains an accurate record of your infrastructure's current state, and its version control capabilities allow precise management and rollback of configurations.

a diagram showing the steps to perform a workflow


Why Manage AWS Security Groups through Terraform

1. Consistency in configurations

Terraform is known for simplifying Kubernetes orchestration, but its capabilities go beyond deploying containerized applications with ease. Thanks to its comprehensive automation and integration capabilities, managing AWS Security Groups with Terraform offers distinct advantages. This tool makes it easy to maintain consistent security configurations across all environments.

2. Integration with CI/CD Pipelines

Terraform connects with CI/CD pipelines like Jenkins, GitLab CI, and GitHub Actions, automating the entire process. Before changes are applied, tools like Checkov can perform static analysis on the Terraform configurations, scanning for policy violations and security risks in your AWS security groups. This proactive approach catches issues early, ensuring your configurations align with best practices and compliance standards before deployment.

3. Resource Deployment Tracking

  Resource deployment tracking with Terraform is managed through a state file, which maintains a detailed record of your infrastructure and its current state. This prevents over-provisioning by deploying only the necessary resources.

4. AWS Resource Tagging Support

Additionally, Terraform supports AWS resource tagging, enabling detailed cost tracking and allocation. This tagging helps break down costs by project or department, making budgeting and financial oversight much more accessible.

Common Pitfalls when Managing AWS Security Groups with Terraform, and How to Avoid Them

1. Misconfigurations

Avoid using unrestricted ingress/egress rules like cidr_blocks = ["0.0.0.0/0"], which expose your resources to the entire internet. Instead, restrict the CIDR blocks to specific IP ranges. However, be cautious of using CIDR ranges that are too broad or overlapping, which can unintentionally expose sensitive resources. Such misconfigurations can create vulnerabilities that attackers may exploit, potentially leading to JavaScript injections and other attacks.

a screenshot of the master cdr block


2. Overly Permissive Rules

Limit broad access by avoiding settings like security_group_id = ["sg-12345678"] and create more granular security groups for specific purposes. Be cautious with wildcards in source security groups and justify their use. Lastly, regularly review user access and update these rules to adhere to the principle of least privilege.

3. Insufficient Use of Modules

Not using Terraform modules effectively can lead to redundant code and increased maintenance efforts. Modules allow you to encapsulate and reuse configurations, promoting DRY (Don't Repeat Yourself) principles. When defining security groups, create reusable modules for standard configurations instead of duplicating code across different projects.

a diagram of a child's mobile model


4. Errors in Dependency Management

Mismanaging dependencies can cause deployment failures and inconsistencies. Avoid circular dependencies by carefully planning resource relationships avoiding cyclical references that could disrupt Terraform operations. Regularly update the Terraform state file to prevent conflicts and use remote state backends like S3 with state locking enabled to maintain state consistency and avoid issues from simultaneous updates.

Developer’s Tutorial: Managing AWS Security Groups through Terraform

1. Prerequisites

Download and install Terraform on your machine. Follow the official installation guide for your operating system.

Install the AWS CLI and then configure it by running:

aws configure

You will be prompted to enter your AWS Access Key ID, Secret Access Key, default region, and default output format. Terraform will use these credentials to interact with your AWS account.

2. Implement continuous security checks with Jit

Jit is an AppSec Posture Management (ASPM) platform that weaves security scanning for IaC (and many other security controls) seamlessly into your CI/CD pipeline. 

When your AWS Security Groups defined with Terraform are committed to your repository (or when changes are committed), Jit scans the configurations for issues using leading security controls, including:

  • KICS – Performs static analysis and enforces policies on Terraform configurations.

  • Trivy – Conducts security scanning for containers and infrastructure-as-code.

If misconfigurations that compromise security are present, Jit generates automated remediation suggestions to help you fix issues before deployment. 

a screenshot of a screenshot of a web page


resource "aws_security_group" "example" {
  name = "example-security-group"
  description = "Example security group"
  vpc_id = var.vpc_id
}z

If your project requires multiple security groups, you can define them in your main.tf file. For instance:

resource "aws_security_group" "web_sg" {
  name = "web-security-group"
  vpc_id = var.vpc_id
}

resource "aws_security_group" "db_sg" {
  name = "db-security-group"
  vpc_id = var.vpc_id
}

This example creates two separate security groups, one for web traffic and another for database traffic. Remember that it’s a good practice to ensure that resource names are unique and descriptive to avoid configuration conflicts and security risks.

5. Define Ingress and Egress Rules

Ingress rules define which inbound traffic is allowed. For example, to allow SSH traffic on port 22 from a specific IP address (e.g., 203.0.113.0/24), you would add:

ingress {
  from_port   = 22
  to_port     = 22
  protocol    = "tcp"
  cidr_blocks = ["203.0.113.0/24"]
}

Egress rules define which outbound traffic is allowed. By default, AWS Security Groups allow all outbound traffic. We can define more restrictive traffic rules. For instance, to allow outbound HTTP and HTTPS traffic only, you would configure:

egress {
  from_port   = 80
  to_port     = 80
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}
egress {
  from_port   = 443
  to_port     = 443
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}

6. Using Variables for Dynamic Configurations

To make your Terraform configuration more flexible, you can use variables. Create a variables.tf file to define your variables. For example, this setup allows you to pass different values for the VPC ID and SSH-allowed CIDR block without changing the configuration file:

variable "vpc_id" {
  description = "The VPC ID"
  type = string
}
variable "ssh_allowed_cidr" {
  description = "The CIDR block allowed to SSH"
  type = string
  default = "203.0.113.0/24"
}

Now reference this variable in your main.tf file:

resource "aws_security_group" "example" {
  name = "example-security-group"
  vpc_id = var.vpc_id
}

7. Reusing Configurations with Modules

Consider using a reusable module for security groups to promote code reuse and simplify maintenance. In a directory called modules/security-group, create a main.tf file with your security group configuration.

Here's an example directory structure for clarity:

terraform-security-groups/
├── main.tf
├── variables.tf
└── modules/
    └── security-group/
        └── main.tf

Then, use this module in your main configuration file:

module "security_group" {
  source  = "./modules/security-group"
  vpc_id  = var.vpc_id
  sg_name = "example-security-group"
}

This module approach allows you to:

  • Define your security group configuration once and reuse it

  • Easily maintain and update security group settings in one place

  • Keep your main configuration file clean and organized

After addressing any issues and once the AWS Security Groups are verified to be configured securely, you can apply the configuration with terraform apply to create the security groups in your AWS environment. You can do this manually or via a script as part of your CI/CD pipeline.

Automate with Terraform, Protect with Jit

Now that you know how to manage your AWS Security Groups with Terraform, you can take it a step further by using Jit. 

The ASPM tool bolsters your IaC configurations with automated security checks, real-time monitoring, and policy enforcement by integrating with tools like KICS, Trivy, and AWS Security Hub. This combination provides continuous security assurance, allowing you to focus on building and deploying applications with confidence. Explore more here to improve IaC security today.