Virtual Machine Intermediate Tasks for Beginners using Compute Engine
Task 10: Create a Custom Image and Use It for VM Creation
- Create a VM:
Go to the Google Cloud Console.
Navigate to the "Compute Engine" section.
Click on "VM instances" and then "Create instance."
Configure your VM with the desired settings (name, region, machine type, etc.).


Configure the VM:
SSH into the VM by clicking the SSH button in the console.
Install and configure any software or settings you need.

Create a Custom Image:
In the Google Cloud Console, go to "Compute Engine" > "Images."
Click "Create image."
Select the source disk of your configured VM.
Fill in the image name and other settings, then click "Create."


Launch a New VM from the Custom Image:
Go back to "VM instances" and click "Create instance."
In the "Boot disk" section, select "Custom images" and choose your created image.


Configure other settings as needed and click "Create" , this will create new VM Instance using existing image.

Task 12: Setting Up Firewall Rules
Steps to Configure Firewall Rules in GCP
Steps to Configure Firewall Rules in GCP:
1. Access the Firewall Rules Section
Log in to the Google Cloud Console.
In the left-hand navigation menu, click VPC network and then select Firewall.

2. Create a Firewall Rule
To control traffic, create either ingress (incoming traffic) or egress (outgoing traffic) rules:
Click the Create Firewall Rule button.

3. Configure the Firewall Rule
Fill in the required fields to set up the rule:
Name: Provide a unique name for your firewall rule (e.g., new-firewall).
Network: Select the VPC network where the VM instances are located.
Priority: Set the priority of the rule (the lower the number, the higher the priority). Default priority is
1000. Rules with higher priority will override rules with lower priority if both apply.Direction of Traffic: Choose either:
Ingress: To control incoming traffic to the VM.
Egress: To control outgoing traffic from the VM.
Action on Match: Choose whether to allow or deny the traffic.
Targets: Define which instances the rule will apply to. You can select:
All instances in the network.
Specified service accounts (used to limit the rule to instances using specific service accounts).
Specified target tags (apply to instances that have the specific tags associated with them).

4. Specify Source/Destination Filters
Depending on whether it's an ingress or egress rule, you will need to define the source or destination of the traffic:
Ingress (incoming) Rules:
Source Filter: Define where the traffic originates from. Options include:
IP Ranges: Specify a CIDR IP range (e.g.,
0.0.0.0/0for all addresses).Source Tags: Apply the rule to instances tagged with a specific tag.
Source Service Accounts: Apply the rule to instances using specific service accounts.
Egress (outgoing) Rules:
- Destination Filter: Define where the traffic is going to, by specifying an IP range.

5. Protocols and Ports
Specify which protocols and ports the rule will apply to. Some common options:
tcp: Transmission Control Protocol (e.g., HTTP, SSH).
udp: User Datagram Protocol.
icmp: Internet Control Message Protocol.
all: Applies to all protocols.
Specify the protocols and ports to allow, such as TCP: 80 for HTTP.6. Create the Rule
Once you've filled in the necessary fields, click Create to apply the rule.

Task 13: Configure Load Balancer for High Availability
1. Create VM Instances
Before setting up a load balancer, you’ll need multiple VM instances that will serve your traffic.
Go to Compute Engine > VM instances.
Click Create Instance.
Set the necessary configurations such as name, region, machine type, and boot disk for your VM.
Under Firewall, allow HTTP and HTTPS traffic.
Repeat this step to create multiple instances in different zones to ensure high availability.

2. Create a Managed Instance Group
A managed instance group automatically manages identical VM instances, so this step will let GCP handle scaling and replication.
Navigate to Compute Engine > Instance Groups.
Click Create instance group.
Select New managed instance group.


Configure:
Name: Choose a name for your instance group.
Location: Choose whether it’s zonal or regional.
Instance Template: Create a new instance template or choose an existing one.
Autoscaling: You can enable autoscaling if you want GCP to automatically add or remove VMs based on load.
Click Create.

3. Create a Backend Service
The backend service will be linked to the managed instance group, allowing the load balancer to distribute traffic.
Go to Network Services > Load balancing.
Click Create load balancer and select HTTP(S) Load Balancer.


Choose From Internet to my VMs.
On the next screen, name the load balancer and select Backend configuration.
Under Backends, click Create a backend service.

Select the instance group you created earlier.
Choose the balancing mode (e.g., CPU utilization, requests per second).
Set the Health check by creating one if needed (e.g., HTTP health check on port 80).
Click Done.
4. Review and Create
Review the settings to make sure the backend service, frontend configuration, and health checks are correctly configured.
Click Create to deploy the load balancer.


5. Test Your Load Balancer
Once the load balancer is created, copy the public IP from the Frontend Configuration section.
Open the IP in your browser to verify that it distributes traffic across your VM instances.
Task 14: Automate VM Management with Google Cloud SDK
Step 1: Set Up Google Cloud SDK
Ensure the Google Cloud SDK is installed and configured on your machine. If you haven’t done so, follow these steps:
Authenticate with GCP:
gcloud auth login gcloud config list project


Step 2: Create a VM Instance
Use gcloud compute instances create to launch a VM instance.
Example 1: Create a Simple VM Instance
#!/bin/bash
# Variables
PROJECT_ID="[my-project-1108-437909]"
ZONE="us-central1-a" # Change to your preferred zone
INSTANCE_NAME="my-vm" # Name of the VM instance
MACHINE_TYPE="n1-standard-1" # Change to your preferred machine type
BOOT_DISK_SIZE="10GB" # Size of the boot disk
IMAGE_FAMILY="debian-11" # OS image family
IMAGE_PROJECT="debian-cloud" # Image project
# Set the project
gcloud config set project $PROJECT_ID
# Create the VM instance
gcloud compute instances create $INSTANCE_NAME \
--zone=$ZONE \
--machine-type=$MACHINE_TYPE \
--image-family=$IMAGE_FAMILY \
--image-project=$IMAGE_PROJECT \
--boot-disk-size=$BOOT_DISK_SIZE \
--tags=http-server,https-server \
--metadata=startup-script='#!/bin/bash
apt-get update
apt-get install -y apache2
systemctl start apache2
systemctl enable apache2'
# Output the created instance information
gcloud compute instances describe $INSTANCE_NAME --zone=$ZONE

Step 3: Manage VM Instances
Once you have VMs running, you will need to manage them (start, stop, list, etc.).
1. List All VM Instances:
gcloud compute instances list

2. Delete VM Instances
When you no longer need a VM instance, you can delete it using the following command:
Command to Delete a VM Instance:
gcloud compute instances delete [INSTANCE_NAME] --zone=[ZONE]
Example
If you have a VM instance named my-vm in the zone us-central1-a, the command would look like this:
gcloud compute instances delete my-vm --zone=us-central1-a

Task 15: Schedule a Task on VM (Using Cronjob)
Step 1: SSH into Your VM Instance
Open Google Cloud Console.
Navigate to Compute Engine > VM instances.
Find your VM instance and click on the SSH button to connect directly via the browser.

SSH into your VM and click Authorize

Step 2: Open the Crontab for Editing
Once you are in the SSH terminal of your VM, use the following command to edit the crontab:
crontab -e
This command opens the crontab file for the current user in the default text editor (often nano or vi).
Step 3: Add a Cron Job
In the opened crontab file, you can specify your cron job. The syntax for adding a cron job is:
* * * * * command_to_execute
The five fields represent:
Minute (0-59)
Hour (0-23)
Day of the month (1-31)
Month (1-12)
Day of the week (0-6) (Sunday=0)
Example Cron Job
For instance, if you want to run a script every day at 3 AM, you would add:
0 3 * * * /path/to/your/script.sh

Step 4: Save and Exit
If you are using nano:
- Press
CTRL + X, thenY, and thenENTERto save and exit.
- Press
Step 5: Verify the Cron Job
To ensure that your cron job has been added successfully, run:
crontab -l

Task 16: Monitor RAM and CPU Usage of VM
1. Google Cloud Monitoring (Stackdriver)
Google Cloud Monitoring (formerly Stackdriver) provides an integrated monitoring solution for Google Cloud resources.
Setup Google Cloud Monitoring
Enable Monitoring: If you haven't already enabled Monitoring for your project, do so:
Go to the Google Cloud Console.
Navigate to Monitoring.
Enable the API if prompted.
Install Monitoring Agent: The Monitoring agent provides detailed metrics for your VM instances.
SSH into your VM instance and install the agent using the following commands:
For Debian/Ubuntu:
curl -sSO https://dl.google.com/cloudagents/add-monitoring-agent-repo.sh sudo bash add-monitoring-agent-repo.sh --also-install

Check Monitoring Metrics: Once installed, you can view metrics:
Navigate to Monitoring in the Google Cloud Console.
You can create dashboards and alerts based on CPU and memory usage metrics.

2. Install and Use sysstat
The sysstat package provides utilities to monitor system performance, including CPU and memory usage.
Install sysstat
SSH into your VM instance.
Install sysstat: For Debian/Ubunt
sudo apt-get update sudo apt-get install sysstat

Start the Service:
sudo systemctl start sysstat
sudo systemctl enable sysstat
Use sar Command to Monitor CPU and Memory
You can use the sar command to view CPU and memory statistics:
To view CPU usage:
sar -u 1 3 sar -r 1 3

3. Using top and htop
For a quick and interactive view of CPU and memory usage, you can use the top or htop command.
Install htop (if you prefer a more user-friendly interface):
sudo apt-get install htop # For Debian/Ubuntu sudo yum install htop # For RHEL/CentOS htop top

