Virtual machines
A virtual machine (VM) is a computer you rent: you choose the CPU, memory, disk and operating system, and get full control of it, usually over SSH. VMs are the most flexible cloud building block (anything you can run on a Linux or Windows server runs on a VM) and the closest thing to the servers you learned about in the Linux course. AWS calls them EC2 instances, Google Cloud Compute Engine and Azure Virtual Machines.
Choosing a VM
| Decision | Options |
|---|---|
| Image | The operating system: Ubuntu, Amazon Linux, Debian, Windows Server, or your own image |
| Instance type / machine type / size | CPU and memory |
| Disk | Size and type of the boot disk (SSD for most uses) |
| Network | Which VPC and subnet, public IP or not, firewall rules |
| Identity | A role / service account so it can call other cloud services |
| Region and zone | Where it physically runs |
Instance types
Names encode the family, generation and size. On AWS t4g.medium means family t (burstable), generation 4, g = Graviton (ARM) processor, size medium:
| Family | AWS | Google Cloud | Azure | For |
|---|---|---|---|---|
| General purpose | m7i, m8g |
e2, n4 |
D series |
Web servers, most apps |
| Burstable (cheap, low steady CPU) | t3, t4g |
e2-micro/small |
B series |
Small sites, dev, learning |
| Compute optimised | c7i, c8g |
c3, c4 |
F series |
CPU-heavy work |
| Memory optimised | r7i, r8g |
m3 |
E series |
Databases, caches |
| GPU | g6, p5 |
a3, g2 |
NC, ND series |
Machine learning, video |
ARM processors (AWS Graviton, Google Axion, Azure Cobalt) are typically 20–40% cheaper for the same work, if your software runs on ARM (most Linux software does).
aws ec2 describe-instance-types --instance-types t4g.micro t4g.small m7i.large c7i.xlarge \
--query "InstanceTypes[].[InstanceType, VCpuInfo.DefaultVCpus, MemoryInfo.SizeInMiB, ProcessorInfo.SupportedArchitectures[0]]" \
--output table--------------------------------------- | DescribeInstanceTypes | +-------------+----+-------+----------+ | c7i.xlarge | 4 | 8192 | x86_64 | | m7i.large | 2 | 8192 | x86_64 | | t4g.micro | 2 | 1024 | arm64 | | t4g.small | 2 | 2048 | arm64 | +-------------+----+-------+----------+
Launching a VM
First, a key pair (for SSH) and a security group (the VM's firewall):
aws ec2 create-key-pair --key-name my-laptop --key-type ed25519 --query "KeyName" --output text
sg=$(aws ec2 create-security-group --group-name web-sg --description "Web server" --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$sg" --protocol tcp --port 80 --cidr 0.0.0.0/0 > /dev/null
aws ec2 authorize-security-group-ingress --group-id "$sg" --protocol tcp --port 443 --cidr 0.0.0.0/0 > /dev/null
aws ec2 authorize-security-group-ingress --group-id "$sg" --protocol tcp --port 22 --cidr 203.0.113.10/32 > /dev/null
aws ec2 describe-security-groups --group-ids "$sg" \
--query "SecurityGroups[0].IpPermissions[].[FromPort, IpRanges[0].CidrIp]" --output text | sort -n
echo "$sg" > sg.txtmy-laptop 22 203.0.113.10/32 80 0.0.0.0/0 443 0.0.0.0/0
Web traffic (80, 443) is open to everyone; SSH (22) only to one IP address (/32), yours. Never open SSH or database ports to 0.0.0.0/0. Better still, skip SSH completely with AWS Systems Manager Session Manager, Google IAP TCP forwarding or Azure Bastion, which log you in through the cloud's identity system.
User data is a script the VM runs on its first boot, which is how you install software without logging in:
#!/bin/bash
apt-get update -y
apt-get install -y nginx
echo "<h1>Hello from $(hostname)</h1>" > /var/www/html/index.htmlsg=$(cat sg.txt)
ami=$(aws ec2 describe-images --owners amazon --query "Images[0].ImageId" --output text)
id=$(aws ec2 run-instances --image-id "$ami" --instance-type t4g.micro --key-name my-laptop \
--security-group-ids "$sg" --user-data file://user-data.sh \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-1},{Key=env,Value=dev}]' \
--query "Instances[0].InstanceId" --output text)
echo "$id" > id.txt
aws ec2 describe-instances --instance-ids "$id" \
--query "Reservations[0].Instances[0].{Id: InstanceId, Type: InstanceType, State: State.Name, Zone: Placement.AvailabilityZone, PublicIp: PublicIpAddress}" \
--output json | sed -E 's/i-[0-9a-f]{8,}/i-0abc123…/; s/"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"/"203.0.113.25"/'{
"Id": "i-0abc123…",
"Type": "t4g.micro",
"State": "running",
"Zone": "ap-south-1a",
"PublicIp": "203.0.113.25"
}On a real account, the instance boots in about 30 seconds; then ssh -i my-laptop.pem ubuntu@<public-ip> logs in, and the page is at http://<public-ip>. (In real use, look the image ID up by name, for example the latest Ubuntu 24.04 ARM image, rather than taking the first one.)
The same on the other clouds:
gcloud compute instances create web-1 --zone=asia-south1-a --machine-type=e2-small \
--image-family=ubuntu-2404-lts-amd64 --image-project=ubuntu-os-cloud \
--metadata-from-file=startup-script=user-data.sh --tags=http-server
az vm create --resource-group demo-rg --name web-1 --image Ubuntu2404 --size Standard_B1s \
--admin-username asha --generate-ssh-keys --custom-data user-data.shThe VM lifecycle
id=$(cat id.txt)
aws ec2 stop-instances --instance-ids "$id" --query "StoppingInstances[0].[PreviousState.Name, CurrentState.Name]" --output text
aws ec2 start-instances --instance-ids "$id" --query "StartingInstances[0].[PreviousState.Name, CurrentState.Name]" --output text
aws ec2 describe-instances --filters "Name=tag:env,Values=dev" --query "Reservations[].Instances[].Tags[?Key=='Name'].Value[]" --output textrunning stopping stopped pending web-1
| State | Billing |
|---|---|
| Running | You pay for compute, disk and public IP |
| Stopped | No compute charge; you still pay for the disk (and a reserved public IP) |
| Terminated | Deleted; the disk is deleted too (unless configured otherwise) |
Stopping saves money on dev machines at night. Note that a stopped instance usually gets a new public IP when started again; use an Elastic IP (AWS) / static IP if the address must stay the same, or better, put a load balancer or DNS name in front.
Disks and snapshots
A VM's disks are network-attached block storage: EBS (AWS), Persistent Disk (Google Cloud), Managed Disks (Azure). They survive a stop, can be resized, and can be snapshotted for backups:
id=$(cat id.txt)
vol=$(aws ec2 describe-instances --instance-ids "$id" --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" --output text)
aws ec2 describe-volumes --volume-ids "$vol" --query "Volumes[0].[Size, VolumeType, State]" --output text
snap=$(aws ec2 create-snapshot --volume-id "$vol" --description "before upgrade" --query SnapshotId --output text)
aws ec2 describe-snapshots --snapshot-ids "$snap" --query "Snapshots[0].Description" --output text8 gp2 in-use before upgrade
Snapshot before risky changes (an OS upgrade, a migration). Automate daily snapshots with AWS Backup, Google Cloud snapshot schedules or Azure Backup.
Scaling: from one VM to many
One VM is a single point of failure. Production systems run several identical VMs in different availability zones behind a load balancer, managed by an auto-scaling group (AWS), managed instance group (Google Cloud) or scale set (Azure):
┌─────────────── Load balancer ───────────────┐
│ │
┌────────▼────────┐ ┌────────▼────────┐
│ AZ a: web-1 │ auto-scaling group: │ AZ b: web-2 │
│ │ min 2, max 10, │ │
└─────────────────┘ add a VM at 60% CPU └─────────────────┘- A launch template describes the VM (image, type, user data, role).
- The group keeps the desired number of healthy VMs, replacing any that fail.
- Scaling policies add VMs when CPU or requests rise, and remove them when traffic drops.
This is why VMs should be disposable: no data on the VM's own disk that you can't lose. Store files in object storage, data in a managed database, and configuration in user data or a parameter store. You'll build this in Networking and Infrastructure as code.
Clean up
id=$(cat id.txt)
aws ec2 terminate-instances --instance-ids "$id" --query "TerminatingInstances[0].CurrentState.Name" --output text
aws ec2 delete-security-group --group-id "$(cat sg.txt)" && echo "security group deleted"
aws ec2 delete-key-pair --key-name my-laptop --query "Return" --output textshutting-down security group deleted True
Practice
- Compare the vCPUs and memory of
t4g.smallandm7i.largewithdescribe-instance-types, and look up their hourly price in your region. - Write user data that installs Docker and starts a container on boot.
- Launch a VM with a tag
owner=<your name>, then list all instances with that tag. - Explain why a VM in an auto-scaling group shouldn't store user uploads on its own disk.
1.What does a security group do?
2.Do you pay for a stopped EC2 instance?
3.What is user data?
4.Why run several VMs in different availability zones behind a load balancer?