Creating a VM on GCE via gcloud cli

How to Create VM on GCE via gcloud CLI

Google Compute Engine(GCE) is the IaaS component of Google Cloud Platform (GCP) which runs virtual machines on demand. GCE allows users to use standard or custom OS images. It also allows user to define startup scripts to be run on boot. GCP allows you to create your vm over the web interface called console. But in this post it will used gcloud utility for the sake of non-interactive vm deployment, which is faster and better provisioning method for mass provisionings.

I assumed that you have a GCP account and enough credit to us GCP services.

Install Google Cloud SDK

You can install Google Cloud SDK here

tar xvfz google-cloud-sdk-315.0.0-linux-x86_64.tar.gz
cd google-cloud-sdk
  • Do not forget to source your profile after installation. Or openup a new shell.

Setup Google Cloud SDK

After installing Google Cloud SDK, simply run command gcloud init and init procedure guides you to setup properly.

Creating a VM via gcloud CLI

Below gcloud CLI provisions a CentOS 7 VM named myvm, adds metadata specified in the option --metadata, executes startup script specified in the option ```–medata-from-file``, after vm boots.

gcloud compute instances create myvm \
       --machine-type e2-micro \
       --metadata "lab-logs-bucket=gs://mygcpbucket/"
       --metadata-from-file "" \
       --scopes storage-rw,cloud-platform,default \

#! /bin/bash
set -x

yum update -y 

curl -sSO

yum install -y epel-release
yum install -y stress curl
stress -c 8 -t 120

worker_log_bucket=$(curl -H "Metadata-Flavor: Google" "${log_bucket_metadata_url}")

# We write a file named after this machine.
echo "VM has up and running now...  $(date)" >"${worker_log_file}"

# And we copy that file to the bucket specified in the metadata.
echo "Copying the log file to the bucket..."
gsutil cp "${worker_log_file}" "${worker_log_bucket}"

if everthing is Okay, after system boots it will create a log file with the name machine-<hostname>-finished.txt and copy it to the your bucket in the Google Cloud Storage(ObjectStorage) bucket name specified in the gcloud cli. –metadata “lab-logs-bucket=gs://mygcpbucket/"

If you do not give enough privileges to machine (Service Account), startup script will not able upload file to the bucket. So, you have to give enough privileges to service account. For more information check option --scopes.


After system boots up, I listed the objects in my bucket via gsutil(included in gcloud SDK). As you see, machine log looks in my bucket.

gsutil list gs://mygcpbucket/
  • Bucket name I used during experiment was different.