Project Objective:
Building an internal tool for a company to collect and manage employee information. The EC2 instance hosts an Employee Information Form (index.html) accessible within the company network. Employees fill out the form, providing details such as their name, age, designation, state, country, and gender.
When an employee submits the form, the data is sent to DynamoDB through API Gateway, utilizing AWS Lambda to process and store the information. This creates a seamless and secure way to gather and manage employee details centrally.
Pre Requisites:
1.DynamoDB
2.IAM Roles
3.Lambda Function
4.API Gateway
5.EC2 Instance.
Creation of Dynamodb:
1.In the aws console search for dynamodb then click on create table.
2.Then enter name of the dyanmodb table name and partition key(anything) and sort key is optional then click on create table.
3.Then click on the table then click on aditional details then note down the ARN of the table, it is required for future reference.
4.Then we can click on explore table items and we can create items and we can check by clicking on the Run.
@@@@@
2.Creation of IAM Roles:
Creating Policy for Lambda:
1.In the aws console search for IAM then click on polocy then click on json then add the script given by below.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem"
],
"Resource": "arn:aws:dynamodb:ap-south-1:YOUR_ACCOUNT_ID:table/dynamodb-name"
}
]
}
Note: Here modify the region & accountID & dynamodb-name
2.Then click on next then enter name of the policy then create the policy.
Creating Lambda Role:
1) In the aws console Search for IAM and navigate to Roles.
3.Use case select the lambda why because we are assigning this role to lambda and hit on the next button.
4.Then we have to search for the policy what ever we created Then click on next.
5.Then enter the name of the lambda function and and click on next then create the role.
@@@@@@
3.Creation of Lambda Function:
1)In the aws console search for lambda then click on create function.
2)Then enter the name of the function then select runtime as python then click on existing role then select the existing role what ever we created earlier and click on create function.
3)Then under the script we have to enter the script.
**Note: **in the script line No:10 we have to enter the name of the dynamodb table what ever we created earlier.
# import the JSON utility package
import json
#import the AWS SDK (for Python the package name is boto3)
import boto3
# import two packages to help us with dates and date formatting
from time import gmtime, strftime
# create a DynamoDB object using the AWS SDK
dynamodb = boto3.resource('dynamodb')
# use the DynamoDB object to select our table
table = dynamodb.Table('dynamodb-table-name')
# store the current time in a human readable format in a variable
now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
# define the handler function that the Lambda service will use an entry point
def lambda_handler(event, context):
print(event)
age=str(event['age'])
response = table.put_item(
Item={
'Name': event['name'],
'Age':age,
'Gender':event['gender'],
'Designation':event['designation'],
'State':event['state'],
'Country':event['country']
})
# return a properly formatted JSON object
return {
'body': json.dumps('Data inserted in DB succesfully')
}
4)After entering the script we have to click on deploy.
5)Next we have to click on test button.
6)We have to enter the script like this for adding this data to dynamodb and also in the event section we have to provide any name and click on save then test the lambda function is updating the dat in the dynamodb or not.
7)After that we can check the update in the dynamodb by clicking on the text button.
8)Finally connectivity between lambda and dynamodb is working fine.
@@@@@@@@@@@@
4.Creation of API Gateway:
I.In the aws console search for api and click on api gateway
III.Click on Build in the rest api section.
IV.Enter the name of the api then click on create button.
V.Click on create method.
VI.Choose post option and arn and type as lambda and function also then click on create.
VII.Then click on enable cors.
VIII.Then click on deploy api
IX.Then enter name of the deploy and choose new stage then click on deploy.
X.After creating deploy we will get url we have to save that for feture reference.
XI.Then we can check the connectivity between api and lambda.
XII.For that we have to click on method we created post method earlier then we have to click on test then we have to add the script in json format same like how we enter in the labda test section ofter that we can see the updates reflection in the dynamodb it is updated or not.
5.Creating EC2 instance:
a)In the aws console search for ec2 then click on create ec2 instance.
b)Enter the name and under the user data add the bwlow script for installing httpd.
c)Ofter creating the ec2 instance under the /var/www/html/index.html file will be there.
d)We have to remove the existing data and add the script below.
<!DOCTYPE html>
<html>
<head>
<title>Candidate Information Form</title>
</head>
<body style="background-color: #3498db;">
<h1 style="text-align: center; color: #fff;">Candidate Information</h1>
<div style="max-width: 400px; margin: 0 auto; padding: 20px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
<form id="candidateForm">
<label for="name" style="display: block; margin-bottom: 8px; color: #555;">Name:</label>
<input type="text" id="name" name="name" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #e8f0fe;">
<label for="age" style="display: block; margin-bottom: 8px; color: #555;">Age:</label>
<input type="number" id="age" name="age" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #f9e8e8;">
<label for="designation" style="display: block; margin-bottom: 8px; color: #555;">Designation:</label>
<input type="text" id="designation" name="designation" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #f3f3d9;">
<label for="state" style="display: block; margin-bottom: 8px; color: #555;">State:</label>
<input type="text" id="state" name="state" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #e6f6f0;">
<label for="country" style="display: block; margin-bottom: 8px; color: #555;">Country:</label>
<input type="text" id="country" name="country" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #fde8e6;">
<label for="gender" style="display: block; margin-bottom: 8px; color: #555;">Gender:</label>
<select id="gender" name="gender" required style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; background-color: #f9ebca;">
<option value="" disabled selected>Select gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<input type="submit" value="Submit" style="background-color: #4CAF50; color: #fff; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s ease;">
</form>
</div>
<script>
// Replace 'YOUR_DYNAMODB_API_URL' with the API endpoint to interact with your DynamoDB backend.
const DYNAMODB_API_URL = 'https://34laurmeo9.execute-api.ap-south-1.amazonaws.com/production';
document.getElementById('candidateForm').addEventListener('submit', function (event) {
event.preventDefault();
const formElements = event.target.elements;
const candidateData = {
name: formElements.name.value,
age: formElements.age.value,
designation: formElements.designation.value,
state: formElements.state.value,
country: formElements.country.value,
gender: formElements.gender.value,
};
// Sending the candidateData to your DynamoDB backend using a fetch API request.
fetch(DYNAMODB_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(candidateData),
})
.then((response) => {
if (response.ok) {
// Show the success popup if the data is successfully stored in DynamoDB.
alert('Successfully submitted!');
// Reset the form after successful submission.
document.getElementById('candidateForm').reset();
} else {
// Show an error popup if there was an issue with storing the data.
alert('Submission failed. Please try again later.');
}
})
.catch((error) => {
console.error('Error:', error);
// Show an error popup if there was an issue with the API request.
alert('Submission failed. Please try again later.');
});
});
</script>
</body>
</html>
e)Note: in the above script in the line 34 we have to modify the DYNAMO_DB_URL with the api url what ever we noted down earlier
f)Then access the application by using ec2 public ip in the chrome.
#### THE END #####
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Same project but ui is body mass index calculator.
for this project also same steps like above project.
1.dynamodb Partition key should be 'First Name' and 'sort key' is optional.
lambda script:
# import the JSON utility package
import json
# import the Python math library
import math
#import the AWS SDK (for Python the package name is boto3)
import boto3
# import two packages to help us with dates and date formatting
from time import gmtime, strftime
# create a DynamoDB object using the AWS SDK
dynamodb = boto3.resource('dynamodb')
# use the DynamoDB object to select our table
table = dynamodb.Table('DYNAMODB TABLE NAME')
# store the current time in a human readable format in a variable
now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
# define the handler function that the Lambda service will use an entry point
def lambda_handler(event, context):
print(event)
height=float(event['height'])/100
weight=float(event['weight'])
bmi=weight/height**2
# write result and time to the DynamoDB table using the object we instantiated and save response in a variable
#remember "First Name" and "Last Name" we have entered exactly same to partition key name and Sort key name in the DynamoDBtable.
response = table.put_item(
Item={
'First Name': event['firstname'],
'Last Name':event['lastname'],
'Height':event['height'],
'Weight':event['weight'],
'BMI':str(bmi),
'Recorded Time':now
})
# return a properly formatted JSON object
return {
'statusCode': 200,
'body': json.dumps('Your BMI is ' + str(bmi))
}
index.html script:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculate Your BMI!</title>
<!-- Styling for the client UI -->
<style>
h1 {
color: #FFFFFF;
font-family: system-ui;
margin-left: 20px;
}
body {
background-color: #4D8FB4;
}
label {
color: #86C900;
font-family: system-ui;
font-size: 20px;
margin-left: 20px;
margin-top: 20px;
}
button {
background-color: #86C232;
border-color: #86C232;
color: #FFFFFF;
font-family: system-ui;
font-size: 20px;
font-weight: bold;
margin-left: 30px;
margin-top: 20px;
width: 140px;
}
input {
color: #222629;
font-family: system-ui;
font-size: 20px;
margin-left: 10px;
margin-top: 20px;
width: 100px;
}
</style>
<script>
// callAPI function that takes the base and exponent numbers as parameters
var callAPI = (firstname,lastname,weight,height)=>{
// instantiate a headers object
var myHeaders = new Headers();
// add content type header to object
myHeaders.append("Content-Type", "application/json");
// using built in JSON utility package turn object to string and store in a variable
var raw = JSON.stringify({"firstname":firstname,"lastname":lastname,"weight":weight,"height":height});
// create a JSON object with parameters for API call and store in a variable
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
// make API call with parameters and use promises to get response
fetch("YOUR API ENDPOINT", requestOptions)
.then(response => response.text())
.then(result => alert(JSON.parse(result).body))
.catch(error => console.log('error', error));
}
</script>
</head>
<body>
<h1>Get Your BMI...!</h1>
<form>
<label>First Name:</label>
<input type="text" id="firstname">
<label>Last Name:</label>
<input type="text" id="lastname">
<br>
<label>Weight in Kg:</label>
<input type="text" id="weight">
<label>Height in cm:</label>
<input type="text" id="height">
<br>
<!-- set button onClick method to call function we defined passing input values as parameters -->
<button type="button" onclick="callAPI(document.getElementById('firstname').value,document.getElementById('lastname').value,document.getElementById('weight').value,document.getElementById('height').value)">Calculate and record</button>
</form>
</body>
</html>
New Task:
Deploying same html file in the aws amplify.
Search AWS amplify. Click on get started.
Deploy without git provider.
Drag and deploy the zip folder here. Save and deploy.
Our application is successfully deployed. We are ready to go. Open the domain url. You will see the efforts paid off....
The Window is as shown below.
As soon as you hit the calculate and record button, you will get response in alert format as shown on the screen. Parallely the records will be stored in DynamoDB table as shown below.
Top comments (0)