Amazon Web Services is a fan-favorite among web developers because AWS offers an excellent suite of solutions and services that can be tailored to fit the needs of any business or organization. AWS solutions are known for their efficiency, easy management, and robust security features.
One of the most popular AWS solutions is EC2 - the Amazon Elastic Compute Cloud is a cloud service that allows businesses to run applications on the public cloud. As for EC2 instances, these are virtual servers that let you run applications without having to worry about infrastructure.
What is an EC2 Instance in AWS?
In the AWS cloud solution ecosystem, an EC2 instance is a virtual server that offers you the basic infrastructure, like RAM, storage, and processing power to run your applications on the AWS ecosystem. EC2 instances are different from standard virtual machines. This is because AWS offers several unique properties that make EC2 instances a great option for businesses.
- EC2 offers auto-scaling - this feature helps businesses automatically manage their computing capacity based on their requirements.
- AWS EC2 instances are pay-as-you-go - there is no minimum fee to be paid upfront for provisioning capacity in AWS.
- EC2 instances pair up with other AWS services, such as Elastic Block Storage and Simple Storage Service, to offer better durability and storage facilities.
Types of EC2 Instances in AWS
Amazon has five categories of EC2 for a variety of uses. We will see the categories in brief here:
General Purpose Instances
The general-purpose instances are mainly for providing CPU, RAM, storage, and networking resources so that the workload can be balanced. These instances are used for applications, gaming servers, and databases.
Compute-Optimized Instances
Compute-optimized instances are more suited for high-performance processing workloads. These instances are ideal for high-traffic web servers and servers that require batch processing.
Memory-Optimized Instances
As the name suggests, these instances deal with large loads of datasets. When a server as an application requires the processing of big data, these instances come in handy.
Storage-Optimized Instances
When you have large datasets on local storage and need I/O operations, you can opt for storage-optimized instances. They allow rapid access to local storage data.
Accelerated Computing Instances
Specific tasks that require hardware accelerators, such as graphic processing, are done with the help of accelerated computing instances.
How to Create an Instance in AWS - Step-by-Step Explanation
First of all, to create an EC2 instance, you will need an AWS account. You can set up a free-tier account to continue with the next step. The next steps are briefed below:
Step 1: In your AWS management console, click services. This week I'll be present on the left of the screen. In the drop-down menu that appears, click EC2. You can create an instance from here by picking the Launch Instance button.
Step 2: You will be taken to a different launch page once you click the button. Here, you can pick the settings and requirements for the instance and create it accordingly.
Step 3: Next, you have to select an Amazon Machine Image. This is the required OS for your requirement - AWS offers options including Linus, macOS, Ubuntu, Windows, etc.
![choose os](https://devopsimages.in/uploads/aws_tep_4_3925700139.png)
Step 4: If you are eligible for the free tier, AWS selects a default storage tier. The instance type options refer to the no. of CPUs and memory required for your application. By default, the available free-tier instance type is t2.micro - selecting other instances will lead to a billing amount, so do not opt for any other.
Step 5: In the main instance setup page, fill in the boxes with corresponding values. You will have to fill in the number of instances, purchasing option, tenancy, network, subnet, shutdown behavior, monitoring, user data, and more fields.
Step 6: Now click you have to create a key pair from the pop-up window. Click Create new key pair - this value pair will be crucial in connecting the instance as it will act as an SSH key. Create the pair by entering the name, and then selecting “.pem”. The pair that is created will download automatically. Select the created key pair.
![configure storage](https://devopsimages.in/uploads/step_6_aws_309dd61040.png)
Step 7: Now keep the network settings in default and select Launch Instance. Make sure that all your options are corresponding to free-tier instances.
Note: If you have any confusion then go through this video
How to Create an Instance in AWS By CLI
Step 1: Make sure that AWS CLI is downloaded and configured in your system
Step 2: Choose an Amazon Machine Image
aws ec2 describe-images --filters "Name=name,Values=amzn2-ami-hvm-2.0.*-x86_64-gp2" --query "Images[*].{ID:ImageId,Name:Name}" --output table
Step 3: Create a Key Pair
aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
chmod 400 MyKeyPair.pem
Step 4: Launch the EC2 Instance
aws ec2 run-instances --image-id ami-0abcdef1234567890 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-0123456789abcdef0 --subnet-id subnet-0bb1c79de3EXAMPLE
Example Command
aws ec2 run-instances --image-id ami-12345678 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-98765432 --subnet-id subnet-1234abcd
How to Create an EC2 Instance Using Terraform
Prerequisites
- Terraform installed on your local machine
- AWS CLI configured with required IAM permissions
- A basic understanding of Terraform and AWS EC2
Step 1: Install Terraform
you can download it from the Terraform website and follow the installation instructions
Step 2: Set Up Your Working Directory
mkdir terraform-ec2
cd terraform-ec2
Step 3: Create a Terraform Configuration File
touch main.tf
Step 4: Define the Provider
provider "aws" {
region = "us-east-1" # Replace with your desired region
}
Step 5: Define the EC2 Instance
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0" # Replace with your desired AMI ID
instance_type = "t2.micro" # Choose your instance type
tags = {
Name = "example-instance"
}
}
Step 6: Initialize Terraform
terraform init
Step 7: Plan the Deployment
terraform plan
Step 8: Apply the Configuration
terraform apply
Step 9: Verify the Instance
Example main.tf
File
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "example-instance"
}
}
How to create an EC2 Instance Using AWS CloudFormation
Step 1: Create the CloudFormation Template
#Create ec2-instance.yml
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template to create an EC2 instance
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: must be the name of an existing EC2 KeyPair.
InstanceType:
Description: EC2 instance type
Type: String
Default: t2.micro
AllowedValues:
- t2.micro
- t2.small
- t2.medium
ConstraintDescription: must be a valid EC2 instance type.
AmiId:
Description: AMI ID for the EC2 instance
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
ImageId: !Ref AmiId
SecurityGroups:
- !Ref InstanceSecurityGroup
InstanceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: 0.0.0.0/0
Outputs:
InstanceId:
Description: The Instance ID of the created EC2 instance
Value: !Ref EC2Instance
PublicIp:
Description: The public IP address of the created EC2 instance
Value: !GetAtt
- EC2Instance
- PublicIp
Step 2: Deploy the CloudFormation Stack
- Login to AWS Console
- Navigate to the CloudFormation Dashboard
- Create a New Stack
- Upload the Template:
- Specify Stack Details
- Configure Stack Options
- Review and Create
Step 3: Monitor the Stack Creation
Step 4: Verify the EC2 Instance
ssh -i /path/to/your-key.pem ec2-user@<PublicIp>
Example ec2-instance.yml
File
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template to create an EC2 instance
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: must be the name of an existing EC2 KeyPair.
InstanceType:
Description: EC2 instance type
Type: String
Default: t2.micro
AllowedValues:
- t2.micro
- t2.small
- t2.medium
ConstraintDescription: must be a valid EC2 instance type.
AmiId:
Description: AMI ID for the EC2 instance
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
ImageId: !Ref AmiId
SecurityGroups:
- !Ref InstanceSecurityGroup
InstanceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: 0.0.0.0/0
Outputs:
InstanceId:
Description: The Instance ID of the created EC2 instance
Value: !Ref EC2Instance
PublicIp:
Description: The public IP address of the created EC2 instance
Value: !GetAtt
- EC2Instance
- PublicIp
How to create an EC2 Instance Using AWS SDK for Python
Prerequisites
- Python installed on your machine
- AWS CLI configured with required IAM permissions
- Boto3 installed (
pip install boto3
)
Step 1: Install Boto3
pip install boto3
Step 2: Configure AWS Credentials
aws configure
Step 3: Write the Python Script
import boto3
# Initialize a session using Amazon EC2
session = boto3.Session(
aws_access_key_id='YOUR_ACCESS_KEY',
aws_secret_access_key='YOUR_SECRET_KEY',
region_name='us-east-1'
)
# Initialize EC2 resource
ec2 = session.resource('ec2')
# Create a new EC2 instance
instances = ec2.create_instances(
ImageId='ami-0c55b159cbfafe1f0', # Replace with your desired AMI ID
MinCount=1,
MaxCount=1,
InstanceType='t2.micro', # Choose your instance type
KeyName='MyKeyPair', # Replace with your key pair name
SecurityGroupIds=['sg-903004f8'], # Replace with your security group ID
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': 'MyInstance'
}
]
}
]
)
print("New instance created:", instances[0].id)
Step 4: Run the Script
python create_ec2_instance.py
Step 5: Verify the EC2 Instance
aws ec2 describe-instances --instance-ids i-xxxxxxxxxxxxxxxxx
How to create an EC2 Instance using AWS CDK (Cloud Development Kit)
Prerequisites
- Node.js and npm installed
- AWS CLI configured with required IAM permissions
- AWS CDK installed (
npm install -g aws-cdk
)
Step 1: Install AWS CDK
npm install -g aws-cdk
Step 2: Create a New CDK Project
mkdir my-cdk-app
cd my-cdk-app
cdk init app --language typescript
Step 3: Install the AWS EC2 Module
npm install @aws-cdk/aws-ec2
Step 4: Define the EC2 Instance
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
export class MyCdkAppStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create a VPC (Virtual Private Cloud)
const vpc = new ec2.Vpc(this, 'MyVpc', {
maxAzs: 3 // Default is all AZs in region
});
// Create a security group
const securityGroup = new ec2.SecurityGroup(this, 'MySecurityGroup', {
vpc,
description: 'Allow ssh access to ec2 instances',
allowAllOutbound: true // Can be set to false
});
securityGroup.addIngressRule(
ec2.Peer.anyIpv4(),
ec2.Port.tcp(22),
'allow ssh access from the world'
);
// Create an EC2 instance
const instance = new ec2.Instance(this, 'MyInstance', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: new ec2.AmazonLinuxImage(), // AMI
securityGroup,
keyName: 'MyKeyPair' // Replace with your key pair name
});
new cdk.CfnOutput(this, 'InstancePublicIp', {
value: instance.instancePublicIp,
description: 'The public IP of the instance',
});
}
}
Step 5: Deploy the Stack
npm run build
cdk deploy
Step 6: Verify the EC2 Instance
Why Opt for AWS EC2 Instances?
AWS EC2 and AWS solutions, in general, are preferred over other cloud solutions because of their strong security and management efficiency. Here are some benefits of EC2 instances that can be a benefit to your business:
Flexibility
AWS offers you different types of instances that will come in handy for clients with varying requirements from a virtual server. For example, small-scale applications can work with general instances, whereas high-performance gaming servers might need compute-optimized instances.
Security
Amazon works on a Virtual Private Cloud (VPC). This provides a secure network for the resources. Since the instances are located in VPC, they are set in a specific IP range. This feature keeps them safe from being exposed to any possible threats on the internet.
Comprehensive Solutions
EC2 can be paired up with a variety of other AWS solutions like S3, DynamoDB, and RDS. This way, users can access a comprehensive set of cloud solutions for all their application development needs.
Cost-saving
AWS gives its customers multiple options when it comes to the cost of the services. Compared to other cloud solutions, AWS is cheap as, for a minimal amount, one can access a wide range of resources and tools. One can also use the free-tier service to explore and learn the tools in the AWS suite - this is a great option for budding developers.
Summing it Up
AWS offers a number of cloud solutions, out of which EC2 is widely utilized by organizations across the world. An instance is a virtual server that lets you run your applications by providing the required infrastructure and storage you need. EC2 instances boast many advantages, too, as they are reliable, secure, and cost-saving.
Read More
https://devopsden.io/article/create-iam-user-in-aws
Follow us on
Table of Contents