Manage Compute Engine resources using custom constraints

Google Cloud Organization Policy gives you centralized, programmaticcontrol over your organization's resources. As theorganization policy administrator, you can define an organization policy,which is a set of restrictions called constraints that apply toGoogle Cloud resources and descendants of those resources in theGoogle Cloud resource hierarchy. You can enforce organization policies atthe organization, folder, or project level.

Organization Policy providespredefined constraints for variousGoogle Cloud services. However, if you want more granular, customizablecontrol over the specific fields that are restricted in your organizationpolicies, you can also createcustom constraints and use those customconstraints in a custom organization policy.

Benefits

  • Cost management: use custom organization policies to restrict the VMinstance and disk sizes and types that can be used in your organization.You can also restrict the machine family that is used for the VM instance
  • Security, compliance, and governance: you can use custom organizationpolicies to enforce policies as follows:
    • To enforce security requirements, you can require specificfirewall port rules on VMs.
    • To support hardware isolation or licensing compliance, you canrequire all VMs within a specific project or folder to run onsole-tenant nodes.
    • To govern automation scripts, you can use custom organizationpolicies to verify that labels match specified expressions.

Policy inheritance

By default, organization policies are inherited by the descendants of theresources on which you enforce the policy. For example, if you enforce a policyon a folder, Google Cloud enforces the policy on all projects in thefolder. To learn more about this behavior and how to change it, refer toHierarchy evaluation rules.

Pricing

The Organization Policy Service, including predefined and custom organization policies, isoffered at no charge.

Before you begin

Required roles

To get the permissions that you need to manage organization policies for Compute Engine resources, ask your administrator to grant you the following IAM roles:

For more information about granting roles, seeManage access to projects, folders, and organizations.

These predefined roles contain the permissions required to manage organization policies for Compute Engine resources. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to manage organization policies for Compute Engine resources:

  • orgpolicy.constraints.list
  • orgpolicy.policies.create
  • orgpolicy.policies.delete
  • orgpolicy.policies.list
  • orgpolicy.policies.update
  • orgpolicy.policy.get
  • orgpolicy.policy.set
  • To test the constraints:
    • compute.instances.create on the project
    • To use a custom image to create the VM:compute.images.useReadOnly on the image
    • To use a snapshot to create the VM:compute.snapshots.useReadOnly on the snapshot
    • To use an instance template to create the VM:compute.instanceTemplates.useReadOnly on the instance template
    • To assign alegacy network to the VM:compute.networks.use on the project
    • To specify a static IP address for the VM:compute.addresses.use on the project
    • To assign an external IP address to the VM when using a legacy network:compute.networks.useExternalIp on the project
    • To specify a subnet for the VM:compute.subnetworks.use on the project or on the chosen subnet
    • To assign an external IP address to the VM when using a VPC network:compute.subnetworks.useExternalIp on the project or on the chosen subnet
    • To set VM instance metadata for the VM:compute.instances.setMetadata on the project
    • To set tags for the VM:compute.instances.setTags on the VM
    • To set labels for the VM:compute.instances.setLabels on the VM
    • To set a service account for the VM to use:compute.instances.setServiceAccount on the VM
    • To create a new disk for the VM:compute.disks.create on the project
    • To attach an existing disk in read-only or read-write mode:compute.disks.use on the disk
    • To attach an existing disk in read-only mode:compute.disks.useReadOnly on the disk

You might also be able to get these permissions withcustom roles or otherpredefined roles.

Compute Engine supported resources

For Compute Engine, you can set CREATE and UPDATE type custom constraints onthe following resources and fields.

  • Persistent Disk:compute.googleapis.com/Disk
    • Persistent Disk type:resource.type
    • Persistent Disk size:resource.sizeGb
    • Persistent Disk licenses:resource.licenses
    • Persistent Disk license codes:resource.licenseCodes
    • Persistent Disk Confidential Computing:resource.enableConfidentialCompute
    • Persistent Disk source image:resource.sourceImage
  • Image:compute.googleapis.com/Image
    • Raw disk source:resource.rawDisk.source
  • VM instance:compute.googleapis.com/Instance
    • Advanced machine features:
      • resource.advancedMachineFeatures.enableNestedVirtualization
      • resource.advancedMachineFeatures.threadsPerCore
      • resource.advancedMachineFeatures.performanceMonitoringUnit
    • Confidential VM instance configurations:
      • resource.confidentialInstanceConfig.enableConfidentialCompute
      • resource.confidentialInstanceConfig.confidentialInstanceType
    • Deletion protection:resource.deletionProtection
    • Ip Forwarding:resource.canIpForward
    • Private Google Access (IPv6):resource.privateIpv6GoogleAccess
    • Labels:resource.labels
    • Accelerators:
      • resource.guestAccelerators.acceleratorType
      • resource.guestAccelerators.acceleratorCount
    • Machine type:resource.machineType
    • Minimum CPU platform:resource.minCpuPlatform
    • Network interface:
      • resource.networkInterfaces.network
      • resource.networkInterfaces.subnetwork
      • resource.networkInterfaces.networkAttachment
      • resource.networkInterfaces.accessConfigs.name
      • resource.networkInterfaces.accessConfigs.natIP
    • Node affinity:
      • resource.scheduling.nodeAffinities.key
      • resource.scheduling.nodeAffinities.operator
      • resource.scheduling.nodeAffinities.values
    • Reservation Affinity:
      • resource.scheduling.reservationAffinity.key
      • resource.scheduling.reservationAffinity.values
    • Shielded Instance Config:
      • resource.shieldedInstanceConfig.enableSecureBoot
      • resource.shieldedInstanceConfig.enableVtpm
      • resource.shieldedInstanceConfig.enableIntegrityMonitoring
    • Zone:resource.zone
  • Other supported compute resources:

Enforcing Mandatory Resource Manager Tags

Some Compute Engine resources also support the GOVERN_TAGS type constraintto enforce mandatory Resource Manager tags on the Compute Engine resource.For more information, seeEnforcement of mandatory tags using organizationpolicies.

Set up a custom constraint

A custom constraint is defined by the resources, methods,conditions, and actions that are supported by the service on which you areenforcing the organization policy. Conditions for your custom constraints aredefined usingCommon Expression Language (CEL). For more information about how to buildconditions in custom constraints using CEL, see the CEL section ofCreating and managing custom organization policies.

You can create a custom constraint and set it up for use in organizationpolicies using the Google Cloud console or gcloud CLI.

Console

  1. In the Google Cloud console, go to theOrganization policies page.

    Go to Organization policies

  2. Select theProject picker at the top of the page.

  3. From theProject picker, select the resource for which you wantto set the organization policy.

  4. ClickCustom constraint.

  5. In theDisplay name box, enter a human-friendly name for theconstraint. This field has a maximum length of 200 characters.Don't use PII or sensitive data in constraint names, because they could beexposed in error messages.

  6. In theConstraint ID box, enter the name you want for your newcustom constraint. A custom constraint must start withcustom., and canonly include uppercase letters, lowercase letters, or numbers, forexample,custom.createOnlyN2DVMs. The maximum length of this field is 70characters, not counting the prefix, for example,organizations/123456789/customConstraints/custom..

  7. In theDescription box, enter a human-friendly description of theconstraint to display as an error message when the policy is violated.This field has a maximum length of 2000 characters.

  8. In theResource type box, select the name of the Google CloudREST resource containing the object and field you want to restrict. Forexample,compute.googleapis.com/Instance.

  9. UnderEnforcement method, select whether to enforce the constrainton the RESTCREATE method.

  10. To define a condition, clickEdit condition.

    1. In theAdd condition panel, create a CEL condition that refers to asupported service resource, for exampleresource.machineType.contains('/machineTypes/n2d'). This field has a maximumlength of 1000 characters.

    2. ClickSave.

  11. UnderAction, select whether to allow or deny the evaluated method ifthe previous condition is met.

  12. ClickCreate constraint.

When you have entered a value into each field, the equivalent YAMLconfiguration for this custom constraint appears on the right.

gcloud

To create a custom constraint using the gcloud CLI, create aYAML file for the custom constraint:

name:organizations/ORGANIZATION_ID/customConstraints/CONSTRAINT_NAMEresource_types:compute.googleapis.com/RESOURCE_NAMEmethod_types:CREATEcondition:CONDITIONaction_type:ACTIONdisplay_name:DISPLAY_NAMEdescription:DESCRIPTION

Replace the following:

  • ORGANIZATION_ID: your organization ID, such as123456789.

  • CONSTRAINT_NAME: the name you want for your newcustom constraint. A custom constraint must start withcustom., and canonly include uppercase letters, lowercase letters, or numbers. Forexample,custom.createOnlyN2DVMs. The maximum length of this field is 70characters, not counting the prefix (for example,organizations/123456789/customConstraints/custom.).

  • RESOURCE_NAME: the name (not the URI) of theCompute Engine API REST resource containing the object and fieldyou want to restrict. For example,Instance.

  • CONDITION: aCEL condition that is written againsta representation of a supported service resource. This field has a maximumlength of 1000 characters. SeeSupported resources for more information about theresources available to write conditions against. For example,"resource.machineType.contains('/machineTypes/n2d')".

  • ACTION: the action to take if thecondition ismet. This can be eitherALLOW orDENY.

  • DISPLAY_NAME: a human-friendly name for theconstraint. This field has a maximum length of 200 characters. Don'tuse PII or sensitive data in constraint names, because they could beexposed in error messages.

  • DESCRIPTION: a human-friendly description of theconstraint to display as an error message when the policy is violated.This field has a maximum length of 2000 characters.

For more information about how to create a custom constraint, seeCreating and managing custom organization policies.

After you have created the YAML file for a new custom constraint, you must set it up to makeit available for organization policies in your organization. To set up a custom constraint, usethegcloud org-policies set-custom-constraint command:
gcloudorg-policiesset-custom-constraintCONSTRAINT_PATH
ReplaceCONSTRAINT_PATH with the full path to yourcustom constraint file. For example,/home/user/customconstraint.yaml.Once completed, your custom constraints are available as organization policiesin your list of Google Cloud organization policies.To verify that the custom constraint exists, use thegcloud org-policies list-custom-constraints command:
gcloudorg-policieslist-custom-constraints--organization=ORGANIZATION_ID
ReplaceORGANIZATION_ID with the ID of your organization resource.For more information, seeViewing organization policies.

Enforce a custom constraint

You can enforce a constraint by creating an organization policy that references it, and thenapplying that organization policy to a Google Cloud resource.

Console

  1. In the Google Cloud console, go to theOrganization policies page.

    Go to Organization policies

  2. From the project picker, select the project for which you want to set the organization policy.
  3. From the list on theOrganization policies page, select your constraint to view thePolicy details page for that constraint.
  4. To configure the organization policy for this resource, clickManage policy.
  5. On theEdit policy page, selectOverride parent's policy.
  6. ClickAdd a rule.
  7. In theEnforcement section, select whether enforcement of this organization policy is on or off.
  8. Optional: To make the organization policy conditional on a tag, clickAdd condition. Note that if you add a conditional rule to an organization policy, you must add at least one unconditional rule or the policy cannot be saved. For more information, seeSetting an organization policy with tags.
  9. ClickTest changes to simulate the effect of the organization policy. Policy simulation isn't available for legacy managed constraints. For more information, see Test organization policy changes with Policy Simulator.
  10. To finish and apply the organization policy, clickSet policy. The policy requires up to 15 minutes to take effect.

gcloud

To create an organization policy with boolean rules, create a policy YAML file that references the constraint:

name:projects/PROJECT_ID/policies/CONSTRAINT_NAMEspec:rules:-enforce:true

Replace the following:

  • PROJECT_ID: the project on which you want to enforce your constraint.
  • CONSTRAINT_NAME: the name you defined for your custom constraint. For example,custom.createOnlyN2DVMs.

To enforce the organization policy containing the constraint, run the following command:

gcloudorg-policiesset-policyPOLICY_PATH

ReplacePOLICY_PATH with the full path to your organization policy YAML file. The policy requires up to 15 minutes to take effect.

Example: Create a constraint that restricts VMs to use the N2D machine type

gcloud

  1. Create aonlyN2DVMs.yaml constraint file with the following information:

    name:organizations/ORGANIZATION_ID/customConstraints/custom.createOnlyN2DVMsresource_types:compute.googleapis.com/Instancecondition:"resource.machineType.contains('/machineTypes/n2d')"action_type:ALLOWmethod_types:CREATEdisplay_name:Only N2D VMs alloweddescription:Restrict all VMs created to only use N2D machine types.
  2. Set the custom constraint.

    gcloud org-policies set-custom-constraint onlyN2DVMs.yaml
  3. Create aonlyN2DVMs-policy.yaml policy file with the following information.In this example we enforce this constraint at theproject level but you might also set this at the organization or folder level.ReplacePROJECT_ID with your project ID.

    name:projects/PROJECT_ID/policies/custom.createOnlyN2DVMsspec:rules:enforce:true
  4. Enforce the policy.

    gcloud org-policies set-policy onlyN2DVMs-policy.yaml
  5. Test the constraint by trying to create a VM that uses a machine type thatisn't an N2D machine.

    gcloud compute instances create my-test-instance \    --project=PROJECT_ID \    --zone=us-central1-c \    --machine-type=e2-medium

    The output is similar to the following:

    ERROR: (gcloud.compute.instances.create) Could not fetch resource:– Operation denied by custom org policies: [customConstraints/custom.createOnlyN2DVMs]: Restrict all VMs created to only use N2D machine types.

Example custom constraints for common use cases

The following sections provide the syntax of some custom constraints that youmight find useful:

Disk

Use caseSyntax
Persistent Disk type must be "Extreme persistent disk (pd-extreme)"
name:organizations/ORGANIZATION_ID/customConstraints/custom.createDisksPDExtremeOnlyresource_types:compute.googleapis.com/Diskcondition:"resource.type.contains('pd-extreme')"action_type:ALLOWmethod_types:CREATEdisplay_name:Create pd-extreme disks onlydescription:Only the extreme persistent disk type is allowed to be created.
Disk size must be less than or equal to 250 GB
name:organizations/ORGANIZATION_ID/customConstraints/custom.createDisksLessThan250GBresource_types:compute.googleapis.com/Diskcondition:"resource.sizeGb<=250"action_type:ALLOWmethod_types:CREATEdisplay_name:Disks size maximum is 250 GBdescription:Restrict the boot disk size to 250 GB or less for all VMs.

Image

Use caseSyntax
Source images must be from Cloud Storagetest_bucket only
name:organizations/ORGANIZATION_ID/customConstraints/custom.createDisksfromStoragebucketresource_types:compute.googleapis.com/Imagecondition:"resource.rawDisk.source.contains('storage.googleapis.com/test_bucket/')"action_type:ALLOWmethod_types:CREATEdisplay_name:Source image must be from Cloud Storage test_bucket onlydescription:Source images used in this project must be imported from theCloud Storage test_bucket.

VM instance

Use caseSyntax
VM must have a label with the key set tocost center
name:organizations/ORGANIZATION_ID/customConstraints/custom.createVMWithLabelresource_types:compute.googleapis.com/Instancecondition:"'cost_center'inresource.labels"action_type:ALLOWmethod_types:CREATEdisplay_name:'cost_center'label requireddescription:Requires that all VMs created must have the a 'cost_center' labelthat can be used for tracking and billing purposes.
VM must have a label with the key set tocost center and the value set toeCommerce
name:organizations/ORGANIZATION_ID/customConstraints/custom.createECommerceVMOnlyresource_types:compute.googleapis.com/Instancecondition:"'cost_center'inresource.labelsandresource.labels['cost_center']=='eCommerce'"action_type:ALLOWmethod_types:CREATEdisplay_name:Label (cost_center/eCommerce) requireddescription:Label required and Key/value must be cost_center/eCommerce.
VM must use machine type N2D
name:organizations/ORGANIZATION_ID/customConstraints/custom.createOnlyN2DVMsresource_types:compute.googleapis.com/Instancecondition:"resource.machineType.contains('/machineTypes/n2d')"action_type:ALLOWmethod_types:CREATEdisplay_name:Only N2D VMs alloweddescription:Restrict all VMs created to only use N2D machine types.
VM must use machine typee2-highmem-8
name:organizations/ORGANIZATION_ID/customConstraints/custom.createOnlyE2highmem8resource_types:compute.googleapis.com/Instancecondition:"resource.machineType.endsWith('-e2-highmem-8')"action_type:ALLOWmethod_types:CREATEdisplay_name:Only "e2-highmem-8" VMs alloweddescription:Restrict all VMs created to only use the E2 high-memorymachine types that have 8 vCPUs.
Ensures that VMs are scheduled on the node group "foo"
name:organizations/ORGANIZATION_ID/customConstraints/custom.createOnlySTVMresource_types:compute.googleapis.com/Instancecondition:"resource.scheduling.nodeAffinities.exists(n,n.key=='foo')"action_type:ALLOWmethod_types:CREATEdisplay_name:Only VMs scheduled on node group "foo" alloweddescription:Restrict all VMs created to use the node group "foo".

What's next

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-11-24 UTC.