Skip to main content

EC2 Instance Counts Remediation

Triage and Remediation

Remediation

Using Console

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.

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

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

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

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

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

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:
import boto3
  1. Set up an AWS session with the required credentials:
session = boto3.Session(
aws_access_key_id='YOUR_ACCESS_KEY_ID',
aws_secret_access_key='YOUR_SECRET_ACCESS_KEY',
region_name='YOUR_REGION_NAME'
)
  1. Create an EC2 client using the session:
ec2_client = session.client('ec2')
  1. Get the current instance count and the instance limit using the describe_account_attributes() method:
response = ec2_client.describe_account_attributes(
AttributeNames=['max-instances']
)
  1. Check if the current instance count exceeds the instance limit:
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.")
  1. If the current instance count exceeds the instance limit, terminate the excess 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))
  1. The final code should look like this:
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.

Using Terraform
# 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...
}
# 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.