AWS Amazon EC2 Security Group

This page shows how to write Terraform and CloudFormation for Amazon EC2 Security Group and write them securely.

aws_security_group (Terraform)

The Security Group in Amazon EC2 can be configured in Terraform with the resource name aws_security_group. The following sections describe 3 examples of how to use the resource and its parameters.

Example Usage from GitHub

sg.tf#L1
resource "aws_security_group" "sg-0008359ed55dd2642" {
  name        = "programregistrydb--staging"
  description = "Managed by Terraform"
  tags = {
    "cluster"     = "bnpi",
    "Name"        = "programregistrydb--staging",
main.tf#L5
resource "aws_security_group" "pass_batch" {
  ingress {
    description = "TLS from VPC"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
sg.tf#L1
resource "aws_security_group" "vpc-0b5987919c0a3d3e7-default" {
    name        = "default"
    description = "default VPC security group"
    vpc_id      = "vpc-0b5987919c0a3d3e7"

    ingress {

Review your Terraform file for AWS best practices

Shisho Cloud, our free checker to make sure your Terraform configuration follows best practices, is available (beta).

Security Best Practices for aws_security_group

There are 3 settings in aws_security_group that should be taken care of for security reasons. The following section explain an overview and example code.

risk-label

Ensure your security group blocks unwanted inbound traffic

It is better to block unwanted inbound traffic.

risk-label

Ensure your security group blocks unwanted outbound traffic

It is better to block unwanted outbound traffic.

risk-label

Ensure to keep the description of your security group up-to-date

It is better to maintain the description of the security group up-to-date. A well-written description of the security group will help team members understand the group correctly.

Review your AWS Amazon EC2 settings

You can check if the aws_security_group setting in your .tf file is correct in 3 min with Shisho Cloud.

Parameters

Explanation in Terraform Registry

Provides a security group resource.

NOTE on Security Groups and Security Group Rules: 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. NOTE: Referencing Security Groups across VPC peering has certain restrictions. More information is available in the VPC Peering User Guide. NOTE: Due to AWS Lambda improved VPC networking changes that began deploying in September 2019, security groups associated with Lambda Functions can take up to 45 minutes to successfully delete. Terraform AWS Provider version 2.31.0 and later automatically handles this increased timeout, however prior versions require setting the customizable deletion timeout to 45 minutes (delete = "45m"). AWS and HashiCorp are working together to reduce the amount of time required for resource deletion and updates can be tracked in this GitHub issue.

Tips: Best Practices for The Other AWS Amazon EC2 Resources

In addition to the aws_default_vpc, AWS Amazon EC2 has the other resources that should be configured for security reasons. Please check some examples of those resources and precautions.

risk-label

aws_default_vpc

Ensure to avoid using default VPC

It is better to define the own VPC and use it.

risk-label

aws_network_acl_rule

Ensure your network ACL rule blocks unwanted inbound traffic

It is better to block unwanted inbound traffic.

risk-label

aws_ebs_volume

Ensure to use a customer-managed key for EBS volume encryption

It is better to use a customer-managed key for EBS volume encryption. It can be gain more control over the encryption by using customer-managed keys (CMK).

risk-label

aws_instance

Ensure to avoid storing AWS access keys in user data

It is better to avoid storing AWS access keys in user data. `aws_iam_instance_profile` could be used instead.

Review your AWS Amazon EC2 settings

In addition to the above, there are other security points you should be aware of making sure that your .tf files are protected in Shisho Cloud.

AWS::EC2::SecurityGroup (CloudFormation)

The SecurityGroup in EC2 can be configured in CloudFormation with the resource name AWS::EC2::SecurityGroup. The following sections describe 10 examples of how to use the resource and its parameters.

Example Usage from GitHub

valid_security_group_with_egress.yml#L8
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "some_group_desc"
      VpcId:
        Ref: VpcId
      Tags:
2-wp-securitygroups.yml#L34
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Security group for Bastion instances
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
EC2.yml#L3
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: 'Spotify'
      GroupDescription: for the app nodes that allow ssh, http and docker ports
      VpcId : !ImportValue VPCMusicfeel
      SecurityGroupIngress:
5-nemsg.yml#L23
    Type: AWS::EC2::SecurityGroup
    Properties:
      SecurityGroupIngress:
      - ToPort: 3389
        IpProtocol: tcp
        CidrIp: 0.0.0.0/0
vpc4ab-resources.yml#L15
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !ImportValue vpc4
      GroupDescription: Allow all local TCP/UDP trafic
      SecurityGroupIngress:
        - IpProtocol: tcp
AWS_EC2_VPC.json#L64
        "resourceType": "AWS::EC2::SecurityGroup",
        "resourceId": "sg-0d46b170",
        "relationshipName": "Contains SecurityGroup"
      },
      {
        "resourceType": "AWS::EC2::SecurityGroup",
cfn-euca9846-secgroups-template.json#L6
                        "Type":"AWS::EC2::SecurityGroup",
                        "Properties":{
                                "GroupDescription":"Cloudformation Group",
                                "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ]
                        }
                },
SG-Violation-UnrestrictedAccess.json#L133
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Allow http to client host",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
cfn-euca10029-99-sgs-template.json#L13
                        "Type":"AWS::EC2::SecurityGroup",
                        "Properties":{
                                "VpcId" : { "Ref" : "VPC" },
                                "GroupDescription":"Cloudformation Group",
                                "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ]
                        }
cfn-euca10029-template.json#L13
                        "Type":"AWS::EC2::SecurityGroup",
                        "Properties":{
                                "VpcId" : { "Ref" : "VPC" },
                                "GroupDescription":"Cloudformation Group",
                                "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ]
                        }

Parameters

Explanation in CloudFormation Registry

Specifies a security group. To create a security group, use the VpcId property to specify the VPC for which to create the security group.

This type supports updates. For more information about updating stacks, see AWS CloudFormation Stacks Updates.

Important To cross-reference two security groups in the ingress and egress rules of those security groups, use the AWS::EC2::SecurityGroupEgress and AWS::EC2::SecurityGroupIngress resources to define your rules. Do not use the embedded ingress and egress rules in the AWS::EC2::SecurityGroup. Doing so creates a circular dependency, which AWS CloudFormation doesn't allow.

Frequently asked questions

What is AWS Amazon EC2 Security Group?

AWS Amazon EC2 Security Group is a resource for Amazon EC2 of Amazon Web Service. Settings can be wrote in Terraform and CloudFormation.

Where can I find the example code for the AWS Amazon EC2 Security Group?

For Terraform, the SchloTech/terraform_python_scripts, SnidermanIndustries/checkov-fork and tappoflw/tappo1 source code examples are useful. See the Terraform Example section for further details.

For CloudFormation, the stelligent/cfn-model, NuvOps/cfn-nested-wordpress and Luisfer25a/CloudFormation source code examples are useful. See the CloudFormation Example section for further details.