Tuesday, 29 September 2020

AWS CLI - AuthFailure

Hello to my fellow cloud engineers. In this blog we will discuss about the solution of a common AWS issue.

ERROR: An error occurred (AuthFailure) when calling the DescribeInstances operation: AWS was not able to validate the provided access credentials

We get this error mostly because of 2 Reasons either we have provided wrong credentials while configuring CLI or the date/time is set incorrectly on the server.


Prerequisite

Setting up AWS CLI

# pip3 install awscli

# aws configure

Enter the access_key, secret_key and the region and you're done setting up aws cli on your machine.


Test the aws configuration

# aws configure list


# aws ec2 describe-instances


An error occurred (AuthFailure) when calling the DescribeInstances operation: AWS was not able to validate the provided access credentials

I kept wondering why I am getting AuthFailure message as I was able to run the CLI commands on other system with the same credentials. Later I realized that this was happening due to mismatch of system clock time and the actual TimeZone time.




# timedatectl set-timezone 'Asia/Kolkata'

Setting the timezone didn't help as the timezone was already the same but the system time was incorrectly set.

To sync the time I tried to enable the NTP (Network Time Protocol)

# timedatectl set-ntp yes

Failed to set ntp: NTP not supported.

I have to install the NTP service as it was not present in my case.

# yum install ntp

# systemctl start ntpd




# timedatectl set-ntp yes 
(This command ran successfully this time)


Able to run the aws commands through CLI successfully

# aws ec2 start-instances --instance-ids i-07ca6e35eed6c5692



This is how I was able to run AWS CLI commands after resolving the AuthFailure issue. I will be glad if this has resolved your issue too, else you can reach out to me through comments/email will be happy to help.

Friday, 17 January 2020

Touchbase with AWS CLI

Hey fellas, wishing you all Happy New Year. Today we are going to learn how to create simple scripts in AWS cli to gather important information of our deployed infrastructure.

The AWS management console is a very convenient way of gathering all this data. But when we require this information as some form of input for other reports/scripts, then AWS CLI comes into play.

AWS CLI vs SDK

AWS CLI acts like an API for communicating with the AWS services from the command line interface.
When an application needs to interact with AWS services, then we have to import AWS SDK in our code to communicate with the services.

Let's begin to extract all possible information from AWS command line interface aka CLI. By the end of this you will be accustomed with AWS CLI.

#Prerequisites

AWS CLI should be configured on your local machine with the AWS user having atleast read only permissions for the module that you are going to explore (EC2,RDS,S3)
If you are not able to run that command then you will be greeted with a message to contact your IAM administrator for granting privileges.

##Installation of AWS CLI tool

$ sudo pip install awscli

##Configuring AWS 

$ aws configure AWS Access Key ID [None]: DSLH546VSFAP AWS Secret Access Key [None]: jeoHhzr4FeEd9o6aOBicTK7kRvpJu5JRfFKFCe4yXw Default region name [None]: ap-south-1 Default output format [None]: <leave blank for default JSON format>


Required permission for accessing EC2 instances: AmazonEC2ReadOnlyAccess




Let us get our hands dirty and begin with the CLI commands to get the desired output:


Use case 1: To describe all of the EC2 instances in any of the mentioned output format.

aws ec2 describe-instances --output <table/json/text>

--output parameter: There are 3 formats in which we can get the output through CLI (table/json/text). the default output format is JSON, if we do not mention anything.


Use case 2: To describe all of the EC2 instances and filter out the information required like: InstanceId, Name, IpAddress, Public DNS address, Current State

--query parameter: Use to filter out the desired fields from the output

aws ec2 describe-instances --query "Reservations[*].Instances[*].{name: Tags[?Key=='Name'] | [0].Value, instance_id: InstanceId, ip_address: PrivateIpAddress, public_dns_name: PublicDnsName, state: State.Name}" --output table



  We can create alias if the command has to be used very frequently. Place the below lines under .bash_aliases file in the user home directory.

$ nano ~/.bash_aliases

alias aws_instances='aws ec2 describe-instances --query "Reservations[*].Instances[*].{name:Tags[?Key=='Name']|[0].Value, instance_id:InstanceId, state:State.Name, privateIP:PrivateIpAddress, AZ:Placement.AvailabilityZone, attached_vol:BlockDeviceMappings[0].Ebs.VolumeId, Security_grp:SecurityGroups[0].GroupName}" --output table'

$ source .bash_aliases





Use case 3: To describe all the mounted Volumes on all of the EC2 instances and filter out the Volume ID, Instance ID, Availability Zone, Size (GB) and Snapshot IDs

aws ec2 describe-volumes --query 'Volumes[*].[VolumeId, Attachments[0].InstanceId, AvailabilityZone, Size, SnapshotId, FakeKey]' --output text

We can attach/detach, create/delete volumes from EC2 instances. Also we can create snapshots.

Use case 4: To describe all the DB instances created under RDS and modifying their storage.

aws rds describe-db-instances --db-instance-identifier mydbinstance 


aws rds modify-db-instance \
--db-instance-identifier mydbinstance \
--allocated-storage 60 \
--apply-immediately


Use case 5: Creating an Instance from AWS CLI (for this we need EC2 admin privileges)

aws ec2 run-instances --image-id <ami-xxxxxxxx> --count 1 --instance-type t2.micro --key-name <MyKeyPair> --security-group-ids <sg-903004f8> --subnet-id <subnet-6e7f829e>
--iam-instance-profile  Name=ecsInstanceRole
--user-data file://bootstrap.txt (name of the file that has the bootstrap commands)


Overall I have looked into many basic commands under different modules EC2, RDS, S3 and ELB. The AWS CLI is a very deep and vast topic to cover on a blog.
We can control almost every service hosted on AWS through this powerful tool. Hope this blog has given you some motivation to take a deeper dive into the advance usage of AWS CLI.
See you folks on my next blog, till then keep learning.

Friday, 13 September 2019

Docker in a glimpse

Docker is a great tool for building micro-services, allowing you to create cloud-based applications and systems.
It is a container management service which is based on the concept of Develop, Ship and Run anywhere. To develop apps and ship them into containers which can be deployed on any platform.

With the initial release of Docker technology in March 2013, there was an embarkment of new technical term - Containerization. It has started revolutionizing the old concept of virtualization, where we need to build a complete Guest OS on top of a host OS to run an application.

Virtual machines are resource-intensive as they consumes a lot of resources (compute, memory,etc) in runtime whereas containers are lightweight and boots up in seconds.

Virtualization vs Containerization





Architecture of Docker


The basic architecture of Docker is a Client-Server architecture and consists of 3 major parts:

1. Docker Host - Docker Host runs the Docker Daemon. Docker Daemon listens for Docker requests. Docker requests could be ‘docker run’, ‘docker build’, anything.
It manages docker objects such as images, containers, networks, and volumes.

2. Docker Client - Docker Client is used to trigger Docker commands. It sends the Docker commands through a CLI to the Docker Daemon. It can communicate with more than one daemon.

3. Registry - The Registry is a stateless, highly scalable server-side application that stores and lets you distribute Docker images. You can create your own image and upload it to Docker Hub or any other specified registry.
When we run the command docker pull or docker run, the required images are pulled from your configured registry.





What are containers?


A container is a special type of process that is isolated from other processes. Containers are assigned resources that no other process can access, and they cannot access any resources that are not explicitly assigned to them.


The technology behind the containers!!


Docker containers are evolved from LXC (Linux Containers)
LXC is the well-known and heavily tested low-level Linux container runtime. It is in active development since 2008 and has implemented various well-known containerization features inside the Linux kernel.
The goal of LXC is to create an environment as close as possible to a standard Linux installation but without the need for a separate kernel. To read more about LXC here.

Docker Daemon/Engine is evolved from LXD (LXD daemon)
LXD is a next generation system container manager. It offers a completely fresh and intuitive user experience with a single command line tool to manage your containers. Containers can be managed over the network in a transparent way through a REST API.


Features of Containers:



  • Complete isolation - Two containerized processes can run side-by-side on the same computer, but they can’t interfere with each other. They can’t access each other’s data unless explicitly configured to do so.
  • Shared physical infrastructure - We don't need separate hardware for running different applications. All can share the same hardware. Shared hardware means lower costs.
  • More Secure - Since there is sharing of hardware only but the processes and data being isolated so it becomes very secure.
  • Faster scaling of applications - The creation and destroying time for containers is negligible. Even there is no need to purchase the physical infrastructure for scaling up of an application like it used to happen many years ago.



The future of Docker


As the technology shifted from mainframes to PC, Baremetal to Virtualization, Datacenters to Cloud. Now is the time for moving from host to containers (going serverless).
As per the trend analysis, By 2020, more than 50% of the global organizations will be running containers in production.

After going through many articles, I can infer that trend in technology has inclined more towards Kubernetes after DockerCon 2017 as the Swarm (Docker's inhouse container orchestration tool) started seeing a tough competition.

Though the simplicity of the Docker Swarm as the container orchestrator that has taken Docker to this level.

We haven't seen any recent development in Docker Swarm repository from quite a long time. (https://github.com/docker/swarm/wiki)

Even Docker itself has adopted Kubernetes as a container orchestrator.

Is this an indication that the Docker Swarm will be soon out of the picture as more and more industries start adopting Kubernetes in their architecture.

Needless to say that the docker has survived till now and will keep running as an organization, regardless of the speculations that some big organizations will acquire it. There are a lot of new upcoming features and development still going on.

Incorporating cgroups v2 will give Docker better resource isolation and management capabilities.
Adopting P2P model for image delivery and distribute images using something like BitTorrent sync.

Referenced Articles:



See you in the upcoming tutorials for taking a deeper dive into Docker.

Monday, 2 September 2019

ESP8266 IOT sensing with Blynk

Basically the internet of things, or IoT, is a system of interrelated computing devices, mechanical and digital machines, objects, animals or people that are provided with unique identifiers (UIDs) and the ability to transfer data over a network without requiring human-to-human or human-to-computer interaction.

Evolution of IOT


The internet of things is also a natural extension of SCADA (supervisory control and data acquisition), a category of software application program for process control, the gathering of data in real time from remote locations to control equipment and conditions.
SCADA systems include hardware and software components. The hardware gathers and feeds data into a computer that has SCADA software installed, where it is then processed and presented it in a timely manner. The evolution of SCADA is such that late-generation SCADA systems developed into first-generation IoT systems.


Designing of our first IOT system


Here we are using ESP8266 Nodemcu module which collects the realtime data from the temperature/humidity sensor (DHT-22) and the soil moisture sensor once every second.

I have created this arduino code where we are collecting this sensor data and sending it over to Blynk hosted API with the help of Blynk libraries.

  1. Download the latest library Blynk_Release_vXX.zip file from the GitHub page and extract the zip file to the Library location of Arduino software.
  2. Download Blynk App on Android or iOS device and follow these steps for getting started.
  3. Download the code from my github repository.
git clone https://github.com/saurabh221089/esp8266_iot_blynk.git

Generate your auth token from app and update it in the code.
char auth[] = "53e4da8793764b6197fc44a673ce4e21";
Change you SSID and Password in the code and flash this code on your ESP module.
char ssid[] = "wifi4u";  //Enter your WIFI Name
char pass[] = "abcd1234";  //Enter your WIFI Password

In the created project on the app, assign the Virtual Pins to the Variables in the program to PULL the data from the API and show it on the app dashboard. 

Blynk.virtualWrite(V5, h);  //V5 is for Humidity
Blynk.virtualWrite(V6, t);  //V6 is for Temperature
Blynk.virtualWrite(V7, m);  //V7 is for Soil Moisture

Flash this code on your NodeMCU module and run the app on the same time to start monitoring.

If you just want to build a static weather monitoring module without any networking involved. You can create a weather monitoring station with ESP8266 and an OLED display.

All the best my friends for your exploration into IOT world. Happy IOTing!!

ESP8266 weather monitor

This tutorial will help you setup your own Weather Monitor with Nodemcu development board on which ESP8266 module is sitting as a microcontroller.

We are going to build a Weather monitor that will show all the vital stats for my home plantation.
Temperature (C), Humidity, Heat Index and Soil moisture percentage. This has helped me to maintain the perfect levels for apt growth of indoor plants.

What is an ESP8266?


The ESP8266 is a System on a Chip (SoC), manufactured by the Chinese company Espressif. It consists of a Tensilica L106 32-bit micro controller unit (MCU) and a Wi-Fi transceiver. It has 11 GPIO pins* (General Purpose Input/Output pins), and an analog input as well. This means that you can program it like any normal Arduino or other microcontroller.

And on top of that, you get Wi-Fi communication, so you can use it to connect to your Wi-Fi network, connect to the Internet, host a web server with real webpages, let your smartphone connect to it, etc. The possibilities are endless! It's no wonder that this chip has become the most popular IOT device available in the market today.

Pre-Requirements


1. Arduino software to upload the .ino sketch on the nodemcu
2. To program the ESP8266, you'll need a plugin for the Arduino IDE, it can be downloaded from GitHub manually, but it is easier to just add the URL in the Arduino IDE:
  1. Open the Arduino IDE.
  2. Go to File > Preferences.
  3. Paste the URL http://arduino.esp8266.com/stable/package_esp8266com_index.json into the Additional Board Manager URLs field.(You can add multiple URLs, separating them with commas.)
  4. Go to Tools > Board > Board Manager and search for 'esp8266'. Select the newest version, and click install. (As of Sep 1st 2019, the latest stable version is 2.5.0.)

Components Required


  • NodeMCU (ESP8266 development board)
  • OLED 128x64 screen
  • DHT-22 temperature/humdity sensor
  • Capacitive Soil Moisture sensor
  • Few jumper cables to connect the components and a breadboard.

Github Repo to clone this project and code




Schematic diagram of the complete circuit



If you want to monitor the weather on your Android device when you are outside your home and want to leverage the full potential of ESP8266 module. You can create an IOT enabled weather monitoring station with ESP8266, DHT-22 sensor and Blynk library and monitor the weather from anywhere around the world.

Monday, 26 August 2019

Role of Ansible in DevOps


Ansible is an open source automation platform. Ansible can help you with configuration management, application deployment, task automation and also IT orchestration.
It is very simple to setup, efficient and powerful tool to make IT professional's life easy.

Features of Ansible:

  1. Ansible uses YAML syntax to define playbook configuration files which is having minimum syntax and easy to understand by humans. 
  2. Write few lines of code to manage and provision your infrastructure.
  3. The work velocity of developers were affected since sysadmins were taking time to configure servers.
  4. Roll-ups and Roll-backs are possible if we want to go back to Java 1.8 from Java 2.0.
  5. Grouping of Servers for partial deployment, let's say on 40 servers out of 100 servers.
  6. Uses push based configuration methodology, where no agent needs to be installed on slaves.
  7. Agent-less configuration tool unlike Puppet & Chef that uses Pull-based (agent-based) config methodology.
  8. Ansible Tower is a GUI based tool where deployment can be done from UI for Large scale enterprises.


Sample Ansible Playbook config file created to make understand the syntax:


Download the sample file - Click Here


Playbooks are simple files written in YAML code. Used to declare configurations and launching task synchronously and asynchronously.
A YAML file will always start with '---' three hyphens.
Indentation matters a lot in YAML files. Running an incorrectly indentated file will run into error and you'll have to spend a lot of time in checking for that extra space.


Hosts is simply a remote machine that Ansible manages. They can have individual variables assigned to them, and can also be organized in groups.


Tasks combine an action with a name. Playbooks exist to run tasks.


Action is a part of a task that specifies which of the modules to run and which arguments to pass to that module. Each task can have only one action, but it may also have other parameters.


Notify is the act of a task registering a change event and informing a handler task that another action needs to be run at the end of the play. If a handler is notified by multiple tasks, it will still be run only once.


Handlers are just like task but they will only run when notified by successful completion of that task.
Handlers are run in the order they are listed, not in the order that they are notified. They are placed at same level (identation) as hosts and tasks in YAML.

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

We can execute commands on remote machines via 2 commands

1. Directly by issuing command
ansible all -m copy -a "src=/home/user1/test.html dest=/home/user2"

2. By creating a playbook file and running it.
ansible-playbook /opt/playbooks/copyfile.yml


##To check the syntax of playbook.yml file

ansible-playbook test-playbook.yml --syntax-check


##To check the list of modules that comes installed with Ansible
(You will be surprised to know that there are around 3000 modules installed by default)
ansible-doc -l


##To test a module named ping, for checking connectivity between controller and slave nodes
ansible -m ping web-servers


If you'll start exploring various modules in ansible, trust me you will fall in love with this tool. As there is nothing which can not be accomplished by it.

Friday, 23 August 2019

Setting up an Ansible Server on AWS EC2 instance


To setup Ansible server on EC2 instance we need to first launch an EC2 instance and SSH into it. Now follow the below commands to install Ansible on it.

##Create ansadmin user and update its password 
useradd ansadmin
passwd ansadmin

##Add ansadmin user to sudoers group
echo "ansadmin ALL=(ALL) ALL" >> /etc/sudoers

##sed command replaces "PasswordAuthentication no to yes" without editing sshd_config file
sed -ie 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config

##create ssh keys for password-less authentication between Ansible control server and hosts.

#Login as ansadmin user and generate ssh key on Master
ssh-keygen

#Create same ansadmin user on the target host server.

#Copy Master ssh keys onto all ansible hosts nodes
ssh-copy-id <target-host-server>

#Update target servers IP on /etc/ansible/hosts file on Master (Always use internal Private IP address)
echo "<target host server IP>" >> /etc/ansible/hosts


Ansible hosts file should look like: cat /etc/ansible/hosts

[web-servers]
10.0.1.20
10.0.1.21
10.0.1.22

#Run ansible command as ansadmin user on Control server. It should be successful.
ansible all -m ping


We have now setup a successful passwordless authentication between all the hosts and the control server from where we can handle any type of tasks like installing any application, starting/stopping any service, copying a config file on servers.
This we will discuss in our next blog.

Setting up a Tomcat server on AWS EC2 instance


This will create a Tomcat server on AWS EC2 instance and don't forget to add Port 8080 in the Security Group open for everyone to connect on the server.

Step 2 is similar installing Java jdk and setting up JAVA_HOME in path variable.


##Download the latest tomcat and extract under /opt directory
cd /opt
wget https://www-us.apache.org/dist/tomcat/tomcat-9/v9.0.22/bin/apache-tomcat-9.0.22.tar.gz
tar -xzf apache-tomcat-9.0.22.tar.gz

##Update the permissions to make startup.sh/shutdown.sh executables.
chmod +x /opt/apache-tomcat-9.0.22/bin/startup.sh shutdown.sh


##Create shortcut for starting/shutting down tomcat server
ln -s /opt/apache-tomcat-9.0.22/bin/startup.sh /usr/local/bin/tomcatup
ln -s /opt/apache-tomcat-9.0.22/bin/shutdown.sh /usr/local/bin/tomcatdown


##Add to the /conf/tomcat-users.xml file as we will be needing the deployer user to deploy our war file.

<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui, manager-script, manager-jmx, manager-status"/>
<user username="deployer" password="deployer" roles="manager-script"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>


##Search for context.xml files

find / -name context.xml

above command gives 3 context.xml files. comment () Value ClassName field on files which are under webapp directory.

##restart tomcat services through our created shortcut
tomcatdown
tomcatup

You can check if the server is up and running by typing the http://public-IP:8080 in your browser.

Setting up a Jenkins Server on AWS EC2 instance


Let us first understand what is Jenkins? Jenkins is a self-contained, open source automation server which can be used to automate all sorts of tasks related to building, testing, and delivering or deploying software. Jenkins is a software that allows continuous integration.

Prerequisites:

Launch and SSH into EC2 Instance.
Don't forget to add Port 8080 in the Security Group to open for all incoming connections.
Java JDK should be installed.

Install Java 1.8 JDK

  • sudo su
  • yum update –y
  • yum install java-1.8*

Update Bash_profile to set JAVA_HOME variable


  • To get the path of java binary - find /usr/lib/jvm/ -name java
  • Add below lines to your .bash_profile file in user's home directory. 
    • JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-1.el7_6.x86_64
    • export JAVA_HOME
    • PATH=$PATH:$JAVA_HOME
  • save the file :wq 
  • To make the changes effective immediately update your .bash_profile
    • source ~/.bash_profile
  • java -version (check the java version)

Install Jenkins


yum -y install wget
wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo

Import a key file from Jenkins-CI to enable installation from the package

rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
yum install jenkins -y


Start Jenkins as a service


## Start jenkins service
systemctl start jenkins

## Setup Jenkins to start at boot,
systemctl enable jenkins


Accessing Jenkins UI


Visit the following address in your browser, http://EC2-SERVER-PUBLIC-IP:8080


Things to do after first login:


  • Default Password Location: cat /var/lib/jenkins/secrets/initialAdminPassword

  • Change admin password
    • Admin > Configure > Password

  • Configure java path
    • Manage Jenkins > Global Tool Configuration > JDK

  • Now you are ready to create a job for your build. Test Jenkins Job
    • Create “new item”
    • Enter an item name – My-first-job
    • Chose Freestyle project
    • Under Build section - choose option - Execute shell : echo "Welcome to Jenkins Demo"
    • Save your job
    • Build job
    • Check "console output" for successful completion of job.
Hurray!! you have just created and ran your first job.

Restarting Jenkins through browser (Only if you are logged in as Admin user)
http://<ip-address>:8080/restart

Wednesday, 7 August 2019

Designing HA Architecture in AWS part-3

Amazon Web Services (AWS) offers a wide range of services that we can leverage to implement High Availability (HA) to any web application that we deploy on the AWS cloud.

I am going to create a Web application which is highly available, resilient, optimized and secure. It delivers high performance and low latency everytime users are accessing it and from whereever the users are accessing it.
I have deployed this application with following parameters:

Region - ap-south-1 (Asia Pacific Mumbai)
Availability Zone - AZ-a and AZ-b
A highly available architecture that spans two Availability Zones. Multi-AZ deployment.
VPC - I have created 2 Virtual Private Clouds
  • testVPC (10.0.0.0/16)
  • new-testVPC (10.1.0.0/16)

Subnets - I have created 2 Subnets and 2 Subnets in this VPC.

Under Availability Zone AZ-b
  • Public_subnet1b = 10.0.1.0/24
  • Private_subnet1b = 10.0.2.0/24

Under Availability Zone AZ-a
  • Public_subnet1a = 10.0.20.0/24
  • Private_subnet1a = 10.0.21.0/24
WPS - I have provisioned the EC2 instances in both of the Public Subnets and installed wordpress on them and named them WPS. So at any point of time we will be having traffic served by atleast 2 intances (1 in each subnet) to a maximum capacity of 6 instances (3 in each subnet).

Route53 - Its a DNS service used for Domain Name Registration, maintaining DNS record sets and setting up different routing policies for Domain Names.

Schematic diagram of the HA architecture below:






I have tried to explain this in Problem and Solution fashion, means what problems I have faced during designing a HA architecture and how I have implemented the solution to that problem.


Problem - How to manage unpredictable load on webserver EC2 instances in our architecture?
Solution - Auto-Scaling Groups

  • An Auto-Scaling group is dependent on 2 things: Launch Configuration and Scaling Policies.

Implementation -

  • First choose the Launch Configuration and the VPC and Subnet in which we are implementing the Auto-Scaling group.
  • Define the group size starting with 1 instance.
  • Next step defining the minimum and maximum size of our group. (Min=1 and Max=3 instances)
  • Create an alarm for Increase Group Size : Avg. CPU utilization >= 75% for consecutive period of 5 mins.
  • You can optionally opt for sending Notification to a Topic name when the above alarm is triggered.
  • Similarly create an alarm for Decrease Group Size : Avg. CPU utilization < 60% for consecutive period of 5 mins.
  • Under the instances tab on selecting Auto-Scaling group, we can see the lifecycle/status of the instances.



Problem - How to get an auto-configured server everytime an instance is added in the Auto-Scaling group?
Solution - Snapshot
  • A Snapshot is a backup of a single EBS volume. You can create an AMI from Snapshot. It is not a bootable copy but an AMI is.

Implementation -

  • Provision a template EC2 instance -> Install Apache,Wordpress and all the key configurations
  • Take Snapshot of the root volume of the EC2 instance, (we can terminate the template instance after taking snapshot).
  • Create an AMI with this Snapshot and name it myWebAppAMI.
  • Use this AMI as Launch Configuration in the Auto Scaling group to spawn an auto-configured EC2 instance in the subnets.
  • In this manner we will be saving the boot time of the newly created EC2 instances and no need to do configurations remotely everytime a server boots up.



Problem - How to update/patch the EC2 instance in private subnet as there is no inbound nor outbound internet access?
Solution - NAT instance

  • A NAT instance, allows your private instances outgoing connectivity to the internet while at the same time blocking inbound traffic from the internet.
  • A NAT instance is similar to a normal EC2 instance with NAT Optimized HVM type AMI.

Implementation -
  • In the public subnet (public_subnet1a), provisioned a NAT instance to allow outbound internet access for DB_server instance in the private subnet (private_subnet1a).
  • After running this instance I have changed the Destination/Source check and disabled it. To do this, right click on your NAT Instance within the AWS Console and select ‘Networking > Change Source/Dest. Check > Yes, Disable’.
  • NAT Gateways provide the same functionality as a NAT instance, however, a NAT Gateway is an AWS managed NAT service. As a result, these NAT Gateways offer greater availability and bandwidth and require less configuration and administration. This was a costlier option and moreover should be applied to a very large scale application.


Problem - How to have SSH access of EC2 instances in private subnets?
Solution - Bastion hosts

  • A Bastion Host is a special purpose computer on a host designed and configured to withstand attacks.
  • It acts as a jump server, allowing you to use SSH or RDP to log in to other instances within private subnets.

Implementation -

  • As we know the servers in private subnets are not configured to talk to the outside network. I have updated the Private Security Group to accept all the inbound/outbound traffic from Public Security Group.
  • In the public subnets, EC2 instances in an Auto Scaling group to allow inbound Secure Shell (SSH) access to EC2 instances in private subnets.



Problem - How to maintain performance of website with the increasing site traffic?
Solution - Elastic Load Balancer (ELB)
Implementation -

  • An Application Load Balancer must be deployed into at least two subnets (Public_subnet1a & Public_subnet1b) to distribute HTTP and HTTPS requests across multiple WordPress instances (WPS1,WPS2,..,WPSn).



Problem - Increasing site traffic means increasing query load on Database, How to cope up?
Solution - ElastiCache

  • Caching improves application performance by storing critical pieces of data in memory for low latency access.
  • Cached information may include the results of I/O-intensive database queries or the results of computationally-intensive calculations.
  • Suppose we are running an online business, customers continuously asking for the information of a particular product. Instead of making a call to DB and always asking information for that product, we can cache the product data using Elasticache.

Implementation -

  • I have used Redis nodes for caching database queries.
  • As the Redis Cache is dependent on just Memory, we should always create the Redis node with Memory Optimized Instance type – (X1, R5, R4, R3)
  • Port should be kept default port - 6379
  • We can set number of Replicas from 0 to 5 to be a part of the cluster.



Problem - How to control the inbound/outbound traffic in the VPC?
Solution - Security Groups and Network Access Control Lists

  • Security Groups add a security layer to EC2 instances that control both inbound and outbound traffic at the instance level.
  • NACL also adds an additional layer of security associated with subnets that control both inbound and outbound traffic at the subnet level.

Implementation -

  • I have created 2 Security Groups - test_security_group and test_security_group_private.
  • I have declared the routes in the route tables and associated the subnets with the respective table - public_route_table and private_route_table



Problem - Why not create a MySQL Database instance instead of a RDS instance?
Solution - RDS (MySQL)
Implementation -

  • Creating a RDS endpoint instead of deploying mySQL Database on an EC2 instance is better in many ways.
  • It frees you from managing the time-consuming database administration tasks such as provisioning, backups, software patching, monitoring, and hardware scaling.
  • It supports "License-included" licensing model, so we do not have to care about purchasing license separately.
  • Amazon RDS provides high availability of MySQL Server using multi-availability zone capability, and this reduces the risk to data loss.



Problem - How should I keep an active most recent backup of our WebApp?
Solution - Amazon S3

  • S3 buckets store the data as objects. We have many advantages of backing up any webapp on these buckets because of their high availability and durability.

Implementation -

  • I am using S3-IA or S3-RRS buckets instead of S3-Standard to decrease the costing of this model as we do not want to access it frequently.
  • I have created a Cron job running on the WebApp EC2 instance to take backup of site hourly.
  • * */1 * * * aws s3 sync --delete /var/www/html s3://<bucket_name>



Problem - How to minimize the high latency if users are accessing this web application from US/Europe or any other part of globe?
Solution - CloudFront
Implementation -

  • I have implemented the CloudFront as the static Content Delivery Network because static content is heavy (such as JPG, media, Audio files) and unnecessary load on EC2 instances.
  • All the static content is being served from the nearest edge locations to the users worldwide. This has helped a lot in maintaining a low latency irrespective of the placement of the EC2 instances.



Problem - The Web application needs to talk to an EC2 instance in a different VPC, how should we do it?
Solution - VPC Peering

  • A VPC peering connection is a networking connection between two VPCs that enables you to route traffic between them using private IPv4 addresses or IPv6 addresses.
  • Instances in either VPC can communicate with each other as if they are within the same network.
  • You can create a VPC peering connection between your own VPCs, or with a VPC in another AWS account.
  • The VPCs can be in different regions (also known as an inter-region VPC peering connection), it provides a simple and cost-effective way to share resources between regions.

Implementation -

  • This peering was added to the architecture taking into account that some service might be required by WebApp running in main VPC to communicate/fetch data from some other EC2 instance in different VPC.
  • I have created a VPC peering named test_peer between the 2 VPCs (testVPC and new-testVPC) which has made communication possible between these VPCs.
  • Additionally I have to add an entry in route table for both of the public subnets in which the EC2 instances needs to communicate.
    • public_route_table -> 10.1.0.0./16 test_peer
    • new_public_route_table -> 10.0.0.0./16 test_peer

I hope this information will be helpful for upcoming solution architects. If you have any doubt/query please feel free to ask in the comment section below.