> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Security group unused exists remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the issue of unused security groups in AWS, follow these steps using the AWS Management Console:

        1. **Sign in to the AWS Management Console**: Go to [https://aws.amazon.com/](https://aws.amazon.com/) and sign in to your AWS account.

        2. **Navigate to the EC2 Dashboard**: Click on the "Services" dropdown menu at the top of the page, select "EC2" under the Compute section.

        3. **View Security Groups**: In the EC2 Dashboard, locate the "Security Groups" option in the navigation pane on the left and click on it.

        4. **Identify Unused Security Groups**: Review the list of security groups to identify the ones that are not associated with any running instances or resources. You can check the "Description" tab of each security group to see if it is actively being used.

        5. **Check Rules and Dependencies**: Before deleting a security group, ensure that there are no dependencies on it. Check if any other resources are using the security group for inbound/outbound rules.

        6. **Delete Unused Security Groups**: To delete a security group, select the checkbox next to the security group(s) you want to remove, click on the "Actions" dropdown menu, and select "Delete security group".

        7. **Confirm Deletion**: A confirmation dialog will appear asking you to confirm the deletion. Review the security group details once more and click "Yes, Delete" to confirm.

        8. **Verify Deletion**: Once the security group is deleted, verify that it has been removed from the list of security groups. Also, ensure that there are no adverse effects on any resources due to the deletion.

        9. **Repeat if Necessary**: Repeat the above steps for any other unused security groups that need to be removed.

        By following these steps, you can identify and remove unused security groups in AWS using the AWS Management Console. This helps in maintaining a clean and secure environment by reducing the attack surface and minimizing the risk of misconfigurations.
      </Accordion>

      <Accordion title="Using CLI">
        #

        To remediate the issue of unused security groups in AWS using AWS CLI, follow these steps:

        1. List all the security groups that are not associated with any EC2 instances:

        ```bash theme={null}
        aws ec2 describe-security-groups --query "SecurityGroups[?length(Instances) == '0'].{Name:GroupName, ID:GroupId}"
        ```

        2. Identify the security group that you want to delete from the list obtained in the previous step.

        3. Delete the unused security group using the following command:

        ```bash theme={null}
        aws ec2 delete-security-group --group-id YOUR_SECURITY_GROUP_ID
        ```

        Make sure to replace `YOUR_SECURITY_GROUP_ID` with the actual ID of the security group you want to delete.

        4. Confirm the deletion by listing the security groups again:

        ```bash theme={null}
        aws ec2 describe-security-groups --query "SecurityGroups[?length(Instances) == '0'].{Name:GroupName, ID:GroupId}"
        ```

        By following these steps, you can remediate the issue of unused security groups in AWS using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the issue of unused security groups in AWS using Python, you can follow these steps:

        1. Install the Boto3 library:

        ```bash theme={null}
        pip install boto3
        ```

        2. Use the following Python script to identify and delete unused security groups:

        ```python theme={null}
        import boto3

        def get_unused_security_groups():
            ec2 = boto3.client('ec2')
            
            # Get all security groups
            response = ec2.describe_security_groups()
            security_groups = response['SecurityGroups']
            
            # Get all instances
            response = ec2.describe_instances()
            instances = []
            for reservation in response['Reservations']:
                instances.extend(reservation['Instances'])
            
            # Get security group IDs attached to instances
            used_security_groups = set()
            for instance in instances:
                for sg in instance.get('SecurityGroups', []):
                    used_security_groups.add(sg['GroupId'])
            
            # Identify unused security groups
            unused_security_groups = [sg for sg in security_groups if sg['GroupId'] not in used_security_groups]
            
            return unused_security_groups

        def delete_security_group(group_id):
            ec2 = boto3.client('ec2')
            
            # Delete the security group
            response = ec2.delete_security_group(GroupId=group_id)
            print(f"Deleted security group: {group_id}")

        if __name__ == '__main__':
            unused_security_groups = get_unused_security_groups()
            for sg in unused_security_groups:
                delete_security_group(sg['GroupId'])
        ```

        3. Replace the AWS credentials in the AWS CLI configuration file located at `~/.aws/credentials` or use an IAM role that has the necessary permissions to list and delete security groups.

        4. Run the Python script to identify and delete the unused security groups.

        Please ensure that you have the necessary permissions to delete security groups before running this script.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Example of a REQUIRED security group that you keep and continue to manage
        resource "aws_security_group" "app_sg" {
          name        = "APP_SG_NAME"          # replace with the required SG name
          description = "Security group for APP_DESCRIPTION"
          vpc_id      = "VPC_ID"               # replace with your VPC ID

          ingress {
            description = "APP_INGRESS_DESCRIPTION"
            from_port   = 443
            to_port     = 443
            protocol    = "tcp"
            cidr_blocks = ["APP_ALLOWED_CIDR_BLOCK"] # e.g. "10.0.0.0/16"
          }

          egress {
            from_port   = 0
            to_port     = 0
            protocol    = "-1"
            cidr_blocks = ["0.0.0.0/0"]
          }

          tags = {
            Name = "APP_SG_TAG_NAME"
          }
        }

        # Any UNUSED security group should be removed from Terraform entirely:
        #   - Locate the aws_security_group "UNUSED_SG" block
        #   - Confirm via CLI it is not associated with ENIs or referenced by other SGs
        #   - Delete that resource block from your *.tf files
        #
        # Example of a block you would DELETE from the configuration:
        #
        # resource "aws_security_group" "unused_sg" {
        #   name        = "UNUSED_SG_NAME"
        #   description = "Unused security group – scheduled for removal"
        #   vpc_id      = "VPC_ID"
        # }
        #
        # WARNING: Removing the resource block is a destructive action and cannot be undone.
        #          If the security group is still in use or referenced, deleting it can cause
        #          network connectivity loss or Terraform apply failures.
        ```

        Removing the `aws_security_group` block from Terraform corresponds to running `aws ec2 delete-security-group` for that group: on `terraform plan` you should see a `- destroy` action for each unused security group resource that you removed from the configuration and no changes for the ones you kept.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
