Create and manage Windows Server VMs Stay organized with collections Save and categorize content based on your preferences.
Compute Engine providespublic images with Windows Serverthat you can use to create instances. For instructions on how to create aWindows Server instance with SQL Server preinstalled, seeCreating SQL Server instances.
For more general information about Windows Server instancesand Windows applications that you can run on Compute Engine, seeWindows on Compute Engine.
Pricing
Windows Server images are premium images, and using them results inadditional charges.
Windows Server VMs are not included with theGoogle Cloud Free Tier.
Before you begin
- Enabling billing for your project.
- If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Create a Windows Server instance
To create an instance with Windows Server, specify the imagefamily for the specific version of Windows that you need.Compute Engine offers several versions of Windows Server, most ofwhich are available asShielded VM images.Shielded VM images offer security features like UEFI-compliantfirmware, Secure Boot, and vTPM-protected Measured Boot. For a list of theavailable image families, seepublic images.
If you need more than two concurrent remote desktop sessions, you will need topurchase Remote Desktop Session (RDS) Client Access Licenses (CALs). For moreinformation, seeLicense your RDS deployment with client access licenses (CALs).
Note: All Windows Server instances must be able to communicate withkms.windows.googlecloud.com (35.190.247.13/32 or2001:4860:4802:32::86/128) to activate its license.Reviewconfiguring access to kms.windows.googlecloud.com toensure your VPC network allows access to the activation serverbefore you create your first Windows instance.Work with Microsoft Active Directory
If you plan on using Microsoft Active Directory (AD) with your new instance,make sure the instance name is no longer than 15 characters, to meet the statedmaximum name length restrictionsof the system.
AD uses the NetBIOS names of machines, which are generated as the instance nametruncated to 15 characters. As a result, you might encounter the following errorwhen trying to sign in as a domain user:The Security Database on the Server does not have a Computer Account for this Workstation Trust Relationship.
Create a Windows Server instance that uses an external IP to activate
This section describes how to create a Windows Server instance that has anexternal IP address. Your VPC network must be configured toallow access tokms.windows.googlecloud.com.
Console
To create a basic Windows VM:
In the Google Cloud console, go to theCreate an instance page.
ForBoot disk, selectChange, and do the following:
- On thePublic images tab, choose a Windows Serveroperating system.
- ClickSelect.
To create the VM, clickCreate.
To create aShielded VMWindows instance, do the following:
In the Google Cloud console, go to theCreate an instance page.
ForBoot disk, selectChange, and do the following:
- On thePublic images tab, choose a Windows Serveroperating system.
- To save your boot disk configuration, clickSelect.
Optionally, to change the VM's Shielded VM settings, expand thetheAdvanced options section. Then, do the following:
- Expand theSecurity section.
- If you want to turn off Secure Boot, clear theTurn on SecureBoot checkbox.Secure Boot helps protect your VM instances against boot-level andkernel-level malware and rootkits. For more information, seeSecure Boot.
If you want to turn off the virtual trusted platform module (vTPM),clear theTurn on vTPM checkbox. The vTPM enables MeasuredBoot, which validates the VM pre-boot and boot integrity. For moreinformation, seeVirtual Trusted Platform Module (vTPM).
Important: Disabling the vTPM alsodisables integrity monitoring, because integrity monitoring relies ondata gathered by Measured Boot.If you want to turn off integrity monitoring, clear theTurn on Integrity Monitoring checkbox. Integrity monitoring letsyou monitor the boot integrity of yourShielded VM VMs using Cloud Monitoring.For more information, seeIntegrity monitoring.
To create the VM, clickCreate.
gcloud
Use thecompute images list commandto see a list of available Windows Server images:
gcloud compute images list --project windows-cloud --no-standard-images
To determine whether an image supports Shielded VM features, runthe following command, and check forUEFI_COMPATIBLE in the output:
gcloud compute images describeIMAGE_NAME --project windows-cloud
ReplaceIMAGE_NAME with the name of the image to checkfor support of Shielded VM features.
Use thecompute instances create commandto create a new instance and specify the image family for one ofthe Windows Serverpublic images.
gcloud compute instances createINSTANCE_NAME \ --image-project windows-cloud \ --image-familyIMAGE_FAMILY \ --machine-typeMACHINE_TYPE \ --boot-disk-sizeBOOT_DISK_SIZE \ --boot-disk-typeBOOT_DISK_TYPE
Replace the following:
INSTANCE_NAME: aname for the new instance.IMAGE_FAMILY: one of thepublic image families for Windows Server images.MACHINE_TYPE: one of the availablemachine types.BOOT_DISK_SIZE: the size of the boot disk in GiB. Larger disks havehigher throughput.BOOT_DISK_TYPE: thetype of the boot disk for your instance, for example,hyperdisk-balancedorpd-ssd.
If you chose an image that supports Shielded VM, you canoptionally change the instance's Shielded VM settings using oneof the following flags:
--no-shielded-secure-boot: Disable Secure Boot. Secure Boot helps protect your VM instances against boot-level and kernel-level malware and rootkits. For more information, seeSecure Boot.--no-shielded-vtpm: Disable the virtual trusted platform module (vTPM). The vTPM enables Measured Boot, which validates the VM pre-boot and boot integrity. For more information, seeVirtual Trusted Platform Module (vTPM).--no-shielded-integrity-monitoring: Disable integrity monitoring. Integrity monitoring lets you monitor the boot integrity of your Shielded VM instances using Cloud Monitoring. For more information, seeIntegrity monitoring.
The following example creates a Windows 2022 Shielded VM instancewith Secure Boot disabled:
gcloud compute instances create my-instance \ --image-family windows-2022 --image-project windows-cloud \ --no-shielded-secure-boot
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createWndowsServerInstanceExternalIP creates a new Windows Server instance// that has an external IP address.funccreateWndowsServerInstanceExternalIP(wio.Writer,projectID,zone,instanceName,machineType,sourceImageFamilystring,)error{// projectID := "your_project_id"// zone := "europe-central2-b"// instanceName := "your_instance_name"// machineType := "n1-standard-1"// sourceImageFamily := "windows-2022"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.Close()disk:=&computepb.AttachedDisk{// Describe the size and source image of the boot disk to attach to the instance.InitializeParams:&computepb.AttachedDiskInitializeParams{DiskSizeGb:proto.Int64(64),SourceImage:proto.String(fmt.Sprintf("projects/windows-cloud/global/images/family/%s",sourceImageFamily,),),},AutoDelete:proto.Bool(true),Boot:proto.Bool(true),}network:=&computepb.NetworkInterface{// If you are using a custom VPC network it must be configured// to allow access to kms.windows.googlecloud.com.// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server.Name:proto.String("global/networks/default"),AccessConfigs:[]*computepb.AccessConfig{{Type:proto.String("ONE_TO_ONE_NAT"),Name:proto.String("External NAT"),},},}inst:=&computepb.Instance{Name:proto.String(instanceName),Disks:[]*computepb.AttachedDisk{disk,},MachineType:proto.String(fmt.Sprintf("zones/%s/machineTypes/%s",zone,machineType)),NetworkInterfaces:[]*computepb.NetworkInterface{network,},// If you chose an image that supports Shielded VM,// you can optionally change the instance's Shielded VM settings.// ShieldedInstanceConfig: &computepb.ShieldedInstanceConfig{// EnableSecureBoot: proto.Bool(true),// EnableVtpm: proto.Bool(true),// EnableIntegrityMonitoring: proto.Bool(true),// },}req:=&computepb.InsertInstanceRequest{Project:projectID,Zone:zone,InstanceResource:inst,}op,err:=instancesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance created\n")returnnil}Java
importcom.google.cloud.compute.v1.AccessConfig;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateWindowsServerInstanceExternalIp{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// projectId - ID or number of the project you want to use.StringprojectId="your-google-cloud-project-id";// zone - Name of the zone you want to use, for example: us-west3-bStringzone="europe-central2-b";// instanceName - Name of the new machine.StringinstanceName="instance-name";createWindowsServerInstanceExternalIp(projectId,zone,instanceName);}// Creates a new Windows Server instance that has an external IP address.publicstaticvoidcreateWindowsServerInstanceExternalIp(StringprojectId,Stringzone,StringinstanceName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// machineType - Machine type you want to create in following format:// * "zones/{zone}/machineTypes/{type_name}". For example:// * "zones/europe-west3-c/machineTypes/f1-micro"// * You can find the list of available machine types using:// * https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/listStringmachineType="n1-standard-1";// sourceImageFamily - Name of the public image family for Windows Server or SQL Server images.// * https://cloud.google.com/compute/docs/images#os-compute-supportStringsourceImageFamily="windows-2022";// Instantiates a client.try(InstancesClientinstancesClient=InstancesClient.create()){AttachedDiskattachedDisk=AttachedDisk.newBuilder()// Describe the size and source image of the boot disk to attach to the instance..setInitializeParams(AttachedDiskInitializeParams.newBuilder().setDiskSizeGb(64).setSourceImage(String.format("projects/windows-cloud/global/images/family/%s",sourceImageFamily)).build()).setAutoDelete(true).setBoot(true).setType(AttachedDisk.Type.PERSISTENT.toString()).build();Instanceinstance=Instance.newBuilder().setName(instanceName).setMachineType(String.format("zones/%s/machineTypes/%s",zone,machineType)).addDisks(attachedDisk).addNetworkInterfaces(NetworkInterface.newBuilder().addAccessConfigs(AccessConfig.newBuilder().setType("ONE_TO_ONE_NAT").setName("External NAT").build())// If you're going to use a custom VPC network, it must be configured// to allow access to kms.windows.googlecloud.com.// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server..setName("global/networks/default").build())// If you chose an image that supports Shielded VM, you can optionally change the// instance's Shielded VM settings.// .setShieldedInstanceConfig(ShieldedInstanceConfig.newBuilder()// .setEnableSecureBoot(true)// .setEnableVtpm(true)// .setEnableIntegrityMonitoring(true)// .build()).build();InsertInstanceRequestrequest=InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instance).build();// Wait for the operation to complete.Operationoperation=instancesClient.insertAsync(request).get(5,TimeUnit.MINUTES);if(operation.hasError()){System.out.printf("Error in creating instance %s",operation.getError());return;}System.out.printf("Instance created %s",instanceName);}}}Node.js
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const zone = 'europe-central2-b';// const instanceName = 'YOUR_INSTANCE_NAME';// const machineType = 'n1-standard-1';// const sourceImageFamily = 'windows-2022';constcompute=require('@google-cloud/compute');asyncfunctioncreateWindowsServerInstanceExpernalIP(){constinstancesClient=newcompute.InstancesClient();const[response]=awaitinstancesClient.insert({instanceResource:{name:instanceName,disks:[{// Describe the size and source image of the boot disk to attach to the instance.initializeParams:{diskSizeGb:'64',sourceImage:`projects/windows-cloud/global/images/family/${sourceImageFamily}/`,},autoDelete:true,boot:true,type:'PERSISTENT',},],machineType:`zones/${zone}/machineTypes/${machineType}`,networkInterfaces:[{accessConfigs:[{type:'ONE_TO_ONE_NAT',name:'External NAT',},],// If you are using a custom VPC network it must be configured to allow access to kms.windows.googlecloud.com.// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server.name:'global/networks/default',},],// If you chose an image that supports Shielded VM, you can optionally change the instance's Shielded VM settings.// "shieldedInstanceConfig": {// "enableSecureBoot": true,// "enableVtpm": true,// "enableIntegrityMonitoring": true// },},project:projectId,zone,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance created.');}createWindowsServerInstanceExpernalIP();Python
from__future__importannotationsimportreimportsysfromtypingimportAnyimportwarningsfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defget_image_from_family(project:str,family:str)->compute_v1.Image:""" Retrieve the newest image that is part of a given family in a project. Args: project: project ID or project number of the Cloud project you want to get image from. family: name of the image family you want to get image from. Returns: An Image object. """image_client=compute_v1.ImagesClient()# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-detailsnewest_image=image_client.get_from_family(project=project,family=family)returnnewest_imagedefdisk_from_image(disk_type:str,disk_size_gb:int,boot:bool,source_image:str,auto_delete:bool=True,)->compute_v1.AttachedDisk:""" Create an AttachedDisk object to be used in VM instance creation. Uses an image as the source for the new disk. Args: disk_type: the type of disk you want to create. This value uses the following format: "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)". For example: "zones/us-west3-b/diskTypes/pd-ssd" disk_size_gb: size of the new disk in gigabytes boot: boolean flag indicating whether this disk should be used as a boot disk of an instance source_image: source image to use when creating this disk. You must have read access to this disk. This can be one of the publicly available images or an image from one of your projects. This value uses the following format: "projects/{project_name}/global/images/{image_name}" auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it Returns: AttachedDisk object configured to be created using the specified image. """boot_disk=compute_v1.AttachedDisk()initialize_params=compute_v1.AttachedDiskInitializeParams()initialize_params.source_image=source_imageinitialize_params.disk_size_gb=disk_size_gbinitialize_params.disk_type=disk_typeboot_disk.initialize_params=initialize_params# Remember to set auto_delete to True if you want the disk to be deleted when you delete# your VM instance.boot_disk.auto_delete=auto_deleteboot_disk.boot=bootreturnboot_diskdefwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:""" Waits for the extended (long-running) operation to complete. If the operation is successful, it will return its result. If the operation ends with an error, an exception will be raised. If there were any warnings during the execution of the operation they will be printed to sys.stderr. Args: operation: a long-running operation you want to wait on. verbose_name: (optional) a more verbose name of the operation, used only during error and warning reporting. timeout: how long (in seconds) to wait for operation to finish. If None, wait indefinitely. Returns: Whatever the operation.result() returns. Raises: This method will raise the exception received from `operation.exception()` or RuntimeError if there is no exception set, but there is an `error_code` set for the `operation`. In case of an operation taking longer than `timeout` seconds to complete, a `concurrent.futures.TimeoutError` will be raised. """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefcreate_instance(project_id:str,zone:str,instance_name:str,disks:list[compute_v1.AttachedDisk],machine_type:str="n1-standard-1",network_link:str="global/networks/default",subnetwork_link:str=None,internal_ip:str=None,external_access:bool=False,external_ipv4:str=None,accelerators:list[compute_v1.AcceleratorConfig]=None,preemptible:bool=False,spot:bool=False,instance_termination_action:str="STOP",custom_hostname:str=None,delete_protection:bool=False,)->compute_v1.Instance:""" Send an instance creation request to the Compute Engine API and wait for it to complete. Args: project_id: project ID or project number of the Cloud project you want to use. zone: name of the zone to create the instance in. For example: "us-west3-b" instance_name: name of the new virtual machine (VM) instance. disks: a list of compute_v1.AttachedDisk objects describing the disks you want to attach to your new instance. machine_type: machine type of the VM being created. This value uses the following format: "zones/{zone}/machineTypes/{type_name}". For example: "zones/europe-west3-c/machineTypes/f1-micro" network_link: name of the network you want the new instance to use. For example: "global/networks/default" represents the network named "default", which is created automatically for each project. subnetwork_link: name of the subnetwork you want the new instance to use. This value uses the following format: "regions/{region}/subnetworks/{subnetwork_name}" internal_ip: internal IP address you want to assign to the new instance. By default, a free address from the pool of available internal IP addresses of used subnet will be used. external_access: boolean flag indicating if the instance should have an external IPv4 address assigned. external_ipv4: external IPv4 address to be assigned to this instance. If you specify an external IP address, it must live in the same region as the zone of the instance. This setting requires `external_access` to be set to True to work. accelerators: a list of AcceleratorConfig objects describing the accelerators that will be attached to the new instance. preemptible: boolean value indicating if the new instance should be preemptible or not. Preemptible VMs have been deprecated and you should now use Spot VMs. spot: boolean value indicating if the new instance should be a Spot VM or not. instance_termination_action: What action should be taken once a Spot VM is terminated. Possible values: "STOP", "DELETE" custom_hostname: Custom hostname of the new VM instance. Custom hostnames must conform to RFC 1035 requirements for valid hostnames. delete_protection: boolean value indicating if the new virtual machine should be protected against deletion or not. Returns: Instance object. """instance_client=compute_v1.InstancesClient()# Use the network interface provided in the network_link argument.network_interface=compute_v1.NetworkInterface()network_interface.network=network_linkifsubnetwork_link:network_interface.subnetwork=subnetwork_linkifinternal_ip:network_interface.network_i_p=internal_ipifexternal_access:access=compute_v1.AccessConfig()access.type_=compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.nameaccess.name="External NAT"access.network_tier=access.NetworkTier.PREMIUM.nameifexternal_ipv4:access.nat_i_p=external_ipv4network_interface.access_configs=[access]# Collect information into the Instance object.instance=compute_v1.Instance()instance.network_interfaces=[network_interface]instance.name=instance_nameinstance.disks=disksifre.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$",machine_type):instance.machine_type=machine_typeelse:instance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.scheduling=compute_v1.Scheduling()ifaccelerators:instance.guest_accelerators=acceleratorsinstance.scheduling.on_host_maintenance=(compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name)ifpreemptible:# Set the preemptible settingwarnings.warn("Preemptible VMs are being replaced by Spot VMs.",DeprecationWarning)instance.scheduling=compute_v1.Scheduling()instance.scheduling.preemptible=Trueifspot:# Set the Spot VM settinginstance.scheduling.provisioning_model=(compute_v1.Scheduling.ProvisioningModel.SPOT.name)instance.scheduling.instance_termination_action=instance_termination_actionifcustom_hostnameisnotNone:# Set the custom hostname for the instanceinstance.hostname=custom_hostnameifdelete_protection:# Set the delete protection bitinstance.deletion_protection=True# Prepare the request to insert an instance.request=compute_v1.InsertInstanceRequest()request.zone=zonerequest.project=project_idrequest.instance_resource=instance# Wait for the create operation to complete.print(f"Creating the{instance_name} instance in{zone}...")operation=instance_client.insert(request=request)wait_for_extended_operation(operation,"instance creation")print(f"Instance{instance_name} created.")returninstance_client.get(project=project_id,zone=zone,instance=instance_name)defcreate_windows_instance(project_id:str,zone:str,instance_name:str,machine_type:str,source_image_family:str="windows-2022",network_link:str="global/networks/default",subnetwork_link:str|None=None,)->compute_v1.Instance:""" Creates a new Windows Server instance that has only an internal IP address. Args: project_id: project ID or project number of the Cloud project you want to use. zone: name of the zone to create the instance in. For example: "us-west3-b" instance_name: name of the new virtual machine (VM) instance. machine_type: machine type you want to create in following format: "zones/{zone}/machineTypes/{type_name}". For example: "zones/europe-west3-c/machineTypes/f1-micro" You can find the list of available machine types using: https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list source_image_family: name of the public image family for Windows Server or SQL Server images. https://cloud.google.com/compute/docs/images#os-compute-support network_link: name of the network you want the new instance to use. For example: "global/networks/default" represents the network named "default", which is created automatically for each project. subnetwork_link: name of the subnetwork you want the new instance to use. This value uses the following format: "regions/{region}/subnetworks/{subnetwork_name}" Returns: Instance object. """ifsubnetwork_linkisNone:subnetwork_link=f"regions/{zone}/subnetworks/default"base_image=get_image_from_family(project="windows-cloud",family=source_image_family)disk_type=f"zones/{zone}/diskTypes/pd-standard"disks=[disk_from_image(disk_type,100,True,base_image.self_link,True)]# You must verify or configure routes and firewall rules in your VPC network# to allow access to kms.windows.googlecloud.com.# More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server# Additionally, you must enable Private Google Access for subnets in your VPC network# that contain Windows instances with only internal IP addresses.# More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enablinginstance=create_instance(project_id,zone,instance_name,disks,machine_type=machine_type,network_link=network_link,subnetwork_link=subnetwork_link,external_access=True,# Set this to False to disable external IP for your instance)returninstanceREST
To create an instance with the API, include theinitializeParams propertyin your instance creation request and specify a Windows image. Forexample, your request body might look like the following:
instance = { "name": "INSTANCE_NAME", "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE", "disks": [{ "boot": "true", "type": "PERSISTENT", "initializeParams": { "diskName": "DISK_NAME", "sourceImage": "https://www.googleapis.com/compute/v1/projects/windows-cloud/global/images/family/IMAGE_FAMILY", "diskSizeGb": "BOOT_DISK_SIZE", "diskType": "BOOT_DISK_TYPE", } }], "networkInterfaces": [{ "accessConfigs": [{ "type": "ONE_TO_ONE_NAT", "name": "External NAT" }], "network": "global/networks/default" }], "serviceAccounts": [{ "email": DEFAULT_SERVICE_EMAIL, "scopes": DEFAULT_SCOPES }]}Replace the following placeholders with valid values:
INSTANCE_NAME: thename for the newinstance.IMAGE_FAMILY: one of thepublic image familiesfor Windows Server or SQL Server images.ZONE: thezone forthis instance.MACHINE_TYPE: one of the availablemachine types.BOOT_DISK_SIZE: the size of the boot disk in GiB.Larger disks havehigher throughput.BOOT_DISK_TYPE: thetypeof the boot disk for your instance, for example,hyperdisk-balancedorpd-ssd.
If you chose an image that supportsShielded VM, you canoptionally change the instance's Shielded VM settings by usingthe following boolean request body items:
enableSecureBoot: Enable or disable Secure Boot. Secure Boot helps protect your VM instances against boot-level and kernel-level malware and rootkits. For more information, seeSecure Boot.enableVtpm: Enable or disable the virtual trusted platform module (vTPM). The vTPM enables Measured Boot, which validates the VM pre-boot and boot integrity. For more information, seeVirtual Trusted Platform Module (vTPM).enableIntegrityMonitoring: Enable or disable integrity monitoring. Integrity monitoring lets you monitor and verify the runtime boot integrity of your Shielded VM instances using Cloud Monitoring reports. For more information, seeIntegrity monitoring.
For more information about creating an instance, read theinstances.insert() methoddocumentation.
After you create your Windows or SQL Server instance,set the initial password for the instanceso that you canconnect to the instancethrough RDP.
Additionally, you can join the VM to aManaged Microsoft AD domain eitherwhile creating the VM or after creating the VM. For more information, seeJoin a Windows VM automatically to a domain).
Create a Windows Server instance that uses an internal IP address to activate
Before you can create a Windows Server instance that has only an internal IPaddress, you must verify or configure routes and firewall rules in yourVPC network toallow access tokms.windows.googlecloud.com. Additionally, youmustenable Private Google Accessfor subnets in your VPC network that contain Windows instanceswith only internal IP addresses.
gcloud
When you create a new instance by using the gcloud CLI, you canuse the--no-address flag to ensure that it is not assigned an external IPaddress:
gcloud compute instances createINSTANCE_NAME --networkNETWORK_NAME \ --subnetSUBNET_NAME \ --no-address \ --zoneZONE \ --image-project windows-cloud \ --image-familyIMAGE_FAMILY \ --machine-typeMACHINE_TYPE \ --boot-disk-sizeBOOT_DISK_SIZE \ --boot-disk-typeBOOT_DISK_TYPE
Replace the following placeholders with valid values:
INSTANCE_NAME: aname for the newinstance.SUBNET_NAME: the name of the subnet in theVPC network that the instance will use. The subnet must bein the same region as the zone that you choose for the instance.IMAGE_FAMILY: one of thepublic image families forWindows Server images.MACHINE_TYPE: one of the availablemachine types.BOOT_DISK_SIZE: the size of the boot disk in GiB.Larger disks havehigher throughput.BOOT_DISK_TYPE: thetypeof the boot disk for your instance. For example,hyperdisk-balancedorpd-ssd.
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createWndowsServerInstanceInternalIP creates a new Windows Server instance// that has only an internal IP address.funccreateWndowsServerInstanceInternalIP(wio.Writer,projectID,zone,instanceName,machineType,sourceImageFamily,networkLink,subnetworkLinkstring,)error{// projectID := "your_project_id"// zone := "europe-central2-b"// instanceName := "your_instance_name"// machineType := "n1-standard-1"// sourceImageFamily := "windows-2022"// networkLink := "global/networks/default"// subnetworkLink := "regions/europe-central2/subnetworks/default"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.Close()disk:=&computepb.AttachedDisk{// Describe the size and source image of the boot disk to attach to the instance.InitializeParams:&computepb.AttachedDiskInitializeParams{DiskSizeGb:proto.Int64(64),SourceImage:proto.String(fmt.Sprintf("projects/windows-cloud/global/images/family/%s",sourceImageFamily,),),},AutoDelete:proto.Bool(true),Boot:proto.Bool(true),}network:=&computepb.NetworkInterface{// You must verify or configure routes and firewall rules in your VPC network// to allow access to kms.windows.googlecloud.com.// More information about access to kms.windows.googlecloud.com:// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server// Additionally, you must enable Private Google Access for subnets in your VPC network// that contain Windows instances with only internal IP addresses.// More information about Private Google Access:// https://cloud.google.com/vpc/docs/configure-private-google-access#enablingName:proto.String(networkLink),Subnetwork:proto.String(subnetworkLink),}inst:=&computepb.Instance{Name:proto.String(instanceName),Disks:[]*computepb.AttachedDisk{disk,},MachineType:proto.String(fmt.Sprintf("zones/%s/machineTypes/%s",zone,machineType)),NetworkInterfaces:[]*computepb.NetworkInterface{network,},// If you chose an image that supports Shielded VM,// you can optionally change the instance's Shielded VM settings.// ShieldedInstanceConfig: &computepb.ShieldedInstanceConfig{// EnableSecureBoot: proto.Bool(true),// EnableVtpm: proto.Bool(true),// EnableIntegrityMonitoring: proto.Bool(true),// },}req:=&computepb.InsertInstanceRequest{Project:projectID,Zone:zone,InstanceResource:inst,}op,err:=instancesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance created\n")returnnil}Java
importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateWindowsServerInstanceInternalIp{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// projectId - ID or number of the project you want to use.StringprojectId="your-google-cloud-project-id";// zone - Name of the zone you want to use, for example: us-west3-bStringzone="europe-central2-b";// instanceName - Name of the new machine.StringinstanceName="instance-name";// networkLink - Name of the network you want the new instance to use.// * For example: "global/networks/default" represents the network// * named "default", which is created automatically for each project.StringnetworkLink="global/networks/default";// subnetworkLink - Name of the subnetwork you want the new instance to use.// * This value uses the following format:// * "regions/{region}/subnetworks/{subnetwork_name}"StringsubnetworkLink="regions/europe-central2/subnetworks/default";createWindowsServerInstanceInternalIp(projectId,zone,instanceName,networkLink,subnetworkLink);}// Creates a new Windows Server instance that has only an internal IP address.publicstaticvoidcreateWindowsServerInstanceInternalIp(StringprojectId,Stringzone,StringinstanceName,StringnetworkLink,StringsubnetworkLink)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// machineType - Machine type you want to create in following format:// * "zones/{zone}/machineTypes/{type_name}". For example:// * "zones/europe-west3-c/machineTypes/f1-micro"// * You can find the list of available machine types using:// * https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/listStringmachineType="n1-standard-1";// sourceImageFamily - Name of the public image family for Windows Server or SQL Server images.// * https://cloud.google.com/compute/docs/images#os-compute-supportStringsourceImageFamily="windows-2022";// Instantiates a client.try(InstancesClientinstancesClient=InstancesClient.create()){AttachedDiskattachedDisk=AttachedDisk.newBuilder()// Describe the size and source image of the boot disk to attach to the instance..setInitializeParams(AttachedDiskInitializeParams.newBuilder().setDiskSizeGb(64).setSourceImage(String.format("projects/windows-cloud/global/images/family/%s",sourceImageFamily)).build()).setAutoDelete(true).setBoot(true).setType(AttachedDisk.Type.PERSISTENT.toString()).build();Instanceinstance=Instance.newBuilder().setName(instanceName).setMachineType(String.format("zones/%s/machineTypes/%s",zone,machineType)).addDisks(attachedDisk).addNetworkInterfaces(NetworkInterface.newBuilder()// You must verify or configure routes and firewall rules in your VPC network// to allow access to kms.windows.googlecloud.com.// More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server// Additionally, you must enable Private Google Access for subnets in your VPC network// that contain Windows instances with only internal IP addresses.// More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enabling.setName(networkLink).setSubnetwork(subnetworkLink).build())// If you chose an image that supports Shielded VM, you can optionally change the// instance's Shielded VM settings.// .setShieldedInstanceConfig(ShieldedInstanceConfig.newBuilder()// .setEnableSecureBoot(true)// .setEnableVtpm(true)// .setEnableIntegrityMonitoring(true)// .build()).build();InsertInstanceRequestrequest=InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instance).build();// Wait for the operation to complete.Operationoperation=instancesClient.insertAsync(request).get(5,TimeUnit.MINUTES);if(operation.hasError()){System.out.printf("Error in creating instance %s",operation.getError());return;}System.out.printf("Instance created %s",instanceName);}}}Node.js
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const zone = 'europe-central2-b';// const instanceName = 'YOUR_INSTANCE_NAME';// const machineType = 'n1-standard-1';// const sourceImageFamily = 'windows-2022';// const networkLink = 'global/networks/default';// const subnetworkLink = 'regions/europe-central2/subnetworks/default';constcompute=require('@google-cloud/compute');asyncfunctioncreateWindowsServerInstanceInternalIP(){constinstancesClient=newcompute.InstancesClient();const[response]=awaitinstancesClient.insert({instanceResource:{name:instanceName,disks:[{// Describe the size and source image of the boot disk to attach to the instance.initializeParams:{diskSizeGb:'64',sourceImage:`projects/windows-cloud/global/images/family/${sourceImageFamily}/`,},autoDelete:true,boot:true,type:'PERSISTENT',},],machineType:`zones/${zone}/machineTypes/${machineType}`,networkInterfaces:[{// You must verify or configure routes and firewall rules in your VPC network// to allow access to kms.windows.googlecloud.com.// More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server// Additionally, you must enable Private Google Access for subnets in your VPC network// that contain Windows instances with only internal IP addresses.// More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enablingname:networkLink,subnetwork:subnetworkLink,},],// If you chose an image that supports Shielded VM, you can optionally change the instance's Shielded VM settings.// "shieldedInstanceConfig": {// "enableSecureBoot": true,// "enableVtpm": true,// "enableIntegrityMonitoring": true// },},project:projectId,zone,});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Instance created.');}createWindowsServerInstanceInternalIP();Python
from__future__importannotationsimportreimportsysfromtypingimportAnyimportwarningsfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defget_image_from_family(project:str,family:str)->compute_v1.Image:""" Retrieve the newest image that is part of a given family in a project. Args: project: project ID or project number of the Cloud project you want to get image from. family: name of the image family you want to get image from. Returns: An Image object. """image_client=compute_v1.ImagesClient()# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-detailsnewest_image=image_client.get_from_family(project=project,family=family)returnnewest_imagedefdisk_from_image(disk_type:str,disk_size_gb:int,boot:bool,source_image:str,auto_delete:bool=True,)->compute_v1.AttachedDisk:""" Create an AttachedDisk object to be used in VM instance creation. Uses an image as the source for the new disk. Args: disk_type: the type of disk you want to create. This value uses the following format: "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)". For example: "zones/us-west3-b/diskTypes/pd-ssd" disk_size_gb: size of the new disk in gigabytes boot: boolean flag indicating whether this disk should be used as a boot disk of an instance source_image: source image to use when creating this disk. You must have read access to this disk. This can be one of the publicly available images or an image from one of your projects. This value uses the following format: "projects/{project_name}/global/images/{image_name}" auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it Returns: AttachedDisk object configured to be created using the specified image. """boot_disk=compute_v1.AttachedDisk()initialize_params=compute_v1.AttachedDiskInitializeParams()initialize_params.source_image=source_imageinitialize_params.disk_size_gb=disk_size_gbinitialize_params.disk_type=disk_typeboot_disk.initialize_params=initialize_params# Remember to set auto_delete to True if you want the disk to be deleted when you delete# your VM instance.boot_disk.auto_delete=auto_deleteboot_disk.boot=bootreturnboot_diskdefwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:""" Waits for the extended (long-running) operation to complete. If the operation is successful, it will return its result. If the operation ends with an error, an exception will be raised. If there were any warnings during the execution of the operation they will be printed to sys.stderr. Args: operation: a long-running operation you want to wait on. verbose_name: (optional) a more verbose name of the operation, used only during error and warning reporting. timeout: how long (in seconds) to wait for operation to finish. If None, wait indefinitely. Returns: Whatever the operation.result() returns. Raises: This method will raise the exception received from `operation.exception()` or RuntimeError if there is no exception set, but there is an `error_code` set for the `operation`. In case of an operation taking longer than `timeout` seconds to complete, a `concurrent.futures.TimeoutError` will be raised. """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefcreate_instance(project_id:str,zone:str,instance_name:str,disks:list[compute_v1.AttachedDisk],machine_type:str="n1-standard-1",network_link:str="global/networks/default",subnetwork_link:str=None,internal_ip:str=None,external_access:bool=False,external_ipv4:str=None,accelerators:list[compute_v1.AcceleratorConfig]=None,preemptible:bool=False,spot:bool=False,instance_termination_action:str="STOP",custom_hostname:str=None,delete_protection:bool=False,)->compute_v1.Instance:""" Send an instance creation request to the Compute Engine API and wait for it to complete. Args: project_id: project ID or project number of the Cloud project you want to use. zone: name of the zone to create the instance in. For example: "us-west3-b" instance_name: name of the new virtual machine (VM) instance. disks: a list of compute_v1.AttachedDisk objects describing the disks you want to attach to your new instance. machine_type: machine type of the VM being created. This value uses the following format: "zones/{zone}/machineTypes/{type_name}". For example: "zones/europe-west3-c/machineTypes/f1-micro" network_link: name of the network you want the new instance to use. For example: "global/networks/default" represents the network named "default", which is created automatically for each project. subnetwork_link: name of the subnetwork you want the new instance to use. This value uses the following format: "regions/{region}/subnetworks/{subnetwork_name}" internal_ip: internal IP address you want to assign to the new instance. By default, a free address from the pool of available internal IP addresses of used subnet will be used. external_access: boolean flag indicating if the instance should have an external IPv4 address assigned. external_ipv4: external IPv4 address to be assigned to this instance. If you specify an external IP address, it must live in the same region as the zone of the instance. This setting requires `external_access` to be set to True to work. accelerators: a list of AcceleratorConfig objects describing the accelerators that will be attached to the new instance. preemptible: boolean value indicating if the new instance should be preemptible or not. Preemptible VMs have been deprecated and you should now use Spot VMs. spot: boolean value indicating if the new instance should be a Spot VM or not. instance_termination_action: What action should be taken once a Spot VM is terminated. Possible values: "STOP", "DELETE" custom_hostname: Custom hostname of the new VM instance. Custom hostnames must conform to RFC 1035 requirements for valid hostnames. delete_protection: boolean value indicating if the new virtual machine should be protected against deletion or not. Returns: Instance object. """instance_client=compute_v1.InstancesClient()# Use the network interface provided in the network_link argument.network_interface=compute_v1.NetworkInterface()network_interface.network=network_linkifsubnetwork_link:network_interface.subnetwork=subnetwork_linkifinternal_ip:network_interface.network_i_p=internal_ipifexternal_access:access=compute_v1.AccessConfig()access.type_=compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.nameaccess.name="External NAT"access.network_tier=access.NetworkTier.PREMIUM.nameifexternal_ipv4:access.nat_i_p=external_ipv4network_interface.access_configs=[access]# Collect information into the Instance object.instance=compute_v1.Instance()instance.network_interfaces=[network_interface]instance.name=instance_nameinstance.disks=disksifre.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$",machine_type):instance.machine_type=machine_typeelse:instance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.scheduling=compute_v1.Scheduling()ifaccelerators:instance.guest_accelerators=acceleratorsinstance.scheduling.on_host_maintenance=(compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name)ifpreemptible:# Set the preemptible settingwarnings.warn("Preemptible VMs are being replaced by Spot VMs.",DeprecationWarning)instance.scheduling=compute_v1.Scheduling()instance.scheduling.preemptible=Trueifspot:# Set the Spot VM settinginstance.scheduling.provisioning_model=(compute_v1.Scheduling.ProvisioningModel.SPOT.name)instance.scheduling.instance_termination_action=instance_termination_actionifcustom_hostnameisnotNone:# Set the custom hostname for the instanceinstance.hostname=custom_hostnameifdelete_protection:# Set the delete protection bitinstance.deletion_protection=True# Prepare the request to insert an instance.request=compute_v1.InsertInstanceRequest()request.zone=zonerequest.project=project_idrequest.instance_resource=instance# Wait for the create operation to complete.print(f"Creating the{instance_name} instance in{zone}...")operation=instance_client.insert(request=request)wait_for_extended_operation(operation,"instance creation")print(f"Instance{instance_name} created.")returninstance_client.get(project=project_id,zone=zone,instance=instance_name)defcreate_windows_instance(project_id:str,zone:str,instance_name:str,machine_type:str,source_image_family:str="windows-2022",network_link:str="global/networks/default",subnetwork_link:str|None=None,)->compute_v1.Instance:""" Creates a new Windows Server instance that has only an internal IP address. Args: project_id: project ID or project number of the Cloud project you want to use. zone: name of the zone to create the instance in. For example: "us-west3-b" instance_name: name of the new virtual machine (VM) instance. machine_type: machine type you want to create in following format: "zones/{zone}/machineTypes/{type_name}". For example: "zones/europe-west3-c/machineTypes/f1-micro" You can find the list of available machine types using: https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list source_image_family: name of the public image family for Windows Server or SQL Server images. https://cloud.google.com/compute/docs/images#os-compute-support network_link: name of the network you want the new instance to use. For example: "global/networks/default" represents the network named "default", which is created automatically for each project. subnetwork_link: name of the subnetwork you want the new instance to use. This value uses the following format: "regions/{region}/subnetworks/{subnetwork_name}" Returns: Instance object. """ifsubnetwork_linkisNone:subnetwork_link=f"regions/{zone}/subnetworks/default"base_image=get_image_from_family(project="windows-cloud",family=source_image_family)disk_type=f"zones/{zone}/diskTypes/pd-standard"disks=[disk_from_image(disk_type,100,True,base_image.self_link,True)]# You must verify or configure routes and firewall rules in your VPC network# to allow access to kms.windows.googlecloud.com.# More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server# Additionally, you must enable Private Google Access for subnets in your VPC network# that contain Windows instances with only internal IP addresses.# More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enablinginstance=create_instance(project_id,zone,instance_name,disks,machine_type=machine_type,network_link=network_link,subnetwork_link=subnetwork_link,external_access=True,# Set this to False to disable external IP for your instance)returninstanceBecause this instance does not have an external IP address, you cannot connectto it directly over the Internet. You can connect from another network connectedto your VPC network by usingCloud Interconnect orCloud VPN,or you can first connect to a bastion instance over RDP and then connect to theinstance that has only an internal IP address.
Additionally, you can join the VM to aManaged Microsoft AD domain eitherwhile creating the VM or after creating the VM. For more information, seeJoin a Windows VM automatically to a domain.
Configure access to kms.windows.googlecloud.com
For Windows activation and renewal, your VPC network must meetthe following routing and firewall rule requirements.
Routing requirements
Your Windows instances must be able to reachkms.windows.googlecloud.com(35.190.247.13 or2001:4860:4802:32::86) through a route whose next hop is thedefault Internetgateway. You cannot activate Windows instances using an instance based NATgateway or Cloud NAT becausekms.windows.googlecloud.com rejectsactivation requests from IP addresses that are not confirmed to beCompute Engine instances.
You can use thedefault route in yourVPC network to route traffic directly tokms.windows.googlecloud.com. If you remove this route, or if you plan to do soin the future,create a custom static route with destination35.190.247.13or2001:4860:4802:32::86, and next hop set todefault Internet gateway, asfollows:
IPv4 only
gcloud compute routes create mskms-ipv4-route-ipv4-network \ --destination-range=35.190.247.13/32 \ --network=ipv4-network \ --next-hop-gateway=default-internet-gateway
Dual stack
gcloud compute routes create mskms-ipv4-route-ipv4-network \ --destination-range=35.190.247.13/32 \ --network=ipv4-network \ --next-hop-gateway=default-internet-gateway
gcloud compute routes create mskms-ipv6-route-ipv6-network \ --destination-range=2001:4860:4802:32::86/128 \ --network=ipv6-network \ --next-hop-gateway=default-internet-gateway
IPv6 only
gcloud compute routes create mskms-ipv6-route-ipv6-network \ --destination-range=2001:4860:4802:32::86/128 \ --network=ipv6-network \ --next-hop-gateway=default-internet-gateway
Replaceipv4-network oripv6-network with the nameof your VPC network.
Either the default route or a custom static route permitinstances with external IP addresses to reachkms.windows.googlecloud.com. Ifyou have Windows instances without external IP addresses or usingCloud NAT, you must alsoenable Private Google Accessso that instances with only internal IP addresses can send traffic to theexternal IP address forkms.windows.googlecloud.com (35.190.247.13 or2001:4860:4802:32::86).
Firewall rule requirements
Theimplied allow egress firewallrule allows instances to make requests and receive established responses. Unlessyou have created custom firewall rules that deny egress, your Windows instancescan communicate withkms.windows.googlecloud.com.
If you customize firewall rules, it's a good practice to create a high priorityegress allow rule that explicitly permits communication with35.190.247.13 or2001:4860:4802:32::86.This way, as you modify your firewall rules, you won't accidentally disableWindows activation.
The followinggcloud examples creates the recommended allow egress rule withthe highest priority:
IPv4 only
gcloud compute firewall-rules create mskms-ipv4-firewall-rule-ipv4-network \ --direction=EGRESS \ --network=ipv4-network \ --action=ALLOW \ --rules=tcp:1688 \ --destination-ranges=35.190.247.13/32 \ --priority=0
Dual stack
gcloud compute firewall-rules create mskms-ipv4-firewall-rule-ipv4-network \ --direction=EGRESS \ --network=ipv4-network \ --action=ALLOW \ --rules=tcp:1688 \ --destination-ranges=35.190.247.13/32 \ --priority=0
gcloud compute firewall-rules create mskms-ipv6-firewall-rule-ipv6-network \ --direction=EGRESS \ --network=ipv6-network \ --action=ALLOW \ --rules=tcp:1688 \ --destination-ranges=2001:4860:4802:32::86/128 \ --priority=0
IPv6 only
gcloud compute firewall-rules create mskms-ipv6-firewall-rule-ipv6-network \ --direction=EGRESS \ --network=ipv6-network \ --action=ALLOW \ --rules=tcp:1688 \ --destination-ranges=2001:4860:4802:32::86/128 \ --priority=0
Replaceipv4-network oripv6-network with the nameof your VPC network.
Verifying that an instance has successfully started
Windows instances experience a longer startup time because of the sysprepprocess. The Google Cloud console might show that the instance is runningeven if the sysprep process is not yet complete. To check if your instance hassuccessfully started and is ready to be used, check the serial port outputwith the following command:
gcloud compute instances get-serial-port-outputINSTANCE_NAMEReplaceINSTANCE_NAME with the name of the instance thatyou want to verify.
...[snip]...Running schtasks with arguments /run /tn GCEStartup--> SUCCESS: Attempted to run the scheduled task "GCEStartup".-------------------------------------------------------------Instance setup finished.INSTANCE_NAME is ready to use.-------------------------------------------------------------
Enabling and disabling Windows instance features
If you have Windows instances with image versionsv20170509 and later orwith agent version4.1.0 and later, you can set instance configurationin a config file or inproject or instance custom metadata.The config file is inINIformat, and is located at the following path:
C:\Program Files\Google\Compute Engine\instance_configs.cfgThe system overrides configuration settings in the following order of priorityfrom the highest priority to the lowest priority:
- Configuration parameters that you set in the config file
- Configuration parameters set in instance-level custom metadata
- Configuration parameters set in project-level custom metadata
For example, if you can enable theaccountManager feature in a config file,your instance ignores parameters that you set in custom metadata to disablethat feature.
One benefit of setting these parameters in the config file is that thosesettings persist when you create a custom image for a Windows Server instance.Instance-level custom metadata does not persist beyond the life of the instance.
You can disable different Windows instance features using the followingexamples.
Disable the account manager
Disabling the account manager also disablesresetting passwords with the Google Cloud CLIor the Google Cloud console:
Config file:
[accountManager]disable=trueIn custom metadata, set
disable-account-managertotruein metadata.
Disable the address manager
Config file entry:
[addressManager]disable=trueIn custom metadata, set
disable-address-managertotruein metadata.
Windows Server Failover Clustering
Enable the Windows Server Failover Clustering agent:
Config file entry:
[wsfc]enable=trueIn custom metadata, set
enable-wsfctotruein metadata.
Using multiple internal load balancers
Specify the IP address of the internal load balancing instancefor failover clustering. This is an advanced configuration thatyou don't need to set for a dedicated failover cluster.
Normally you use an instance of internal load balancing to directnetwork traffic to one VM instance at a time. If you adda second instance of internal load balancing that uses the failoverclustering VM instances as part of a load-balanced website backend,you would have two internal load balancing IP addresses. If failover clusteringuses10.0.0.10 and the website's load balancer uses10.0.0.11,you must specify the IP address of the load balancer that you use for failoverclustering. This disambiguates which address is in use for the cluster.
Config file entry:
[wsfc]addresses=10.0.0.10In custom metadata, set
wsfc-addrsto a10.0.0.10.
Changing the clustering agent port
Set the failover clustering agent port. The default port is59998.You need to specify a port only when you want to use a different port:
Config file entry:
[wsfc]port=12345In custom metadata, set
wsfc-agent-portto the port number.
Image version notes
Older images don't use a config file and only have a subset of features.Image versions between versionv20160112 and versionv20170509, orWindows agent version between3.2.1.0 and4.0.0 require you to use thefollowing custom metadata values:
- Set
disable-account-managertotruein instance metadata to disablethe account manager. - Set
disable-address-managertotruein instance metadata to disablethe address manager.
What's next
- Generate credentials for Windows VMs
- Add a persistent disk
- Connect to Windows VMs using RDP
- Connect to Windows VMs using SSH
- Connect to Windows VMs using PowerShell
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.