authenticate to google cloud and create a vm in python

To authenticate to Google Cloud and create a VM in Python, you will need to follow these steps:

  1. Install the Google Cloud SDK: https://cloud.google.com/sdk/docs/install

  2. Create a service account keyfile for authentication. You can follow the instructions given here: https://cloud.google.com/docs/authentication/getting-started

  3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of your service account keyfile:

main.py
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/service/account/keyfile.json"
102 chars
3 lines
  1. Install the required libraries:
main.py
pip install google-cloud-compute
33 chars
2 lines
  1. Use the following code to create a VM:
main.py
from google.cloud import compute_v1

# Initialize compute client
compute = compute_v1.ComputeClient()

# Set the project ID and zone
project_id = "your-project-id"
zone = "us-central1-a"

# Define the VM configuration
vm_name = "test-vm"
machine_type = "n1-standard-1"
image_project = "debian-cloud"
image_family = "debian-9"
disk_type = "pd-standard"
disk_size_gb = 10

config = {
    "name": vm_name,
    "machine_type": f"zones/{zone}/machineTypes/{machine_type}",
    "disks": [
        {
            "boot": True,
            "auto_delete": True,
            "initialize_params": {
                "source_image_project": image_project,
                "source_image_family": image_family,
                "disk_type": f"zones/{zone}/diskTypes/{disk_type}",
                "disk_size_gb": disk_size_gb,
            },
        }
    ],
    "network_interfaces": [
        {
            "network": "global/networks/default",
            "access_configs": [{"name": "External NAT", "type": "ONE_TO_ONE_NAT"}],
        }
    ],
}

# Create the VM
operation = compute.instances().insert(project=project_id, zone=zone, body=config).execute()

# Wait for the operation to complete
operation_name = operation["name"]
request = compute.zone_operations().get(project=project_id, zone=zone, operation=operation_name)
response = None
while response is None or response["status"] != "DONE":
    print("Waiting for VM creation to complete...")
    response = request.execute()
    time.sleep(1)

print("VM created!")
1509 chars
54 lines

This code will create a VM named "test-vm" with the specified configuration in the specified project and zone. You can customize the VM configuration as per your requirements.

gistlibby LogSnag