script for instance setup, minor corrections

This commit is contained in:
Kaushik Narayan R 2024-02-10 10:35:40 -07:00
parent e94c398919
commit 2d833a1379
5 changed files with 116 additions and 2 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
*.pem *.pem
node_modules/ node_modules/
*.log *.log
*.ps1

View File

@ -0,0 +1,23 @@
#!/bin/bash
# initializing instance
cd /home/ubuntu
sudo apt update
sudo apt upgrade -y
# Project specific setup
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
echo -e '\nexport NVM_DIR="$HOME/.nvm"\n[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm \n[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion\n' >> .bashrc
source ~/.bashrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
nvm install v20.11.0
npm i -g pm2
git clone https://github.com/20kaushik02/CSE546_Cloud_Computing_Projects repo
cd repo/Project-1/Part-1/web-tier-express
npm i
# Start
pm2 start npm --name webTier -- run prod
pm2 save

View File

@ -0,0 +1,75 @@
import os
import boto3
import dotenv
import httpx
import pdb
import json
import argparse
class aws_grader():
def __init__(self, access_keyId, access_key):
self.iam_access_keyId = access_keyId
self.iam_secret_access_key = access_key
self.iam_session = boto3.Session(aws_access_key_id = self.iam_access_keyId,
aws_secret_access_key = self.iam_secret_access_key)
self.ec2_resources = self.iam_session.resource('ec2', 'us-east-1')
def get_tag(self, tags, key='Name'):
if not tags:
return 'None'
for tag in tags:
if tag['Key'] == key:
return tag['Value']
return 'None'
'''
Test Case:1
1) Checks if there is a web EC2 instance with the name "web-instance"
2) Checks if the state of "web-instance" is "running".
'''
def test_case_1(self):
message = ""
for instance in self.ec2_resources.instances.all():
name = self.get_tag(instance.tags)
if name == "web-instance":
message += "web-tier instance found."
state = instance.state['Name']
message += f" With state: {state}"
if state == "running":
self.web_tier_instanceId = instance.id
print(f"Test Case:1 Passed. {message}")
return
else:
print(f"Test Case:1 Failed. {message}")
return
message += "web-tier Instance Not Found."
print("Test Case:1 Failed. {message}")
def main(self):
# Use the session to access resources via the role
print("======== Welcome to CSE546 Cloud Computing Grading Console ==================")
print(f"IAM ACESS KEY ID: {self.iam_access_keyId}")
print(f"IAM SECRET ACCESS KEY: {self.iam_secret_access_key}")
self.test_case_1()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Upload images')
parser.add_argument('--access_keyId', type=str, help='ACCCESS KEY ID of the grading IAM user')
parser.add_argument('--access_key', type=str, help='SECRET ACCCESS KEY of the grading IAM user')
args = parser.parse_args()
access_keyId = args.access_keyId
access_key = args.access_key
aws_obj = aws_grader(access_keyId, access_key)
aws_obj.main()

View File

@ -13,16 +13,31 @@ reservation = dev_ec2_client.run_instances(
MaxCount=1, # try to allocate max_count instances. we only need one for now MaxCount=1, # try to allocate max_count instances. we only need one for now
InstanceType="t2.micro", InstanceType="t2.micro",
TagSpecifications=[ TagSpecifications=[
{"ResourceType": "instance", "Tags": [{"Key": "Name", "Value": "WebTier"}]} {"ResourceType": "instance", "Tags": [{"Key": "Name", "Value": "web-instance"}]}
], ],
) )
print("Instances allocated successfully:", "Yes" if reservation else "No") print("Instances allocated successfully:", "Yes" if reservation else "No")
print("Groups:", len(reservation["Groups"])) # TODO: add grp info logging print("Groups:", len(reservation["Groups"])) # TODO: add grp info logging
print("Instances:", len(reservation["Instances"])) print("Instances:", len(reservation["Instances"]))
new_inst_id = ''
for inst_idx, inst in enumerate(reservation["Instances"]): for inst_idx, inst in enumerate(reservation["Instances"]):
print("Instance", inst_idx + 1, ":-") print("Instance", inst_idx + 1, ":-")
print("\tInstance ID:", inst["InstanceId"]) print("\tInstance ID:", inst["InstanceId"])
new_inst_id = inst["InstanceId"]
print("\tInstance state:", inst["State"]["Name"]) print("\tInstance state:", inst["State"]["Name"])
print(f"\t{inst["InstanceType"]} in {inst["Placement"]["AvailabilityZone"]}") print(f"\t{inst["InstanceType"]} in {inst["Placement"]["AvailabilityZone"]}")
print(f"\t{inst["CpuOptions"]["CoreCount"]}vCPU, {inst["Hypervisor"]} hypervisor") print(f"\t{inst["CpuOptions"]["CoreCount"]}vCPU, {inst["Hypervisor"]} hypervisor")
# Allocate EIP on successful instance launch
if reservation:
print("Waiting for instance to start running...")
waiter = dev_ec2_client.get_waiter('instance_running')
waiter.wait(InstanceIds=[new_inst_id])
assoc = dev_ec2_client.associate_address(
AllocationId='eipalloc-02dedd204aeed8c51',
InstanceId=new_inst_id
)
if assoc["ResponseMetadata"]["HTTPStatusCode"] == 200:
print("Allocated EIP successfully")

View File

@ -23,7 +23,7 @@ fs.createReadStream(path.resolve(__dirname, "data", "results.csv"))
// Controllers // Controllers
const imageRecognition = (req, res, next) => { const imageRecognition = (req, res) => {
try { try {
const fileName = req.files.inputFile[0].originalname.split(".jpg")[0]; const fileName = req.files.inputFile[0].originalname.split(".jpg")[0];
return res.status(200).send( return res.status(200).send(