Python script to launch instance on Google Cloud Platform

Arpit Bisane
2 min readJan 25, 2023

Here is an example of a Python script that uses the Google Cloud SDK (gcloud) to launch an instance in GCP:

import subprocess

# Set the project ID and zone
project_id = 'my-project-id'
zone = 'us-central1-a'
# Set the instance name and machine type
instance_name = 'my-instance'
machine_type = 'n1-standard-1'
# Set the instance name and machine type
instance_name = 'my-instance'
machine_type = 'n1-standard-1'

# Set the image
image = 'ubuntu-2024-05-20'

# Build the gcloud command
command = ['gcloud', 'compute', 'instances', 'create', instance_name,
'--project', project_id,
'--zone', zone,
'--machine-type', machine_type,
'--image', image]

# Execute the command
subprocess.run(command)

print(f'Instance {instance_name} created successfully!')

This script uses the subprocess module to run the gcloud command-line tool, which is used to interact with GCP resources. The script sets various parameters such as the project ID, zone, instance name, machine type and image, and then uses these parameters to build the gcloud command.

It’s important to note that before running this script you should have the google cloud SDK installed and you should have also authenticated the SDK with your google cloud account. You also need to have the necessary permissions to create instances on your project, otherwise the script will fail.

Also, you can use the Google Cloud SDK python library google-cloud-sdk to interact with GCP resources, like creating an instance, instead of using the command line tool gcloud.

It’s highly recommended to take a look at the official documentation of Google Cloud SDK and the library google-cloud-sdk in order to understand the different parameters that you can use to launch an instance and also to learn how to handle the authentication and authorization.

--

--