How to create a AWS Virtual Machine (AWS EC2 Instance)

We can create virtual machines using automation. AWS provides us a way to automate creation on thousands of virtual machines using AWS API also known as AWS EC2 API.

Without doing the manual effort of always going to the AWS web console and creating a VM, we can automate it using Scripts. Using this script we can make a call to AWS EC2 API.

Ways to automate the creation of AWS EC2 instance:

We will expose the API of the AWS EC2 server. When API will receive the request, the EC2 instance is responded to. The request should be valid, authenticate and authorized. We can automate the creation of EC2 instances by following ways:

  1. AWS CLI

  2. AWS API(For ex:Boto 3)

  3. AWS CDK

  4. AWS Cloud Formation Template

  5. Terraform(Used to automate resource creation)

    By the above, we can directly contact AWS API.

How to create a Free EC2 instance from AWS Console

  1. Head over to the AWS console website. Link:https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3FhashArgs%3D%2523%26isauthcode%3Dtrue%26nc2%3Dh_ct%26src%3Dheader-signin%26state%3DhashArgsFromTB_us-east-2_686c53e9c732e9fb&client_id=arn%3Aaws%3Asignin%3A%3A%3Aconsole%2Fcanvas&forceMobileApp=0&code_challenge=y1GP9jOl4IbzZYhG-ZyDjyAfKul3m4mROYY50zs_1NU&code_challenge_method=SHA-256

  2. Create a new Account or Sign in to existing account.

  3. Search for EC2 service. Click on instances and Click on Launch Instance

  4. Name the Server for ex: test.

  5. Click on Ubunutu OS.

  6. Choose free tier eligible .

  7. Now click on Create a new Key Pair. This allows us to login to EC2 instance. This is used like a password to login into EC2 instance.

  8. Name it anything for ex: test111 . Keep Key-Pair type as RSA and Private key File format as .pem for time being.

  9. Keep everything as it is and scroll down till end and click on Launch Instance.

  10. Congrats your EC2 instance is created . This will take a couple of minutes to setup and after some time it will show running state.

Creating EC2 instance using Automation(Scripting)

-How to login into EC2 instance

Through AWS console:

  1. Login into AWS account .

  2. You will find the running instance under instances. Click on it and click on Connect-> Connect .

Through Terminal:

  1. Install a command line Terminal . For Windows

    https://www.putty.org/

    https://mobaxterm.mobatek.net/download-home-edition.html

  2. Navigate to EC2 -> Instances

  3. Copy public IP Address

  4. Now in terminal we need to login with Key-Value pair that we downloaded. But here pem file permissions are too open. We need to keep the permissions closed because if we are using a shared virtual machine then anyone can access your pem file so we keep the permission closed.

  5. Run below commands

  6.      chmod 600 C:/Users/vijay/Downloads
        ssh -i C:/Users/vijay/Downloads/<Name_of_Pem_File_Downloaded>.pem ubuntu@<public_ip_Address>
    
  7. We will be successfully logged into AWS Instance.

Automate the creation of EC2 Instance

Using AWS Command Line Interface:

  1. You can download AWS CLI from here according to your OS:https://aws.amazon.com/cli/

Install it and to see if it is installed run the command:

aws version

-> Output
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

aws: error: argument command: Invalid choice, valid choices are:

accessanalyzer                           | account
acm                                      | acm-pca
alexaforbusiness                         | amp
amplify                                  | amplifybackend
amplifyuibuilder                         | apigateway
apigatewaymanagementapi                  | apigatewayv2
appconfig                                | appconfigdata
appflow                                  | appintegrations
application-autoscaling                  | application-insights
applicationcostprofiler                  | appmesh
apprunner                                | appstream
appsync                                  | arc-zonal-shift
athena                                   | auditmanager
autoscaling                              | autoscaling-plans
backup                                   | backup-gateway
backupstorage                            | batch
billingconductor                         | braket
budgets                                  | ce
chime                                    | chime-sdk-identity
chime-sdk-media-pipelines                | chime-sdk-meetings
chime-sdk-messaging                      | chime-sdk-voice
cleanrooms                               | cloud9
cloudcontrol                             | clouddirectory
cloudformation                           | cloudfront
cloudhsm                                 | cloudhsmv2
cloudsearch                              | cloudsearchdomain
cloudtrail                               | cloudtrail-data
cloudwatch                               | codeartifact
codebuild                                | codecatalyst
codecommit                               | codeguru-reviewer
codeguruprofiler                         | codepipeline
codestar                                 | codestar-connections
codestar-notifications                   | cognito-identity
cognito-idp                              | cognito-sync
comprehend                               | comprehendmedical
compute-optimizer                        | connect
connect-contact-lens                     | connectcampaigns
connectcases                             | connectparticipant
controltower                             | cur
customer-profiles                        | databrew
dataexchange                             | datapipeline
datasync                                 | dax
detective                                | devicefarm
devops-guru                              | directconnect
discovery                                | dlm
dms                                      | docdb
docdb-elastic                            | drs
ds                                       | dynamodb
dynamodbstreams                          | ebs
ec2                                      | ec2-instance-connect
ecr                                      | ecr-public
ecs                                      | efs
eks                                      | elastic-inference
elasticache                              | elasticbeanstalk
elastictranscoder                        | elb
elbv2                                    | emr
emr-containers                           | emr-serverless
es                                       | events
evidently                                | finspace
finspace-data                            | firehose
fis                                      | fms
forecast                                 | forecastquery
frauddetector                            | fsx
gamelift                                 | gamesparks
glacier                                  | globalaccelerator
glue                                     | grafana
greengrass                               | greengrassv2
groundstation                            | guardduty
health                                   | healthlake
honeycode                                | iam
identitystore                            | imagebuilder
importexport                             | inspector
inspector2                               | internetmonitor
iot                                      | iot-data
iot-jobs-data                            | iot-roborunner
iot1click-devices                        | iot1click-projects
iotanalytics                             | iotdeviceadvisor
iotevents                                | iotevents-data
iotfleethub                              | iotfleetwise
iotsecuretunneling                       | iotsitewise
iotthingsgraph                           | iottwinmaker
iotwireless                              | ivs
ivs-realtime                             | ivschat
kafka                                    | kafkaconnect
kendra                                   | kendra-ranking
keyspaces                                | kinesis
kinesis-video-archived-media             | kinesis-video-media
kinesis-video-signaling                  | kinesis-video-webrtc-storage
kinesisanalytics                         | kinesisanalyticsv2
kinesisvideo                             | kms
lakeformation                            | lambda
lex-models                               | lex-runtime
lexv2-models                             | lexv2-runtime
license-manager                          | license-manager-linux-subscriptions
license-manager-user-subscriptions       | lightsail
location                                 | logs
lookoutequipment                         | lookoutmetrics
lookoutvision                            | m2
machinelearning                          | macie
macie2                                   | managedblockchain
marketplace-catalog                      | marketplace-entitlement
marketplacecommerceanalytics             | mediaconnect
mediaconvert                             | medialive
mediapackage                             | mediapackage-vod
mediastore                               | mediastore-data
mediatailor                              | memorydb
meteringmarketplace                      | mgh
mgn                                      | migration-hub-refactor-spaces
migrationhub-config                      | migrationhuborchestrator
migrationhubstrategy                     | mobile
mq                                       | mturk
mwaa                                     | neptune
network-firewall                         | networkmanager
nimble                                   | oam
omics                                    | opensearch
opensearchserverless                     | opsworks
opsworkscm                               | organizations
osis                                     | outposts
panorama                                 | personalize
personalize-events                       | personalize-runtime
pi                                       | pinpoint
pinpoint-email                           | pinpoint-sms-voice
pinpoint-sms-voice-v2                    | pipes
polly                                    | pricing
privatenetworks                          | proton
qldb                                     | qldb-session
quicksight                               | ram
rbin                                     | rds
rds-data                                 | redshift
redshift-data                            | redshift-serverless
rekognition                              | resiliencehub
resource-explorer-2                      | resource-groups
resourcegroupstaggingapi                 | robomaker
rolesanywhere                            | route53
route53-recovery-cluster                 | route53-recovery-control-config
route53-recovery-readiness               | route53domains
route53resolver                          | rum
s3control                                | s3outposts
sagemaker                                | sagemaker-a2i-runtime
sagemaker-edge                           | sagemaker-featurestore-runtime
sagemaker-geospatial                     | sagemaker-metrics
sagemaker-runtime                        | savingsplans
scheduler                                | schemas
sdb                                      | secretsmanager
securityhub                              | securitylake
serverlessrepo                           | service-quotas
servicecatalog                           | servicecatalog-appregistry
servicediscovery                         | ses
sesv2                                    | shield
signer                                   | simspaceweaver
sms                                      | snow-device-management
snowball                                 | sns
sqs                                      | ssm
ssm-contacts                             | ssm-incidents
ssm-sap                                  | sso
sso-admin                                | sso-oidc
stepfunctions                            | storagegateway
sts                                      | support
support-app                              | swf
synthetics                               | textract
timestream-query                         | timestream-write
tnb                                      | transcribe
transfer                                 | translate
voice-id                                 | vpc-lattice
waf                                      | waf-regional
wafv2                                    | wellarchitected
wisdom                                   | workdocs
worklink                                 | workmail
workmailmessageflow                      | workspaces
workspaces-web                           | xray
s3api                                    | s3
ddb                                      | configure
deploy                                   | configservice
opsworks-cm                              | history
cli-dev                                  | help
  1. If we get above output it means we have successfully installed

  2. Navigate to Profile -> Security Credentials. Scroll Down to Access key -> Create access key.

  3. Copy the Access key and run below on command line

  4.     aws configure
    
  5. Then it will ask for Access Key ID , Secret Access Key. We get this when we create the access key in Step 2

  6. Keep Default Region, Default Format and we will be able to access AWS services through CLI.

  7. From here we can create EC2 Instance