0% found this document useful (0 votes)
16 views

Cloud Computing

The document discusses creating a serverless Python application using AWS Cloud9 IDE. It covers provisioning a Cloud9 environment, creating a SAM application with Python 3.8 runtime, configuring and testing the application locally, and deploying the application as an AWS Lambda function.

Uploaded by

SRIMANTH BATTULA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Cloud Computing

The document discusses creating a serverless Python application using AWS Cloud9 IDE. It covers provisioning a Cloud9 environment, creating a SAM application with Python 3.8 runtime, configuring and testing the application locally, and deploying the application as an AWS Lambda function.

Uploaded by

SRIMANTH BATTULA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Creating a Serverless Python App using

AWS virtual integrated development


environment (IDE), Cloud 9.

Serverless computing is a cloud computing execution model, in


which infrastructure provisioning and management are handled by
the cloud provider, allowing the IT professional to focus on the
application. Serverless services vary based on their proposed use
cases but, for this article, we will focus on the Serverless
Application Model (SAM). In SAM, the application in context is
functional codes that respond to events when triggered.

In this article, we’ll use AWS virtual integrated development


environment (IDE), Cloud 9 to create a serverless python
application, test the application using function and API call, and
deploy the application to AWS Lambda function.
Objectives
 Provision AWS Cloud9 Environment.

 Create SAM Application with python 3.8 runtime.

 Configure and test SAM application.

 Deploy SAM application as Lambda function.

 Test Lambda function.

 Clean up.

Pre-requisites
 Amazon Web Services (AWS) account

 AWS S3 bucket (In the same region with other resources)

 IAM User with Administrator Access Policy

Let’s do this

Provisioning of AWS Cloud9 Environment

Step 1: Sign in to AWS Management Console.

Step 2: Navigate to the Cloud9 Service.


Cloud9 Service

Step 3: Click Create Environment

Create Cloud9 Environment

Name environment
Name: wiki
Description: Describe product from Wikipedia

Configure Settings
Environment type: Create a new EC2 instance for
environment
Instance type: t2.micro (1GiB RAM + 1vCPU)
Platform: Amazon Linux 2
Cost-saving setting: After 30minutes(default)
Tag:
Key: wikipedia
Value: python

Review and Create Environment

Cloud9 IDE ready for development

Create SAM Application with python 3.8 runtimes

Step 1: Click aws-explorer (aws-icon) from the left navigation


pane.

Step 2: Click the > beside the region.

Step 3: Right-click Lambda and select Create Lambda SAM


Application.

Select a SAM Application model: python 3.8


Select an Architecture: x86_64
Select a SAM Application Template: AWS SAM Hello World
Select a workspace folder: wiki
Enter a name for your new application: wiki_func

Hit Enter Key

Step 4: Click the toggle tree (folder icon) from the left pane and
navigate to the wiki_func/hello_world directory.

Step 5: Replace the contents of the app.py file with the snippet


import json
import wikipedia# prints when function loads
print('Loading function')
def lambda_handler(event, context):

# Check that the request has some input body and save it
if 'body' in event:
event = json.loads(event["body"]) # Get the wikipedia
"entity" from the body of the request
entity = event["entity"]
res = wikipedia.summary(entity, sentences=4) # 4 sentences
# print statements
print(f"context: {context}, event: {event}")
print(f"Response from wikipedia API: {res}") # Format the
response as JSON and return the result
response = {
"statusCode": "200",
"headers": { "Content-type": "application/json" },
"body": json.dumps({"message": res})
} return response

Save your changes.

Step 6: Append wikipedia to the requirements.txt file and save

wikipedia in requirements.txt
The default disk space for Cloud9 is insufficient for running the
AWS Toolkit container images. Let’s resize the disk space

Step 7: Click the plus icon in the windows tab, select New File and
paste the shell script
#!/bin/bash# Specify the desired volume size in GiB as a command
line argument. If not specified, default to 20 GiB.
SIZE=${1:-20}# Get the ID of the environment host Amazon EC2
instance.
INSTANCEID=$(curl
http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(curl -s
http://169.254.169.254/latest/meta-data/placement/availability-
zone | sed 's/\(.*\)[a-z]/\1/')# Get the ID of the Amazon EBS
volume associated with the instance.
VOLUMEID=$(aws ec2 describe-instances \
--instance-id $INSTANCEID \
--query
"Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeI
d" \
--output text \
--region $REGION)# Resize the EBS volume.
aws ec2 modify-volume --volume-id $VOLUMEID --size $SIZE# Wait
for the resize to finish.
while [ \
"$(aws ec2 describe-volumes-modifications \
--volume-id $VOLUMEID \
--filters Name=modification-
state,Values="optimizing","completed" \
--query "length(VolumesModifications)"\
--output text)" != "1" ]; do
sleep 1
done#Check if we're on an NVMe filesystem
if [[ -e "/dev/xvda" && $(readlink -f /dev/xvda) =
"/dev/xvda" ]]
then
# Rewrite the partition table so that the partition takes up
all the space that it can.
sudo growpart /dev/xvda 1# Expand the size of the file system.
# Check if we're on AL2
STR=$(cat /etc/os-release)
SUB="VERSION_ID=\"2\""
if [[ "$STR" == *"$SUB"* ]]
then
sudo xfs_growfs -d /
else
sudo resize2fs /dev/xvda1
fielse
# Rewrite the partition table so that the partition takes up
all the space that it can.
sudo growpart /dev/nvme0n1 1# Expand the size of the file
system.
# Check if we're on AL2
STR=$(cat /etc/os-release)
SUB="VERSION_ID=\"2\""
if [[ "$STR" == *"$SUB"* ]]
then
sudo xfs_growfs -d /
else
sudo resize2fs /dev/nvme0n1p1
fi
fi

Save with file with the name, resize.sh

Step 8: Make resize.sh executable and run the bash script


chmod +x resize.sh
./resize.sh 20

Output:
ec2-user:~/environment $ ./resize.sh 20
% Total % Received % Xferd Average Speed Time Time
Time Current
Dload Upload Total Spent
Left Speed
100 19 100 19 0 0 1727 0 --:--:-- --:--:--
--:--:-- 1727
{
"VolumeModification": {
"TargetSize": 20,
"OriginalMultiAttachEnabled": false,
"TargetVolumeType": "gp2",
"ModificationState": "modifying",
"TargetMultiAttachEnabled": false,
"VolumeId": "vol-06d630f2bc9aa926d",
"TargetIops": 100,
"StartTime": "2021-11-20T02:26:13.000Z",
"Progress": 0,
"OriginalVolumeType": "gp2",
"OriginalIops": 100,
"OriginalSize": 10
}
}
CHANGED: partition=1 start=4096 old: size=20967391 end=20971487
new: size=41938911 end=41943007
meta-data=/dev/xvda1 isize=512 agcount=6,
agsize=524159 blks
= sectsz=512 attr=2,
projid32bit=1
= crc=1 finobt=1
spinodes=0
data = bsize=4096 blocks=2620923,
imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal bsize=4096 blocks=2560,
version=2
= sectsz=512 sunit=0 blks,
lazy-count=1
realtime =none extsz=4096 blocks=0,
rtextents=0
data blocks changed from 2620923 to 5242363

Step 9: In the Terminal, navigate to the wiki_func/hello_world


directory and install the contents of the requirment.txt file
cd wiki_func/hello_world/
pip3 install -r requirements.txt --target .

Great work champ 👏, we’ve successfully set up a SAM application


with python 3.8 and installed its dependencies. Let’s configure our
environment to test the application.

Configure and Test SAM application

Before we deploy the SAM Application, let’s test its functionality


within Cloud9

Step 1: From the toggle tree pane, click the gear icon dropdown and
select Show Hidden Files
Toggle display of hidden files

Step 2: Select the dropdown of the .c9 directory and


open lanch.json

Step 3: Replace the contents of the lanch.json with the snippet


{
"configurations": [
{
"type": "aws-sam",
"request": "direct-invoke",
"name": "api-wiki-config",
"invokeTarget": {
"target": "api",
"templatePath": "wiki_func/template.yaml",
"logicalId": "HelloWorldFunction"
},
"api": {
"path": "/hello",
"httpMethod": "post",
"payload": {
"json": {
"entity": "serverless"
}
}
}
},
{
"type": "aws-sam",
"request": "direct-invoke",
"name": "wiki-config",
"invokeTarget": {
"target": "template",
"templatePath": "wiki_func/template.yaml",
"logicalId": "HelloWorldFunction"
},
"lambda": {
"payload": {
"json": {
"entity": "serverless"
}
},
"environmentVariables": {},
"runtime": "python3.7"
}
}
]
}

Save your changes.

Step 4: Test the SAM application using the local config


Click the dropdown beside Run,
Select wiki-config.
Click Run.

SAM local invocation output

Step 5: Test the SAM application using the api config


Navigate to the template.yaml file and change the HelloWorld
event method to post. Save your changes.

Change event method from get to post


Click the dropdown beside Run,
Select api-wiki-config.
Click Run.

SAM api invocation output

now we’ve tested our application within Cloud9 successfully, let’s


deploy it to the Lambda function.

Deploy SAM Application as Lambda Function

The Cloud9 environment is configured with a predefined IAM user


which won’t give us access to our cloud resources. Let’s configure the
environment with our IAM user and deploy the function.

Step 1: Setup IAM user on Cloud9 environment.


aws configure

Paste the credentials respectively. Force update if required.

Step 2: Refresh webpage to allow new configuration.

Step 3: Click aws-explorer (aws-icon) from the left navigation


pane.

Step 4: Click the > beside the region.

Step 5: Right-click Lambda and select Deploy SAM Application.


SAM template: wiki_func/template.yaml
AWS S3 Bucket to deploy code to: <your_s3_bucket_name>
Name for deployment stack: <name_of_stack>

Hit Enter Key.

SAM Application deployed to wiki-hello stack

Test Lambda Function

Step 1: Navigate to the Lambda service and select Functions from


the left navigation pane.

Step 2: Click the Test tab.


Name: wiki-serverless
Payload:
{
"entity": "serverless"
}

Step 3: Click the Test button.

Function execution output:


API call output:

(Optional) Step 4: Make changes to the code, click deploy and test
the output.

Clean Up

Step 1: Navigate to CloudFormation service.

Step 2: Select and Delete wiki-hello stack.

Step 3: Select and Delete aws-cloud9-wiki-###.

Step 4: Navigate to Cloud9 service and delete the wiki environment.

Congratulations you’ve successfully set up a Cloud9 environment,


created, configured, and tested a SAM Application within Cloud9,
and deployed a SAM application to Lambda functions, where it was
tested.
Conclusion

Serverless computing is a great technique to implement for event-


driven applications but care must be taken to avoid cost escalation
as charges are made from function calls.

You might also like