> ## 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.

# EC2 Instance Count Should Not Exceed the Limit

### More Info:

Your AWS account should not reached the limit set for the number of EC2 instances.

### Risk Level

Informational

### Address

Operational Maturity

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the "EC2 Instance Count Should Not Exceed the Limit" misconfiguration in AWS using the AWS console, follow these steps:

        1. Log in to the AWS Management Console.
        2. Navigate to the EC2 Dashboard.
        3. Click on the "Limits" link in the left-hand menu.
        4. In the "Service" drop-down menu, select "EC2".
        5. In the "Limit types" drop-down menu, select "Running On-Demand Instances".
        6. Check the current limit for the region where the misconfiguration was detected.
        7. If the limit has been exceeded, click on the "Request limit increase" button.
        8. Fill out the form with the required information, including the new limit request and the reason for the increase.
        9. Submit the form and wait for AWS to review and approve the request.
        10. Once the request is approved, the limit will be increased, and you can launch additional EC2 instances within the new limit.

        Note: It is important to regularly monitor your EC2 instance usage and request limit increases as needed to avoid exceeding the limits and incurring unexpected charges.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of EC2 Instance Count Should Not Exceed the Limit in AWS using AWS CLI, you can follow the below steps:

        1. First, check the current EC2 instance count using the AWS CLI command:

        ```
        aws ec2 describe-instances --query 'Reservations[].Instances[].InstanceId' --output text | wc -w
        ```

        2. If the instance count is exceeding the limit, you need to stop or terminate some of the instances to bring the count below the limit.

        3. To stop an instance, use the AWS CLI command:

        ```
        aws ec2 stop-instances --instance-ids <instance-id>
        ```

        Here, replace `<instance-id>` with the actual ID of the instance that you want to stop.

        4. To terminate an instance, use the AWS CLI command:

        ```
        aws ec2 terminate-instances --instance-ids <instance-id>
        ```

        Here, replace `<instance-id>` with the actual ID of the instance that you want to terminate.

        5. Repeat step 3 and 4 until the instance count is below the limit.

        6. Once the instance count is below the limit, you can monitor it using CloudWatch alarms and set up notifications to alert you if the count exceeds the limit again in the future.

        Note: It is important to regularly monitor your AWS resources and set up alerts to avoid exceeding the limits and incurring unexpected charges.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of EC2 instance count exceeding the limit in AWS using Python, follow the below steps:

        1. Import the necessary libraries:

        ```python theme={null}
        import boto3
        ```

        2. Set up an AWS session with the required credentials:

        ```python theme={null}
        session = boto3.Session(
            aws_access_key_id='YOUR_ACCESS_KEY_ID',
            aws_secret_access_key='YOUR_SECRET_ACCESS_KEY',
            region_name='YOUR_REGION_NAME'
        )
        ```

        3. Create an EC2 client using the session:

        ```python theme={null}
        ec2_client = session.client('ec2')
        ```

        4. Get the current instance count and the instance limit using the describe\_account\_attributes() method:

        ```python theme={null}
        response = ec2_client.describe_account_attributes(
            AttributeNames=['max-instances']
        )
        ```

        5. Check if the current instance count exceeds the instance limit:

        ```python theme={null}
        max_instances = int(response['AccountAttributes'][0]['AttributeValues'][0]['AttributeValue'])
        current_instances = ec2_client.describe_instances()['Reservations']
        if len(current_instances) > max_instances:
            print("Current instance count exceeds the instance limit.")
        ```

        6. If the current instance count exceeds the instance limit, terminate the excess instances:

        ```python theme={null}
        excess_instances = len(current_instances) - max_instances
        for i in range(excess_instances):
            instance_id = current_instances[i]['Instances'][0]['InstanceId']
            ec2_client.terminate_instances(InstanceIds=[instance_id])
            print("Instance {} terminated.".format(instance_id))
        ```

        7. The final code should look like this:

        ```python theme={null}
        import boto3

        session = boto3.Session(
            aws_access_key_id='YOUR_ACCESS_KEY_ID',
            aws_secret_access_key='YOUR_SECRET_ACCESS_KEY',
            region_name='YOUR_REGION_NAME'
        )

        ec2_client = session.client('ec2')

        response = ec2_client.describe_account_attributes(
            AttributeNames=['max-instances']
        )

        max_instances = int(response['AccountAttributes'][0]['AttributeValues'][0]['AttributeValue'])
        current_instances = ec2_client.describe_instances()['Reservations']

        if len(current_instances) > max_instances:
            excess_instances = len(current_instances) - max_instances
            for i in range(excess_instances):
                instance_id = current_instances[i]['Instances'][0]['InstanceId']
                ec2_client.terminate_instances(InstanceIds=[instance_id])
                print("Instance {} terminated.".format(instance_id))
        else:
            print("Current instance count does not exceed the instance limit.")
        ```

        Note: Make sure to replace the placeholders 'YOUR\_ACCESS\_KEY\_ID', 'YOUR\_SECRET\_ACCESS\_KEY', and 'YOUR\_REGION\_NAME' with the actual values.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Option 1: Terminate an unneeded EC2 instance by removing it from Terraform
        # WARNING: Destroying this resource will terminate the EC2 instance and delete its ephemeral storage.
        #          Ensure all necessary data is backed up before applying.
        resource "aws_instance" "UNNEEDED_INSTANCE" {
          # REMOVE this entire resource block (or reduce a count/from list so this instance is no longer managed)
          # to have Terraform issue a destroy for the underlying EC2 instance.

          ami           = "AMI_ID_TO_REPLACE"
          instance_type = "t3.micro"
          subnet_id     = "SUBNET_ID"
          # ...other required arguments...
        }
        ```

        ```hcl theme={null}
        # Option 2: Request an EC2 running on‑demand instance quota increase via Service Quotas
        # This matches:
        #   aws service-quotas request-service-quota-increase \
        #     --service-code ec2 --quota-code L-1216C47A --desired-value <new_desired_limit>
        resource "aws_servicequotas_service_quota" "ec2_running_ondemand_standard" {
          service_code = "ec2"
          quota_code   = "L-1216C47A"        # Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances
          value        = NEW_DESIRED_LIMIT   # e.g., 75; must be >= 50 and above your current quota
        }
        ```

        If you remove an `aws_instance` resource (or reduce its `count`/remove an element from `for_each`), applying the plan will permanently terminate that EC2 instance; this is irreversible.

        For verification, `terraform plan` should show either:

        * a `-` destroy for the specific `aws_instance` you chose to terminate, and no unexpected changes to others, or
        * a `+` create for `aws_servicequotas_service_quota.ec2_running_ondemand_standard` with `value = NEW_DESIRED_LIMIT`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-limits.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-limits.html)
