Skip to main content

EC2

EC2 provides resizable compute capacity in the cloud. It allows users to run virtual servers known as instances, providing flexibility and scalability to host various applications, manage workloads, and build a range of computing solutions on the AWS cloud platform.

Types of EC2

instance-Type-Naming

AWS-Instance-Types

Spot Instance

You can use Spot Instances to purchase extra computing power at a discounted price to supplement On-Demand Instances. They are a more affordable option than On-Demand EC2 pricing. Flexible and fault-tolerant applications and high-performance workloads use them. Spot Instances are also ideal for flexible workloads, such as data analysis, batch jobs, background processing, and optional tasks. For more information, see Amazon EC2 Spot Instances.

AWS Spot Instances help reduce On-Demand Instance costs on EC2. You can use Spot Instances to supplement On-Demand Instances. Spot Instances shouldn’t handle all workloads because of potential service disruptions.

Spot Instance interruption

Amazon EC2 terminates, stops, or hibernates your Spot Instance when Amazon EC2 needs the capacity back. Amazon EC2 provides a Spot Instance interruption notice, which gives the instance a two-minute warning before it is interrupted.

Spot Instance request

If your Spot Instance request is active and has an associated running Spot Instance, or your Spot Instance request is disabled and has an associated stopped Spot Instance, canceling the request does not terminate the instance; you must terminate the running Spot Instance manually.

Moreover, to cancel a persistent Spot request and terminate its Spot Instances, you must cancel the Spot request first and then terminate the Spot Instances.

Spot Instance Interruption behaviors

You can specify that Amazon EC2 should do one of the following when it interrupts a Spot Instance:

  • Stop the Spot Instance
  • Hibernate the Spot Instance
  • Terminate the Spot Instance (default behavoir)

Spot Fleet

The Spot Fleet selects the Spot Instance pools that meet your needs and launches Spot Instances to meet the target capacity for the fleet. By default, Spot Fleets are set to maintain target capacity by launching replacement instances after Spot Instances in the fleet are terminated.

When launching instances, Spot Fleet uses the allocation strategy that you specify to pick the specific pools from all your possible pools. You can specify one of the following allocation strategies:

  • priceCapacityOptimized
  • capacityOptimized
  • diversified
  • lowestPrice
  • InstancePoolsToUseCount

ec2-allocation

Examples

If your fleet is large or runs for a long time, you can improve the availability of your fleet by distributing the Spot Instances across multiple pools using the diversified strategy.

For example, if your Spot Fleet specifies 10 pools and a target capacity of 100 instances, the fleet launches 10 Spot Instances in each pool. If the Spot price for one pool exceeds your maximum price for this pool, only 10% of your fleet is affected. Using this strategy also makes your fleet less sensitive to increases in the Spot price in any one pool over time. With the diversified strategy, the Spot Fleet does not launch Spot Instances into any pools with a Spot price that is equal to or higher than the On-Demand price.


To create an inexpensive and diversified fleet, use the lowestPrice strategy in combination with InstancePoolsToUseCount. For example, if your target capacity is 10 Spot Instances, and you specify 2 Spot capacity pools (for InstancePoolsToUseCount), Spot Fleet will draw on the two lowest-priced pools to fulfill your Spot capacity.

You can use a low or high number of Spot capacity pools across which to allocate your Spot Instances. For example, if you run batch processing, it is recommended to specify a low number of Spot capacity pools (for example, InstancePoolsToUseCount=2) to ensure that your queue always has compute capacity while maximizing savings.

If you run a web service, AWS recommends specifying a high number of Spot capacity pools (for example, InstancePoolsToUseCount=10) to minimize the impact if a Spot capacity pool becomes temporarily unavailable.


Take note that Spot Fleet attempts to draw Spot Instances from the number of pools that you specify on a best-effort basis. If a pool runs out of Spot capacity before fulfilling your target capacity, Spot Fleet will continue to fulfill your request by drawing from the next lowest-priced pool. To ensure that your target capacity is met, you might receive Spot Instances from more than the number of pools that you specified. Similarly, if most of the pools have no Spot capacity, you might receive your full target capacity from fewer than the number of pools that you specified.

Reserved Instance

Reserved Instances provide you with significant savings on your Amazon EC2 costs compared to On-Demand Instance pricing. Reserved Instances are not physical instances, but rather a billing discount applied to the use of On-Demand Instances in your account.

When you purchase a Reserved Instance, you determine the scope of the Reserved Instance. The scope is either regional or zonal.

  • Regional: When you purchase a Reserved Instance for a Region, it's referred to as a regional Reserved Instance. It does not reserve capacity.
  • Zonal: When you purchase a Reserved Instance for a specific Availability Zone, it's referred to as a zonal Reserved Instance. It reserves capacity.
Upgrade and downgrade instance type

When you purchase a Reserved Instance, you can choose between a Standard or Convertible offering class. The Reserved Instance applies to a single instance family, platform, scope, and tenancy over a term.

You can upgrade or downgrade the instance size of both Standard and Convertible Reserved Instance. However, only the Convertible Reserved instance can change the instance type.

On-demand Instance

Capacity Reservations

By creating Capacity Reservations, you ensure that you always have access to EC2 capacity when you need it, for as long as you need it(no commitment is required). You can also sepecify the duratin for how long you want it to be. Please remember capacity reservations do not offer any billing discounts

AWS official link: On-Demand Capacity Reservations

EBS–optimized instances

To optimize EBS performance for handling a high volume of transactions from your EC2 instance, you can change your instance type to those EBS–optimized instances. Supported instances

An Amazon EBS–optimized instance uses an optimized configuration stack and provides additional, dedicated capacity for Amazon EBS I/O. This optimization provides the best performance for your EBS volumes by minimizing contention between Amazon EBS I/O and other traffic from your instance.

T2 Unlimited Mode

t2-t3-bucket

When you use t2.unlimited, it doesn’t actually mean that you have unlimited resources. Instead, it changes what happens when you exhaust your burst credits. Instead of being throttled, unlimited mode creates extra charges to your AWS account. From the AWS doc page on Unlimited Mode:

A burstable performance instance configured as unlimited can burst above the baseline for as long as required. This enables you to enjoy the low instance hourly price for a wide variety of general-purpose applications, and ensures that your instances are never held to the baseline performance.

You can think of unlimited mode as an “unlimited burst” mode, where more bursting costs you more money, but you can burst as much as your application requires.

There are many burstable resources in AWS. GP2 and magnetic EBS volumes have burstable capacity and certain instance types have burstable CPU. From the same AWS documentation page as above:

  • T3 instances are launched as unlimited by default.
  • T2 instances are launched as standard by default.

To enable unlimited mode for T2 instance, check T2 Unlimited – Going Beyond the Burst with High Performance

Placement Groups

A Spread placement group is a group of instances that are each placed on distinct racks, with each rack having its own network and power source.

Spread placement groups are recommended for applications that have a small number of critical instances that should be kept separate from each other. Launching instances in a spread placement group reduces the risk of simultaneous failures that might occur when instances share the same racks.

A spread placement group can span multiple Availability Zones in the same Region. You can have a maximum of 7 running instances per Availability Zone per group. Therefore, to deploy 15 EC2 instances in a single Spread placement group, you will need to use 3 AZs.

placementgroups Source: AWS - Placement Groups

Cluster

  • Same rack and same availability zone
  • Great network, low latency (10Gbps bandwidth between instances)
  • Cons: if rack fails then all the EC2 instances will fail at the same time

Usage: Big data job that needs to complete fast, Application with low latency and high throughput.

Spread

  • All EC2 instance will be located on different hardware
  • Span across multiple AZ
  • Reduced risk of simultaneous failure
  • Limit of 7 instances per AZ per placement group

Usage: Application that needs maximize highly availability, Critical Applications that needs to be isolated from failure from each other

Partition

  • Up to 7 partitions per AZ with 100s of EC2 instances
  • The instances of 1 partition do not share racks with instances of other partitions
  • A partition failure can affect many EC2 instances from same partition but it won't affect other EC2 instances on other partitions
  • EC2 instances can get access to the partition information using metadata

Usage: This strategy is typically used by large distributed and replicated workloads, such as Hadoop, Cassandra, and Kafka.

Behavior

Reboot

Rebooting an instance only performs a graceful restart on your EC2 instance without instance interruption. The instance will remain in the same hardware. To resolve the system status check failure issue, you need to migrate the instance to a new host.

What is Status check?

AWS monitors the health of each EC2 instance with two status checks. An EC2 instance becomes unreachable if a status check fails.

EC2 life cycle - Hibernate

When you EC2 Instance Hibernate to hibernate an instance, AWS signals the operating system to perform hibernation (suspend-to-disk). Hibernation saves the contents from the instance memory (RAM) to your Amazon EBS root volume. AWS then persists the instance's Amazon EBS root volume and any attached Amazon EBS data volumes instead of losing the data stored in memory (RAM) when stopping an instance.

When you start your instance:

  • The Amazon EBS root volume is restored to its previous state
  • The RAM contents are reloaded
  • The processes that were previously running on the instance are resumed
  • Previously attached data volumes are reattached and the instance retains its instance ID

Overview of EC2 hibernation: hibernate Source: Let’s talk about EC2 Placement Groups and Hibernate

Recovered instance is identical

A recovered instance is identical to the original instance, including the instance ID, private IP addresses, Elastic IP addresses, and all instance metadata. If the impaired instance has a public IPv4 address, the instance retains the public IPv4 address after recovery. If the impaired instance is in a placement group, the recovered instance runs in the placement group.

Scheduled events

TL;DR - AWS manages regional scheduled events for all the EC2 instances

AWS allows for scheduling events on instances, such as reboot, stop/start, or retirement. These events are infrequent and trigger notifications via email, providing event details and timing. Scheduled events are managed by AWS which means you can't configure scheduled events for your instances, but you can customize notifications and take actions during events.

Amazon EC2 can create the following types of events for your instances, where the event occurs at a scheduled time:

  • Instance stop: At the scheduled time, the instance is stopped. When you start it again, it's migrated to a new host. Applies only to instances backed by Amazon EBS.
  • Instance retirement: At the scheduled time, the instance is stopped if it is backed by Amazon EBS, or terminated if it is backed by instance store.
  • Instance reboot: At the scheduled time, the instance is rebooted.
  • System reboot: At the scheduled time, the host for the instance is rebooted.
  • System maintenance: At the scheduled time, the instance might be temporarily affected by network maintenance or power maintenance.

Status checks

Status checks are built into Amazon EC2, so they cannot be disabled or deleted. When status checks fail, you have 2 options to do the followup actions

  • Option 1: CloudWatch Alarm
    • Send notifications using SNS
    • Recover EC2 instance with same private/public IP, EIP, metadata, and Placement Group
  • Option 2: Auto Scaling Group
    • Set min/max/desired 1 to recover an instance but won't keep the same private and elastic IP

SYSTEM status checks

System status checks monitor the AWS systems on which your instance runs

  • Problem with the underlying host. Example: 
    • Loss of network connectivity
    • Loss of system power
    • Software issues on the physical host
    • Hardware issues on the physical host that impact network reachability
  • Either wait for AWS to fix the host, OR
  • Move the EC2 instance to a new host = STOP & START the instance (if EBS backed)

INSTANCE status checks

Instance status checks monitor the software and network configuration of your individual instance

  • Example of issues
    • Incorrect networking or startup configuration
    • Exhausted memory
    • Corrupted file system
    • Incompatible kernel
  • Requires your involvement to fix
  • Restart the EC2 instance, OR
  • Change the EC2 instance configuration

Configuration

Shutdown Behavior

InstanceInitiatedShutdownBehavior

By default, the Shutdown Behavior is set to "stop" for EC2 instances. When an instance is stopped, the instance is moved to a stopped state, and the instance's Amazon EBS (Elastic Block Store) volumes are preserved. This allows you to start the instance again later and retain the data and configuration.

However, you can also choose to set the Shutdown Behavior to "terminate" for an instance. In this case, when the instance is stopped, it is automatically terminated, and the instance and its associated resources, including EBS volumes, are deleted. The data and configuration stored on the instance and its volumes will be lost.

  aws ec2 run-instance --region ap-south-1 \
--count 1 \
--image-id myamiid \
--security-group-ids mysgid \
--subnet-id mysubnetid \
--key-name mykeypair \
--instance-type t2.micro \
--tag-specification 'ResourceType=instance,Tags=[{Key=Name,Value=Myinstance}]'
--instance-initiated-shutdown-behavior=terminate

This terminate behavior is not applicable when shutting down from AWS console. You have to run shutdown command by using operating system command from the EC2 instance to terminate the EC2 instance.

DisableApiTermination

By default, you can terminate your instance using the Amazon EC2 console, command line interface, or API. To prevent your instance from being accidentally terminated using Amazon EC2, you can enable termination protection for the instance. The DisableApiTermination attribute controls whether the instance can be terminated using the console, CLI, or API.

warning

You can still terminate the DisableApiTermination EC2 instance

  • by initiating shutdown from the instance
  • or shutdown by ASG

Termination protection

This is a setting to protect against accidental termination in AWS Console or CLI. By default, termination protection is disabled for your instance. You can set the value of this attribute when you launch the instance, while the instance is running, or while the instance is stopped (for Amazon EBS-backed instances).

We have an instance which its shutdown behavior is terminate and enable terminate protection is ticked

  • When shutdowning the instance from the OS, what will happen?
  • The instance will still be terminated!

User data scripts

User Data is generally used to perform common automated configuration tasks and even run scripts after the instance starts.

When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2:

  • shell scripts
  • cloud-init directives.
Default behaviour
  • By default, scripts entered as user data are executed with root user privileges
  • By default, user data runs only during the boot cycle when you first launch an instance

ec2-bootstrap-script

Instance profile

An instance profile is a container that holds an IAM role. When you launch an EC2 instance with an associated profile, the instance can then use the permissions granted by the IAM role to access only those AWS services or resources the role permits — without having to manually manage credentials or access keys. This helps improve security and simplifies AWS resource management.

Make sure instance profile has enough permission to access other AWS services

Imagine there is a case - a CloudWatch Logs Agent has been set up on the instance to publish application logs. Despite having full access to the AWS account, the administrator is still unable to view the logs in the CloudWatch Logs Console. What should I do?

Attach an IAM role with sufficient CloudWatch Logs permission to the instance profile of the EC2 instance

Tenancy

Each EC2 instance that you launch into a VPC has a tenancy attribute. This attribute has the following values.

  • Shared (default) --- Multiple AWS accounts may share the same physical hardware.
  • Dedicated Instance (dedicated) --- Your instance runs on single-tenant hardware.
  • Dedicated Host (host) --- Your instance runs on a physical server with EC2 instance capacity fully dedicated to your use, an isolated server with configurations that you can control.

ec2-tenancy

Source: New – T3 Instances on Dedicated Single-Tenant Hardware

The more isolated of your EC2 instance, the more expensive it will be. Here is the price ordering: Dedicated Host > Dedicated instance > Shared(default)

Type change

You can only change the tenancy of an instance from dedicated to host, or from host to dedicated after you've launched it.

Dedicated host vs Dedicated instances

Dedicated instances: If you stop/start instance, you can get some other hardware somewhere else. Basically, the hardware is "yours" (you are not sharing it with others) for the time your instance is running. You stop/start it, you may get different physical machine later on (maybe older, maybe newer, maybe its specs will be a bit different), and so on. So your instance is moved around on different physical servers - whichever is not occupied by others at the time. Thus it may share hardware with other instances from the same AWS account that are not Dedicated Instances.

Dedicated host: With Dedicated Host the physical server is basically yours. It does not change, it's always the same physical machine for as long as you are paying. It also enable you to use

  • your existing server-bound software licenses (e.g. your existing per-socket, per-core, or per-VM software licenses, including Windows Server, Microsoft SQL Server, SUSE, and Linux Enterprise Server.)
  • address corporate compliance and regulatory requirements.

Source: Full comparsion table

AMI

  • An AMI includes the following:
    • A template for the root volume for the instance (for example, an operating system, an application server, and applications)
    • Launch permissions that control which AWS accounts can use the AMI to launch instances
    • A block device mapping that specifies the volumes to attach to the instance when it’s launched
  • Behaviours
    • As the AMI is tied to a specific AWS Region, you need to copy the AMI to other AWS Regions if required.
    • Linux paravirtual (PV) AMIs aren't supported in all AWS Regions and copying these across unsupported Regions results in this error
    • Copy & recover
      • You can copy both Amazon EBS-backed AMIs and instance-store-backed AMIs.
      • Copying a source AMI results in an identical but distinct target AMI with its own unique identifier(AMI ID).
      • You can change or deregister the source AMI with no effect on the target AMI.
      • You can't restore or recover** a deleted or deregistered AMI**. The only option is to create a new, identical AMI
  • Automation
    • EC2 Image Builder is a service AWS offer that allows you to automate the process of building custom AMIs. It also handles the full pipeline for creating, testing and even distributing the machine images.
    • Image Builder uses the AWS Task Orchestrator and Executor (AWSTOE) component management application to orchestrate complex workflows. Build and test components that work with the AWSTOE application are based on YAML documents that define the scripts to customize or test your image.
      • For AMI images, Image Builder installs components and the AWSTOE component management application on its Amazon EC2 build and test instances.
      • For container images, the components and AWSTOE component management application are installed inside of the running container.
      • An AWS document defines AWSTOE as a "standalone application that creates, validates, and runs commands within a component definition framework." With AWSTOE, you can modify system configuration and orchestrate complex workflows without writing code. That means you can have a series of components written in YAML, which are instructions that you want to be executed on your operating system, and AWSTOE can simply run and validate against your operational system.
  • A Golden AMI is an AMI that you standardize through configuration, consistent security patching, and hardening. It also contains agents you approve for logging, security, performance monitoring, etc. Reference: Announcing the Golden AMI Pipeline
  • ASG need to have permission to access the customer-managed customer master keys (CMKs) when an IAM is encrypted.

Reference: Linux AMI virtualization types (HVM & PV)

No-Reboot Option

ami-no-reboot

  • By default, when Amazon EC2 creates the new AMI, it reboots the instance so that it can take snapshots of the attached volumes while data is at rest, in order to ensure a consistent state (file system integrity).
  • Enabling this option allowing you to create an AMI without shutting down your instance.
    • It is beneficial in situations where you want to create an AMI without disrupting the availability or continuity of your applications.
    • The AMI will be crash-consistent (all the volumes are snapshotted at the same time), but not application-consistent (all the operating system buffers are not flushed to disk before the snapshots are created).
AWS Backup does not reboot EC2 instances at any time.

AWS Backup follows the default mechanism of taking backups. In this case, the default mechanism for backing up EBS volumes is to backup with no-reboot behavior. This means that AWS Backup will not be able to help you create an AMI that guarantees file system integrity since you need to reboot the instance to do this.

To maintain file system integrity you need to provide the reboot parameter while taking images which is (EventBridge + Lambda + CreateImage API with reboot paramenter)

The detailed steps are using the CreateImage API, build a Lambda function that will take an AMI of the EC2 instance and include a reboot parameter. Then, create a rule to invoke the Lambda function daily on Amazon EventBridge (Amazon CloudWatch Events).

Screenshot to show you can't set the reboot parameter on AWS Backup: amazon_aws_backup_ebs_noreboot_only

AWS Backup with tags
  1. Create a backup plan in AWS Backup.
  2. Assign tags to resources based on the environment ( Production, Development, Testing).
  3. Create one backup policy for production environments and one backup policy for non-production environments.
  4. Schedule the backup plan based on the organization's backup policies

In addition, AWS Backup leverages AWS Organizations to implement and maintain a central view of backup policy across resources in a multi-account AWS environment. What is AWS backup?

Copy AMIs across regions

As the AMI is tied to a specific AWS Region, you need to copy the AMI to other AWS Regions if required.

copy-AMI

Source: AWS - Encryption and copying

Copy encrypted snapshot

  • Copying an AMI backed by an encrypted snapshot cannot result in an unencrypted target snapshot.
  • You can copy AMIs with encrypted snapshots and also change encryption status during the copy process.

The following table shows encryption support for various AMI-copying scenarios. While it is possible to copy an unencrypted snapshot to yield an encrypted snapshot, you cannot copy an encrypted snapshot to yield an unencrypted one.

ScenarioDescriptionSupported
1Unencrypted-to-unencryptedYes
2Encrypted-to-encryptedYes
3Unencrypted-to-encryptedYes
4Encrypted-to-unencryptedNo

Source: AWS - Encryption and copying

Cross-accounts sharing AMIs

  • Sharing an AMI does not affect the ownership of the AMI
  • If you're sharing the AMI with an encrypted volume that means that you need to share any key that is attached to that volume as well that was used to encrypt and decrypt that volume otherwise the targeted account cannot use your volume.
  • What will happen if an AMI shared from account A to account B and then de-registered the AMI in a few days?
    • You can't launch new instances from the AMI in account A or in account B
    • The instances already launched from the shared AMI in account B, are not impacted by this de-registration
  • You can share an AMI with specific AWS accounts from the AMI Console UI without making the AMI public. All you need is the AWS account IDs.

Cross-accounts copying AMI

  • If you copy an AMI that has been shared with your account, you are the owner of the target AMI in your account
  • The owner of the source AMI must grant you read permissions for the storage that backs the AMI (EBS Snapshot)
  • You do not need to share the Amazon EBS snapshots that an AMI references in order to share the AMI, because the system automatically provides the access to the referenced Amazon EBS snapshots for the launch.
  • You can only share AMIs that have unencrypted volumes and volumes that are encrypted with a customer-managed CMK. If you share an AMI with encrypted volumes, you as a owner must share any CMKs used to encrypt them to the account that you want to share.

Recover/rebuild the accidentally deleted AMI

Once an AMI is deleted or deregistered, it cannot be restored or recovered. However, you have two options to create an identical AMI:

  • Use Amazon EBS snapshots created during the AMI creation process
    • If you accidentally delete the AMI, you can launch an identical AMI using one of the retained EBS snapshots.
  • Recover from existing EC2 instances
    • If the AMI and snapshots are deleted, you can still recover the AMI from existing EC2 instances launched using the deleted AMI. Note that this process may require rebooting the instance unless the "No reboot" option was selected during instance launch.

Troubleshooting

Availability

An application is currently hosted on four EC2 instances (behind Application Load Balancer) deployed in a single Availability Zone (AZ). To maintain an acceptable level of end-user experience, the application needs at least 4 instances to be always available.

What is your recommandation to achieve high availability with MINIMUM cost?

Deploy the instances in three Availability Zones. Launch two instances in each Availability Zone.

Cost

You have deployed a database technology that has a synchronous replication mode to survive disasters in data centers. The database is therefore deployed on two EC2 instances in two Availability Zones. The database must be publicly available so you have deployed the EC2 instances in public subnets. The replication protocol currently uses the EC2 public IP addresses.

What can you do to decrease the replication cost?

The answer is to use the EC2 instances private IP for the replication - The source of the cost is that traffic between two EC2 instances is going over the public internet, thus incurring high costs. Here, the correct answer is to use Private IP, so that the network remains private, for a minimal cost.

How can EC2 securely connect to AWS services?

Use an IAM Instance Role

  • instead of passing your own AWS account creditental in your codebase
  • You can’t use SSM either, because you also need your credential too call the AWS SDK to get the SSM which - again you need to provide your account credential (A question of which came first: the chicken or the egg?)

Each Amazon EC2 instance contains metadata that the AWS CLI can directly query for temporary credentials. When an IAM role is attached to the instance, the AWS CLI automatically and securely retrieves the credentials from the instance metadata.

ec2-role-instance

Source: Using an IAM role to grant permissions to applications running on Amazon EC2 instances

Network issues

Adding an ENI doesn't not increase the networking performance. Upgrading the EC2 instance to a larger instance type does

Launch Issues

InstanceLimitExceeded

info

vCPU-based limits only apply to running On-Demand instances and Spot instances

The InstanceLimitExceeded error in AWS occurs when you attempt to launch or create new EC2 instances but reach your account's limit for the maximum number of vCPUs per region. Each AWS account has certain service limits in place, including EC2 instance limits, to prevent abuse or overutilization of resources.

For t2 micros, we can see we have one vCPU, but if we choose an instance such as the C59 xlarge, we have 36 vCPU, so using this instance type, it would quickly reach the limit.

Resolution: Either launch the instance in a different region or request AWS to increase your limit of the region

InsufficientInstanceCapacity

You get the InsufficientInstanceCapacity error when AWS does not have enough on-demand capacity regarding the particular AZ

SSH Issues

  • Make sure the private key (pem file) on your linux machine has 400 permissions, else you will get “Unprotected private key file” error

  • Make sure the username for the OS is given correctly when logging via SSH, else you will get “Host key not found”, “Permission denied”, or “Connection closed by [instance] port 22” error

  • Possible reasons for “Connection timed out” to EC2 instance via SSH:

    • SG is not configured correctly
    • NACL is not configured correctly
    • Check the route table for the subnet (routes traffic destined outside VPC to IGW)
    • Instance doesn’t have a public IPv4
    • CPU load of the instance is high

Using a single SSH key pair for all EC2 instances in all AWS Regions

  1. Generate a public SSH key (.pub) file from the private SSH key (.pem) file.
  2. Set the AWS Region you wish to import to.
  3. Import the public SSH key into the new Region.

https://aws.amazon.com/premiumsupport/knowledge-center/ec2-ssh-key-pair-regions/

Change the EC2 instance type which is backed by EBS

In order to change the EC2 instance type, you must stop your Amazon EBS–backed instance before you can change its instance type. When you stop and start an instance, AWS moves the instance to new hardware; however, the instance ID does not change.

Change EC2 instance type in an Auto Scaling group

If your instance is in an Auto Scaling group, the Amazon EC2 Auto Scaling service marks the stopped instance as unhealthy, and may terminate it and launch a replacement instance. To prevent this, you can suspend the scaling processes for the group while you're resizing your instance.

EBS backed EC2 goest from pending to terminated immediately

EC2 instance goes from the pending state to the terminated state immediately after restarting it. Below are the reasons:

  • You’ve reached your EBS volume limit.
  • An EBS snapshot is corrupt.
  • The root EBS volume is encrypted and you do not have permission to access the KMS key for decryption.
  • The instance store-backed AMI that you used to launch the instance is missing a required part (an image.part.xx file).