Friday, April 25, 2025

Different Ways to Create EC2 Instances | Deep Dive & Hands-On.

A deep dive into the different Ways to Creates EC2 Instances.

Focus:

  • Tailored for Devops, DevSecops & Cloud Engineers.

Breakdown:

  • Intro,
  • Several different ways to create Amazon EC2 instances,
  • AWS Management Console (UI),
  • AWS CLI (Command Line Interface),
  • AWS SDKs (Boto3 for Python, AWS SDK for JavaScript, etc.),
  • Infrastructure as Code (IaC) Tools,
  • AWS CloudFormation (stack)
  • Terraform (by HashiCorp),
  • Automated & Advanced Methods,
  • Projects: Hands-On(s)

Intro:

  • There are several ways to create EC2 instances in AWS, ranging from:  manual creation from the console (sometimes bootstrapping packages)  to fully automated methods.
  •  Several different ways to create Amazon EC2 instances:
AWS Management Console:
  •  A web-based graphical interface that is typically used for getting started quickly and for manual, interactive creation of instances.
AWS CLI (Command Line Interface):
  •  A unified tool to manage AWS services, allowing users to script and automate instance creation using commands like aws ec2 run-instances.
AWS SDKs (Software Development Kits):
  •  Language-specific APIs (e.g., Python, Java, Node.js) that allow developers to integrate instance creation and management capabilities directly into their applications.
AWS CloudFormation:
  •  A service that helps model and set up AWS resources using templates, allowing users to define their entire infrastructure as code.
AWS CDK (Cloud Development Kit):
  •  An open-source software development framework to define cloud application resources using familiar programming languages.
Terraform by HashiCorp:
  •  A popular third-party Infrastructure as Code (IaC) tool that allows defining and provisioning AWS infrastructure using HashiCorp Configuration Language (HCL).
AWS OpsWorks:
  •  A service that uses Chef and Puppet to automate operational tasks, including provisioning EC2 instances.
  • Each method offers different levels of automation, control, and integration depending on the user's requirements.

Here is twtech most common use-cases and step-by-step creation (Hands-on)

 Manual Methods

  1. AWS Management Console (UI)
    • Easiest way for beginners.
    • Step-by-step wizard to configure AMI, instance type, key pair, storage, network, security group, etc.
  2. AWS CLI (Command Line Interface)
    • Useful for scripting or quick instance launches.
    • Example:

#   bash 

aws ec2 run-instances --image-id ami-1234567xxxxx  --count 1 --instance-type t2.micro --key-name twtechKeyPair --security-groups twtech-SecurityGroup

 

Or:

 

#  bash

 

aws ec2 run-instances \

  --image-id ami-1234567xxxxx \

  --count 1 \

  --instance-type t2.micro \

  --key-name twtechKeyPair \

  --security-groups twtech-SecurityGroup

  1. AWS SDKs (Boto3 for Python, AWS SDK for JavaScript, etc.)
    • Great for integrating instance creation into twtech applications or backend services.
    • Python (Boto3) example:

#  python

 

import boto3

ec2 = boto3.resource('ec2')

ec2.create_instances(ImageId='ami-12345678xxx', MinCount=1, MaxCount=1, InstanceType='t2.micro')

Infrastructure as Code (IaC) Tools

  1. AWS CloudFormation (stack)
    • Declarative IaC tool.
    • Define instances and other resources in YAML or JSON.
    • Example snippet:

#  yaml 

Resources:

  MyEC2Instance:

    Type: AWS::EC2::Instance

    Properties:

      InstanceType: t2.micro

      ImageId: ami-12345678xxx

      KeyName: twtechKeyPair

  1. Terraform (by HashiCorp)
    • Popular cross-cloud IaC tool.

# Sample twtech-refactored terraform codes.

# twtech-resources.tf

resource "aws_instance" "twtech" {

  ami             = var.ami

  instance_type   = var.instance

  key_name        = var.key

  user_data       = file("${path.module}/userdata.sh")

  count           = 1

  subnet_id       = var.subnet

  security_groups = ["sg-00215f09ece4xxxx"]

  tags = {

    Name = "twtech-sonar-maven-server"

    env  = var.namespace

  }

  root_block_device {

    volume_size = 20    # Size of the root volume in GB

  }

}

# twtech variables.tf

variable "instance" {

  type    = string

  default = "t2.medium"

}

variable "key" {

  type    = string

  default = "twtech-KeyPair"

}

variable "namespace" {

  type    = string

  default = "dev"

}

variable "subnet" {

  type    = string

  default = "subnet-0c2261460dbxxxxxx"

}

variable "ami" {

  type    = string

  default = "ami-0720ac433axxxxx"

}

# providers.tf

terraform {

  required_version = "~> 1.0"

  required_providers {

    aws = {

      source  = "hashicorp/aws"

      version = "~> 5.0"

    }

  }

}

# twtech-sonar-maven-userdata

Link to the userdata-script:

https://github.com/Devopspat35/Package-management/blob/master/twtech-sonarqube.sh

  1. Pulumi
    • IaC using general-purpose programming languages (Python, Go, JavaScript, etc.).
    • Similar to Terraform but more code-centric.

 Automated & Advanced Methods

  1. AWS EC2 Auto Scaling Groups
    • Automatically launch EC2 instances based on demand or schedules.
    • Useful for horizontal scaling and fault tolerance.
  2. Elastic Beanstalk
    • PaaS abstraction; handles EC2 instance creation automatically as part of environment setup.
  3. AWS OpsWorks
    • Uses Chef/Puppet to manage EC2 instances.
    • Useful if you're in a configuration management-heavy environment.
  4. EC2 Image Builder
  • Automates creation of golden AMIs and can include EC2 launch steps.
  1. AWS CDK (Cloud Development Kit)
  • Infrastructure defined using familiar programming languages (TypeScript, Python, etc.).
  • Example in Python:

#  python

from aws_cdk import aws_ec2 as ec2

instance = ec2.Instance(self, "twtech-Instance",

  instance_type=ec2.InstanceType("t2.micro"),

  machine_image=ec2.MachineImage.latest_amazon_linux()

)

 

Project: Hands-On

Method ONE

Bootstrapping Packages while Provisioning instance for Sonarqube :

  1. AWS Management Console (UI)
    • Easiest way for beginners.
    • Step-by-step wizard to configure AMI, instance type, key pair, storage, network, security group, etc.
    • twtech sometime Bootstraps the needed dependencies, packages and applications while provisioning the instance.

twtech-web-server creation: GUI

  • Dependencies:
  •  t2.medium and above,
  • openjdk-11 (java-11)
step-1:
  • Search for ec2 from among aws services:


  • twtech Launchs instance from console: UI

step-2:

  • twtech Configures the variables and resources for before launching the instances:

  • Select the Amazon Machine Image


  • For the purpose of this project, twtech is using:  t2.medium

  • Key pair for login can be selected from: dropdown menu or created.

  • Network settings: for security reason, twtech open traffic to only the needed ports.

  • Configure storage: The root-volume starts from 8Gigabytes
  • Volume can not be decreased once created, but twtech can increase up to 30G which is the maximum free tier eligible size.

 From:

To:

  • Advanced details:  To bootstrap package or Userdata:

  •  Sonarqube installation script path (metadata or user-data)

https://github.com/Devopspat35/Package-management/blob/master/twtech-sonarqube.sh


step-3:
  • twtech may have the script written, copied and pasted or uploaded


  • launch the instance:

step-4:

  • It takes a couple of minutes for packages to be fully bootstrapped on the instance.
  • Refresh page:

step-5:

  • Connect to the instance to verify that the needed configurations, and resources were successfully provisioned (bootstrapped)
  • Using ssh client ( VSCode, mobaxterm, putty, intelliJ idea …etc ), ssh into the sever
  • For this Project, twtech is using VSCode from gitbash terminal
  • Navigate to location of the key.pem( twtechKeyPai) create

cd ~/Downloads

  • Connect to the instance: twtech-sonarqube-server
  • with ssh-client:

ssh -i "twtech-KeyPair.pem" ec2-user@ec2-3-148-xxx-187.us-east-2.compute.amazonaws.com

step-6:

  • Successfully, twtech has bootstrapped sonarqube in a redhat instance with all the needed dependencies, assigne it the nee permissions, initialize the server, started the services and switched to sonar-usrer
  • # switch to sonar user

 sudo su - sonar

step-7:

  • # verify that sonar have ownership of sonarqube home directory

ls -al /opt/sonarqube


Step-8:

  • #  How twtech starts sonarQube server

 sh /opt/sonarqube/bin/linux-x86-64/sonar.sh start

  • Step-9:
  • # twtech verifies the sonarqube server status.

  sh /opt/sonarqube/bin/linux-x86-64/sonar.sh status

  • Step-10:
  • #  twtech Accesses twtech-sonarqube-server: Access sonarqube on the browser

curl ifconfig.me                # To get host server pubIPaddress.

Step-11:
  • twtech accesses Sanarqube on the browser and login.

# twtech-serverPubIP:9000

18.191.xxx.2:9000

# Default USERNAME: admin

# Default password: admin


Step-11:
  • Once login as admin, other twech-users are created and passwords assigned.


  •  twtech-admin-user creates other sonar-users.



Step-11:

  • Logout as admin user

Step-11

  • Login  as twtech-patpat created by admin: To verify that the account works and also verify the permission attached to the user created by the admin (Security purpose)

  • twtech-patpat (new user create by admin) can not create other sonar user, because of readonly access. 
  • There is:Permission denial.


  • twtech Successfully created sonar user  (twtech-patpat) and used credentials to login

Project: Hands-On

Method Two

  • The Provisioning of EC2 instance (twtech-webserver) with a Command line.
  • twtech can use the Ubuntu (subsystem for window), Powershell, gitbash or Command prompt.
Step-1:
  • Terminal should be configured with aws-access-key to allow it make API calls to AWS


Step-2:
  • twtech makes sure the appropriate  Amazon Machine Image (ami) is referenced:

Step-3:

  • twtech Assig the a Security Group from the list of existing Security group with: Security-groupID 


Step-4:
  • twtech provision from a configured script or as a command from CLI


#!/bin/bash

 

aws ec2 run-instances --image-id ami-1234567xxxxx  --count 1 --instance-type t2.micro --key-name twtech-KeyPair –security­-groups-ids sg-0cfb2xxxxxxx --subnet-id subnet-6e7xxx --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=twtech-webserver}]'

 

or:

 

aws ec2 run-instances --image-id ami-1234567xxxxx  --count 1 --instance-type t2.micro --key-name twtech-KeyPair –security­-groups-ids sg-0cfb2xxxxxxx --subnet-id subnet-6e7f82xxx --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=twtech-db-server}]'

twtech Explanation of Parameters:

  • --image-id: AMI ID to launch (choose one from your region).
  • --count: Number of instances to launch.
  • --instance-type: EC2 instance type (e.g., t2.micro for free tier).
  • --key-name: Name of the existing EC2 key pair for SSH access.
  • --security-group-ids: Security group IDs to attach.
  • --subnet-id: Subnet within your VPC.
  • --tag-specifications: Optional tags to label the instance.


Step-5:

  • twtech Verifies on console to make sure the instance is provisioned using command line: GUI



twtech-insights:

  • Make sure twtech AWS CLI is configured (aws configure) with appropriate credentials and region referenced.


Project: Hands-On

Method Three   

  • How twtech use Using Infrastructure as Code (IaC) to provision EC2 instances with Associated resources.

Terraform (by HashiCorp)

  • twtech uses tarraform (.tf) files to reference: resources, variables, & provider values.
  • The userdata (if needed for bootstrap) is in the .sh format and the path to this userdate must be referenced
Step-1:

 twtech refactors terraform codes

# twtech-resources.tf

resource "aws_instance" "twtech" {

  ami             = var.ami

  instance_type   = var.instance

  key_name        = var.key

  user_data       = file("${path.module}/userdata.sh")

  count           = 1

  subnet_id       = var.subnet

  security_groups = ["sg-00215f09ece4xxxx"]

  tags = {

    Name = "twtech-sonar-maven-server"

    env  = var.namespace

  }

  root_block_device {

    volume_size = 20 # Size of the root volume in GB

  }

}

# twtech-variables.tf

variable "instance" {

  type    = string

  default = "t2.medium"

}

variable "key" {

  type    = string

  default = "twtech-KeyPair"

}

variable "namespace" {

  type    = string

  default = "dev"

}

variable "subnet" {

  type    = string

  default = "subnet-0c2261460dbxxxxxx"

}

variable "ami" {

  type    = string

  default = "ami-0720ac433axxxxx"

}

# providers.tf

terraform {

  required_version = "~> 1.0"

  required_providers {

    aws = {

      source  = "hashicorp/aws"

      version = "~> 5.0"

    }

  }

}

Step-2:

  • twtech configure the userdata
# twtech-sonar-maven-userdata

Link to the userdata-script: to bootstrap

https://github.com/Devopspat35/Package-management/blob/master/twtech-sonarqube.sh


Step-3:
  •  twtech verify that instance is provisioned seamlessly 
Step-4:
  • connects to the instance (sonar-maven-server)

ssh -i "devsecopspat.pem" ec2-user@ec2-128-221-xxx-20.us-east-2.compute.amazonaws.com


Step-5:
  • twtech verifies that all the dependecies , and applications are bootstrapped. 
  •  verify installed packages
 java -version


 mvn --version


 npm --version


 Step-6:
  • switch to sonar user
 sudo su - sonar

 
Step-7:
  • twtech verifies that the home directory of sonar is owned by sonar user.
  • twtech waits about 3 minutes for packages and directories to be fully provisioned in the server.
  • Liste the content of Sonarqube directory.
ls -al /opt/sonarqube

Step-8:
  • How twtech starts and verify the status of the sonar-maven-server.
 sh /opt/sonarqube/bin/linux-x86-64/sonar.sh start 

 
sh /opt/sonarqube/bin/linux-x86-64/sonar.sh status


Step-9:
  •  twtech Gets the host pubIPaddress with command line:
curl ifconfig.me

  • twtech Accesses the sonar-maven-server application logs: CLI
curl -v 3.142.xxx.237:9000

Step-9:
  •  twtech accesses sonarqube serve on the browser.

#  PubIP:9000
142.xxx.237:9000
Step-10:
  • twtech Login to sonarqube application as: admin
The default USERNAME: admin
The default password: admin

Step-11:
  • twtech-admin can successfully start creating: projects, user, passwords and threshold (standard or quality gate) , and  much more.

Step-12:
  •  twtech-admin-user creates other sonar-users.




Step-13:

  • Sign out as admin user

Step-13:

Sign as twtech-patpat (new user created): to verify the permissions.

Step-14:

  • Permissions reveal the  new user created from console (twtech-patpat)  can not create other sonar user.


Step-15:

  • With Terrraform as a code, twtech has also Successfully created sonar-user  (twtech-patpat), granted just the needed persmission, and used the credential generated to login seamlessly

No comments:

Post a Comment

Amazon EventBridge | Overview.

Amazon EventBridge - Overview. Scope: Intro, Core Concepts, Key Benefits, Link to official documentation, Insights. Intro: Amazon EventBridg...