> For the complete documentation index, see [llms.txt](https://mamawhocode.gitbook.io/aws/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mamawhocode.gitbook.io/aws/services/compute/ec2.md).

# EC2

Elastic Compute Cloud

[FAQs](https://aws.amazon.com/ec2/faqs/?saa=sec\&sec=prep) |&#x20;

## Overview

* A virutal server
* Can scale up and down within minutes
* SLA = 99.99%

### Instance type

* T2, G is a general purpose instance type.
* X1e, R is memory optimized.
* H1 is storage optimized.
* P3 is for advanced computing and can include special hardware for graphics processing.

### EBS Volume

[EBS](/aws/services/compute/ec2/ebs.md) is a network disk that is attached to EC2.

### EC2 Instance store

When you need very high IOPS storage for EC2, refer to [EC2 Instance store](/aws/services/compute/ec2/instancestore.md).

***

## Provision EC2

Steps to provision an EC2 instance

* Remember to create & download keypair.
* `Capacity reservation` (reserve capacity for EC2 instance in a specific AZ): `None`. Turn this to None to save cost.&#x20;

![](https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2Fgit-blob-fb80151a8c533bf882f865dc251fa2c82bb30ce5%2FEC2_20220501112839.png?alt=media)

***

## Connect to EC2

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FY0nbtgfRTmOy96zMIEi5%2Fimage.png?alt=media&amp;token=5ec1424f-3be0-409e-97b6-0d4f09130c9f" alt="" width="563"><figcaption><p>through console, HTTP, SSH</p></figcaption></figure>

### Session Manager (easiest)

<figure><img src="https://docs.aws.amazon.com/images/prescriptive-guidance/latest/patterns/images/pattern-img/09dad38a-0430-4905-b45f-68a3676fd089/images/e1aa3153-236e-40c4-9715-147a8b97a24f.png" alt=""><figcaption><p>Session Manager Connection architecture</p></figcaption></figure>

* Session are secured using AWS Key Management service key.
* Can log session commands in S3 bucket or CloudWatch Logs log group.
* No SSH, no Bastion host, No need to open inbound ports.
* 1-click access.

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FPK6J63CCebm3AdObqQqq%2Fimage.png?alt=media&amp;token=3ae12c19-c76c-4d36-b45c-65065f9946e7" alt=""><figcaption><p>1 click access browser-based shell</p></figcaption></figure>

#### SSM trouble shooting

```bash
# check system agent is enabled?
sudo systemctl status amazon-ssm-agent

# when creating EC2 instance, you should configure the IAM profile to use SSM. 
# if not, after attaching the IAM profile, you need to restart the SSM agent
sudo systemctl restart amazon-ssm-agent
```

#### Session manager URL

<pre><code><strong>https://us-east-1.console.aws.amazon.com/systems-manager/session-manager/i-08d8812972af11492
</strong></code></pre>

### EC2 instance connect

* Using IAM policies to control SSH access.
* No need of SSH Keys, but actually using SSH access to your instance.

### SSH to EC2

```bash
ssh -i MyKeyPair.pem ec2-user@Public-ipaddress
```

***

## Features

### ASG: Auto Scaling Group

* Ensure that you have correct number of EC2 instances available to handle the load on your application.
* Automatically instance *<mark style="color:red;">replacement</mark>*\
  -> If the health check fail, it will trigger the lauching of new healthy instance.
* Instance *<mark style="color:red;">rebalancing</mark>* \
  -> When an AZ failed, it will shift the instances from that failed AZ to the remaining healthy AZ.

<figure><img src="https://2259236002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fuh9xZDZ53qGqmMCM44PU%2Fuploads%2FBIooEXnEJL09DdnxbwLy%2Fimage.png?alt=media&amp;token=c9b19a6b-8640-4c92-acf9-f42733d33a67" alt="" width="375"><figcaption><p>instance rebalance</p></figcaption></figure>

* Provision new resources take minutes. Slow if compare to Lambda scaling ability.

### EC2 Hibernate

* Hibernation saves the contents from the instance memory (RAM) to your [EBS](/aws/services/compute/ec2/ebs.md) root volume.
* Allows applications to pick up ***exactly where they left off***.
* Use cases
  * *<mark style="color:red;">Services that take time to initialize</mark>*
  * Saving RAM state
  * Long-running processing
  * eg: 2-weeks company shutdown
* To use hibernate
  * Root volume: *<mark style="color:red;">must be encrypted EBS volume</mark>*.
  * AMI: Linux or Windows
  * RAM size: must less than 150GB.
  * *<mark style="color:red;">NOT hibernated > 60 days.</mark>*&#x20;

-> It is not possible to enable or disable hibernation for an instance after it has been launched.

### Placement group

There are 3 types of Placement group

<table><thead><tr><th>Cluster</th><th width="220.33333333333331">Partition</th><th>Spread</th></tr></thead><tbody><tr><td>high-performance<br><em><mark style="color:red;"><strong>low-latency</strong></mark></em></td><td>large distributed, replicated workloads</td><td><em><mark style="color:red;"><strong>high-availability</strong></mark></em><br>reduce failures</td></tr><tr><td>placing EC2 instnaces next to each other</td><td>Hadoop, Cassandra, Kafka</td><td>placing EC2 instances in different hardware cross-AZs.</td></tr></tbody></table>

***

### Detailed monitoring

Send metric to Cloud Watch every 1-minute (instead of 5-minute period).

## Troubleshooting

* Check **inbound** of **Security group** if it already allow the right protocol/port.
* Check **NACLs** associated with the subnets, to ensure they allow inbound and outbound traffic.
* ALB listener if the traffic is being directed to the correct `protocol:port` of the Target Group
* Check if the Target group includes the EC2 instances as registered targets.
* EC2 instance:
  * Check health status, and `Status check` 2/2?
  * Connect to the EC2 instance to check if the httpd server is running.
* Check logs
  * Check EC2 instance's system logs.
  * `CloudWatch` log: CPU, network traffic, disk I/O...
  * `CloudTrail` log.

## Trivia

* Termination protection will not prevent an Autoscaling Group from terminating instances, instance scale-in protection will. Termination protection protect from *<mark style="color:red;">manually termination</mark>*.
* `DefaultInstanceWarmup` : determines how long your instances need to finish initializing to be `InService` state.
* The only way to retrieve *<mark style="color:red;">instance metadata</mark>* is to use the link-local address, which is `169.254.169.254`.
* When you stop an instance, AWS may move the virtualized EC2 instance to another host computer; the instance may get a new public IP address, and the data in your attached instance store volumes will be deleted.
* When you provision an IAM to use with SSM, refer [pre-installed ssm agent AMI list](https://docs.aws.amazon.com/systems-manager/latest/userguide/ami-preinstalled-agent.html).
* You can combine Spot + On-Demand instance only. You ***cannot*** combine Spot and Reserved instances.
