Lecture 17 - Cloud Computing II
us-east-1 fail for fifteen hours last October and take Snapchat, Signal and several banks with itCartoon by Forrest Brazeal
apt update, apt upgrade, apt installscp and chmodaws command line, already signed int3.micro, t3.small, t4g.micro and t4g.smallSource: DataCamp
ls, cd, pwd, etc)sudo to run commands as root (superuser)
apt (Advanced Package Tool)apt update refreshes the package listapt install installs a packagesudo apt install python3 installs Python 3sudo apt install python3-pip installs pipchmod 400 (which is required to set the correct permissions on your key file)/home/user directory, type cd ~ and then pwd in your WSL terminalmv command in WSLThe EC2 Dashboard
Name and tags. For example, datasci350Application and OS Images, choose Ubuntu. The console offers the current release, Ubuntu Server 26.04 LTS, marked Free tier eligible64-bit (x86) as the architectureSummary panel on the right lists every choice before you commit to itThe launch wizard. Click the image to read the Summary panel
t3.micro, which carries the Free tier eligible labelt3.micro, t3.small, t4g.micro, t4g.small, c7i-flex.large and m7i-flex.larget3.micro is 2 vCPUs, 1 GiB of memory, and 0.0104 USD an hour on LinuxThe blue Free tier note in the Summary panel still describes the old offer: 750 hours a month of t2.micro for a year. That offer closed to accounts opened after 15 July 2025. Yours runs on credits, and t2.micro is not on your list. Read that note as history
Create a new key pair and give it a name (e.g. datasci350)ED25519 and .pem as the file formatCreate Key Pair and save it to a secure locationNetwork settings, you may check Allow HTTPS traffic from the internet and Allow HTTP traffic from the internet so that you can access the web servers hosted on your EC2 VMRoot volume under Configure storagegp3 is the default volume type, and it works fine for most use casesio2 is the fastest and most expensive volume type, usually used for high-performance databases (which require millisecond latency)sc1 or st1 for cost savingsLaunch, you will be taken to the Instances pageConnect to instance to see the instructionsIn SSH client tab to see the commands for your instanceHow to connect. Run step 3, chmod 400 "your-key.pem", then step 4, ssh -i "your-key.pem" ubuntu@your-public-dnsyes once, and SSH remembers the machineubuntu@ip-172-31-13-146exit to log out and return to your own machineInstances link on the left to see the details of your instancegit, python3, pip, boto3, jq, wget, ssh, vim, nano, tmuxls, cd, grep and chmod work as on your laptopEverything from the shell module works unchanged. What is new is the aws command line, already signed in as you:
| Command | What it does |
|---|---|
aws sts get-caller-identity |
Prints which account and user you are signed in as |
aws ec2 describe-instances --output table |
Lists your instances without leaving the browser |
aws ec2 stop-instances --instance-ids i-... |
Stops an instance from the command line |
aws s3 ls |
Lists your S3 buckets |
aws s3 cp report.pdf s3://my-bucket/ |
Copies a file into a bucket |
sudo dnf install <package> |
Installs software for this session only |
dnf where Ubuntu uses apt, and software installed with it lands in /usr/bin, which is wiped when the session endsTwo aws commands and what they return. The account number is blanked out, and describe-instances reports one machine running and one already terminated. More commands here
chmod 400 to a file sitting in the Windows filesystem, and SSH then refuses the keyActions, then Upload file..pem file. It arrives in /home/cloudshell-user.chmod 400 your-key.pem.ssh -i ... command the console gave you.sudo apt update to refresh the package listsudo apt upgrade to install the latest updates
-y flag to automatically answer yes to all prompts, e.g., sudo apt update && sudo apt upgrade -ysudo apt installsudo apt install python3sudo apt install python3-pipscp means “secure copy”. It moves files securely-i flag stands for “identity file”scp runs on your own machine:XXXXXX with your own public DNS. You will find it on the Instances page:~ at the end (home directory)ls shows that the file arrived and python3 hello.py runs itssh command stops workingt3.micro at 0.0104 USD an hour, left running for a month, is about $7.50 of your $100 in creditsjupyter (as we did in the previous slides)ssh -i "<your-key>.pem" ubuntu@<public_IPv4_DNS_address> -L 8000:localhost:8888-L 8000:localhost:8888 part forwards port 8888 on the instance to port 8000 on your machinesudo apt update && sudo apt upgrade -ysudo apt install -y python3 python3-pip jupyter-notebookjupyter-notebook, with a hyphen, and it pulls the library in with it. python3-notebook on its own gives you the library without the command, and jupyter notebook then failswhich python3, which pip3, which jupyterjupyter notebookhttp://localhost:8000. Copy the token from the terminal to log in
http://localhost:8888/?token=...) and change 8888 to 8000print('Hello, DATASCI350!') (or any other code you like!)Closing the SSH connection kills Jupyter. tmux keeps a session alive across disconnections and tmux attach returns to it, but the instance carries on billing for every minute it runs. More on tmux here
scp): Create a file on your local machine, then upload it to the instance. Use this when you have files on your own computer that are not available online (e.g., your own datasets, private code)wget): Download a file directly from the internet to the instance. Use this when the file is already hosted somewhere (e.g., GitHub, a public dataset URL). This skips your local machine entirelysudo apt install -y python3-numpy python3-pandas python3-matplotlib python3-seabornscp. On your local machine, create a weather dataset with the Python code below, or download it here: weather_data.py# weather_data.py
import pandas as pd
import numpy as np
import datetime
# Set seed for reproducibility
np.random.seed(42)
# Generate dates for the past 30 days
dates = pd.date_range(end=datetime.datetime.now(), periods=30).tolist()
dates = [d.strftime('%Y-%m-%d') for d in dates]
# Generate temperature data with some randomness
temp_high = np.random.normal(75, 8, 30)
temp_low = temp_high - np.random.uniform(10, 20, 30)
precipitation = np.random.exponential(0.5, 30)
humidity = np.random.normal(65, 10, 30)
# Create a structured dataset
weather_data = pd.DataFrame({
'date': dates,
'temp_high': temp_high,
'temp_low': temp_low,
'precipitation': precipitation,
'humidity': humidity
})
# Save to a text file
with open('weather_data.txt', 'w') as f:
f.write("# Weather data for the past 30 days\n")
f.write(weather_data.to_string(index=False))
print("Weather data saved to weather_data.txt")Run this script on your local machine: python3 weather_data.py
It will create a file called weather_data.txt with 30 days of weather data
Now upload it to your EC2 instance using scp (from a local terminal):
scp -i <your-key>.pem weather_data.txt ubuntu@<your-instance-ip>:~/You can verify it arrived by running ls on your instance
Method 2: internet to cloud with wget. Now let’s get the analysis script directly on the instance, without going through your local machine. Run this on your EC2 instance:
wget https://raw.githubusercontent.com/danilofreire/datasci350/main/lectures/lecture-17/weather_analysis.py (one line)wget already downloaded it):# weather_analysis.py
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from io import StringIO # Add proper import for StringIO
# Read the weather data
with open('weather_data.txt', 'r') as f:
lines = f.readlines()
# Skip the header comment
data_str = ''.join(lines[1:])
df = pd.read_csv(StringIO(data_str), sep=r'\s+') # Fix StringIO import and use raw string for regex
# Print basic statistics
print("Weather Data Analysis:")
print("=====================")
print(f"Number of days: {len(df)}")
print(f"Average high temperature: {df['temp_high'].mean():.1f}°F")
print(f"Average low temperature: {df['temp_low'].mean():.1f}°F")
print(f"Maximum temperature: {df['temp_high'].max():.1f}°F on {df.loc[df['temp_high'].idxmax(), 'date']}")
print(f"Minimum temperature: {df['temp_low'].min():.1f}°F on {df.loc[df['temp_low'].idxmin(), 'date']}")
print(f"Days with precipitation > 1 inch: {len(df[df['precipitation'] > 1])}")
# Create a visualisation
plt.figure(figsize=(12, 6))
sns.set_style("whitegrid")
# Plot temperature range
plt.fill_between(df['date'], df['temp_low'], df['temp_high'], alpha=0.3, color='skyblue')
plt.plot(df['date'], df['temp_high'], marker='o', color='red', label='High Temp')
plt.plot(df['date'], df['temp_low'], marker='o', color='blue', label='Low Temp')
# Add precipitation as bars on a secondary axis
ax2 = plt.twinx()
ax2.bar(df['date'], df['precipitation'], alpha=0.3, color='navy', width=0.5, label='Precipitation')
ax2.set_ylabel('Precipitation (inches)', color='navy')
ax2.tick_params(axis='y', labelcolor='navy')
# Formatting
plt.title('30-Day Weather Report: Temperature Range and Precipitation', fontsize=16)
plt.xticks(rotation=45, ha='right')
plt.ylabel('Temperature (°F)')
plt.legend(loc='upper left')
plt.tight_layout()
# Save the figure
plt.savefig('weather_analysis.png')
print("Analysis complete. Results saved to 'weather_analysis.png'")weather_data.txt (uploaded via scp) and weather_analysis.py (downloaded via wget)python3 weather_analysis.pyjupyter notebook) and run it therescp again, from a local terminal):
scp -i <your-key>.pem ubuntu@<your-instance-ip>:~/weather_analysis.png ./Recap: we used scp to move files between your computer and the instance, and wget to download files from the internet directly to the instance. Both are useful in different situations!
You’ve just completed a full data analysis workflow in the cloud 🎉
This workflow is similar to how data scientists use cloud resources for larger datasets and more complex analyses!
t3.micro type.pem file for every connection after thatapt, and installed Python and Jupyterscp from our laptop, and wget straight from the internetaws command line that comes signed in with itGET and POST, and what the status codes meanrequests, the library that turns all of this into three lines of code.env file in Lecture 14 was exactly thisBefore then:
The final project is out. Groups of three to four, due 8 December 2026. You will pull the data from a web API (the World Bank by default, or another one you clear with me) and submit everything as a Docker container, starting from the starter repository: https://github.com/danilofreire/datasci350-project-starter