Hour 3: Guardrails: Organization Policy, VPC Service Controls, keys and detection

Organization Policy constraints, VPC Service Controls perimeters, Cloud KMS and Secret Manager, Security Command Center and Cloud Asset Inventory.
Hour 3Organization PolicyVPC Service ControlsCloud KMS

Hour 3: Guardrails, Organization Policy, VPC Service Controls, keys and detection

Hour 1 gave you a hierarchy and Hour 2 gave you identities with limited roles. Neither stops a well-meaning engineer, or an attacker with a valid token, from creating a public VM, copying a dataset to a personal project or leaving a service account key in a repository. Guardrails are the controls that hold even when somebody has permission. This hour covers the four families of guardrails that a landing zone sets up before the first workload arrives.

The first family is preventive configuration limits: Organization Policy constraints say which resources may exist, and Assured Workloads packages them for regulated folders. The second is data-flow limits: VPC Service Controls draws a perimeter around Google APIs. The third is key and secret control: Cloud KMS and Secret Manager keep encryption keys and credentials out of code. The fourth is detection: Security Command Center and Cloud Asset Inventory tell you what already exists and what drifted.

The hour is hands-on. You read effective policies, write policy files, run a dry-run policy and a dry-run perimeter, create a customer-managed key and a secret, inventory resources, and in the main lab you enforce a constraint, prove that a forbidden VM is refused, and restore the original state. Every command comes with expected output, common errors and a note on cost.

The pages are written for people who run production platforms. They explain the inheritance rules, the order of rollout (inventory, dry-run, read logs, enforce), the exceptions that a reviewer can read, and the failures that are typical in the first year: a pipeline broken by a perimeter, a disabled key that stops a bucket, and findings that nobody reads.

What you will be able to do after this hour

  • Explain how Organization Policy constraints are inherited and merged, and read the effective policy of a project with gcloud org-policies describe --effective.
  • Name the eight baseline constraints of a landing zone, say what each blocks, and write the policy file for a boolean and for a list constraint.
  • Decide whether a workload needs an Assured Workloads folder, and describe the operating rules of one.
  • Build a VPC Service Controls perimeter in dry-run mode, read the violations, and choose between an access level, an ingress rule and an egress rule.
  • Create a Cloud KMS key ring and key with rotation, use it as a customer-managed encryption key (CMEK), and store a secret in Secret Manager.
  • Describe what Security Command Center and Cloud Asset Inventory report, and triage a finding.
  • Enforce a constraint on a lab folder, prove the denial, find the evidence in the audit log, and restore the original policy.
  • Diagnose the four common production failures: a policy that blocks a deploy, a perimeter that blocks a pipeline, a disabled CMEK key, and noisy findings.

Schedule (60 minutes)

#ModuleMinutes
1Organization Policy6
2Essential constraint catalogue7
3Assured Workloads and regulated folders7
4VPC Service Controls8
5Keys and secrets7
6Detection and posture7
7Lab: enforce and prove a constraint10
8Production and troubleshooting8
Total60

The minutes are the reading and listening time of each module. Labs take longer if you run every step; the timings in the lab tabs say how long.

What the labs create, and what they cost

ModuleWhat the lab doesBillable resourcesCost class
1Reads effective policy; sets and deletes a dry-run policy on a lab folderNoneFree
2Audits the eight baseline constraints; optional policy on a lab folderNone (an optional test key would be deleted)Free
3Worksheet and read-only inspection of a regulated folder; no workload is createdNoneFree
4Dry-run perimeter around a sandbox project with one test bucketOne bucket with one tiny object, log entriesLow (usually well under a few USD per day for this lab)
5KMS key ring and key, a CMEK bucket, a secret, a disable testOne software key version, one tiny object, one secret versionLow
6Read-only inventory and triage of one findingNoneFree
7Deny external IPs on a lab folder, try to create a VM, restoreNone, because creation is deniedFree
8Diagnose simulated incidents with read-only commandsNoneFree

Key rings and keys in Cloud KMS cannot be deleted; they keep their names. They do not cost anything when they hold no enabled key versions. The cleanup in Module 5 schedules destruction of the key versions and removes the other test resources.

What you need

  • A sandbox organization with a lab folder and a lab project. Organization Policy at scale, VPC Service Controls and the organization-level inventory need an organization. The setup page explains what is possible without one.
  • Roles on the lab folder (not on the organization root) such as roles/orgpolicy.policyAdmin, and, for the perimeter lab, a delegated Access Context Manager role.
  • The Google Cloud CLI (gcloud, current release channel) or Cloud Shell in a browser.
  • A billing account with a budget in place, from Hour 1.

See the Setup tab for the environment checks and the order in which to prepare them.

Cost. Policies, perimeters, access levels and inventory reads are free. A few steps create small billable resources, and each says so with its cleanup. Budgets send alerts; they do not cap spending, so run the cleanup at the end of every lab and set a budget before you begin.
Safety. Guardrails can stop real work. Use a sandbox organization or a dedicated lab folder, never the organization root and never a folder with live workloads. Test every new rule in dry-run first, keep the rollback command written down, and use placeholders such as ORG_ID and FOLDER_ID in the commands. IDs in the expected output are illustrative.

Setup

Guardrails: Organization Policy, VPC Service Controls, keys and detection
Hour 3

Environment for Hour 3

This hour changes guardrails, so the environment matters more than in the earlier hours. You need an identity that can set policy on a lab folder and nowhere else, the Google Cloud CLI, a lab project with billing and a budget, and a short list of APIs. The steps below are ordered so that you can stop at the point your environment allows.

1. Choose your environment

OptionWhat worksWhat does not
Sandbox organization (recommended): a Cloud Identity Free domain you own, or a training organizationEverything: policies on folders, dry-run perimeters, organization-level inventory and findings (tier permitting)Nothing is missing. You must hold the admin roles yourself or have admin help.
Company organization with a lab folder and delegated rolesPolicies and read commands scoped to your lab folder; projects below it; KMS and Secret Manager in your lab projectOrganization-level policy, access policies, organization findings and organization inventory are usually denied: use project or folder scope
No organization (personal account, project at the root)Policies on a project, KMS, Secret Manager, project-level asset search, effective policy readsFolder policies, VPC Service Controls (perimeters need an organization), organization inventory, Security Command Center organization features
What to do without an organization. Replace --folder=FOLDER_ID by --project=PROJECT_ID where a lab allows it (Modules 1, 2 and 7), run Module 5 as written, run Module 6 at project scope, and treat Modules 3 and 4 as reading exercises with their diagrams and design worksheets. A free Cloud Identity account with a domain you own gives you an organization for the full course; keep it separate from your company account.

2. Prepare a lab folder and a lab project

Every policy in this hour is set on one lab folder. A policy set on the organization root affects everybody. If you do not have a lab folder yet, create one as in Hour 1 (folders are free):

gcloud resource-manager folders create --display-name="lz-lab" --organization=ORG_ID
gcloud resource-manager folders list --organization=ORG_ID

Create or choose one throw-away project in it with billing linked and a budget set (Hour 1, Module 3). The lab project must not hold real workloads.

gcloud projects describe PROJECT_ID --format="value(parent.id,parent.type,lifecycleState)"
555555555555  folder  ACTIVE

IDs in expected output are illustrative. The parent must be your lab folder, not the organization.

3. Open a shell with gcloud

Cloud Shell is the fastest option. Open https://console.cloud.google.com, sign in and click the Cloud Shell icon. It provides a current gcloud CLI. Cloud Shell is not part of any perimeter you build in Module 4: that is useful, because it is a ready example of a caller from outside.

Local install. Install the Google Cloud CLI (current release channel) from cloud.google.com/sdk/docs/install, then:

gcloud init
gcloud auth login
gcloud config configurations create lz-lab
gcloud config set account YOUR_EMAIL
gcloud config set project PROJECT_ID

A separate configuration keeps lab commands away from other environments.

4. Check commands

gcloud --version
gcloud auth list
gcloud organizations list
gcloud org-policies list --folder=FOLDER_ID
gcloud access-context-manager policies list --organization=ORG_ID
Google Cloud SDK 5xx.x.x
      Credentialed Accounts
ACTIVE  ACCOUNT
*       you@example.com

DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Listed 0 items.

NAME          ORGANIZATION  SCOPES  TITLE
330193482019  123456789012          default policy

Version numbers are placeholders. Any current gcloud release works; update with gcloud components update (local install) or open a new Cloud Shell session. Listed 0 items. for the folder is normal on a new folder: nothing is set there yet.

  • Empty organization list. You are not in an organization, or you lack permission to see it. Use the "no organization" path.
  • PERMISSION_DENIED on org-policies list. You need roles/orgpolicy.policyViewer on the folder, and the Organization Policy API must be enabled in the project that makes the call (step 5).
  • Empty Access Context Manager list. No access policy exists. Ask the organization owner; creating the single organization policy in a shared organization is a decision for the security team.

5. Enable the APIs

Enabling an API is free. Run these in the lab project:

gcloud services enable orgpolicy.googleapis.com \
  accesscontextmanager.googleapis.com \
  cloudkms.googleapis.com \
  secretmanager.googleapis.com \
  cloudasset.googleapis.com \
  compute.googleapis.com \
  logging.googleapis.com \
  --project=PROJECT_ID
gcloud services list --enabled --project=PROJECT_ID --filter="config.name:(orgpolicy OR cloudkms OR secretmanager OR cloudasset)" --format="value(config.name)"
cloudasset.googleapis.com
cloudkms.googleapis.com
orgpolicy.googleapis.com
secretmanager.googleapis.com

Add assuredworkloads.googleapis.com only if you will run the read-only commands of Module 3. Enabling Compute Engine on a project that has no network may leave you without a default network if the baseline constraint of Module 2 is enforced; Module 7 tells you what to check.

6. Roles you need

Ask your platform team for these on the lab folder and the lab project only. Do not ask for organization-level roles for a course.

ForRoleScope
Reading policiesroles/orgpolicy.policyViewerLab folder
Setting and deleting policies (Modules 1, 2, 7)roles/orgpolicy.policyAdminLab folder
Access policy, levels and perimeters (Module 4)roles/accesscontextmanager.policyAdmin (or a scoped access policy delegated to you)Organization or scoped policy
Assured Workloads read commands (Module 3)roles/assuredworkloads.readerOrganization
Keys and secrets (Module 5)roles/cloudkms.admin, roles/secretmanager.adminLab project
Inventory and findings (Module 6)roles/cloudasset.viewer, roles/securitycenter.findingsViewerLab folder or project (organization if allowed)
VM request in the lab (Module 7)roles/compute.instanceAdmin.v1Lab project
Reading audit logsroles/logging.viewer (or roles/logging.privateLogViewer for data access logs)Lab project or folder
Separation of duties. In a real organization, policyAdmin belongs to a small platform group. Hold it only on the lab folder for this course, and give it up afterwards. Anyone with this role can switch off every guardrail below it.

7. Variables, budget and cleanup habit

export ORG_ID=123456789012
export FOLDER_ID=555555555555
export PROJECT_ID=lab-sandbox-1234
export REGION=europe-west1
export ZONE=europe-west1-b
echo "$ORG_ID $FOLDER_ID $PROJECT_ID $REGION $ZONE"

Replace the example values with yours. Set a small budget with alerts at 50, 90 and 100 percent before you start (Hour 1). A budget sends alerts; it does not stop spending.

  • Use one prefix for everything you create, such as lz-lab, so that cleanup commands cannot touch other resources.
  • Write the rollback command of every policy before you set it: gcloud org-policies delete CONSTRAINT --folder=FOLDER_ID.
  • After each lab run gcloud org-policies list --folder=$FOLDER_ID and confirm that the folder is back to its starting state.
  • Keep the effective-policy output from before each change, so that you can compare after cleanup.
Security. Do not paste service account keys, passwords, tokens or real secret values into commands or chat. The Module 5 lab uses a harmless sample value. Do not set a policy on the organization root while you learn, and never enforce a perimeter on a shared project.

Module 1 · Organization Policy

00–06 · Constraints, boolean and list policies, inheritance, dry-run and the effective policy
Organization PolicyConstraintsInheritance6 min
Learning objectives
  • Explain what an Organization Policy constraint is and how it differs from an IAM role.
  • Predict the effective policy of a project from the policies set on its organization, folder and project.
  • Read, set and remove a policy with gcloud org-policies, and test a new rule in dry-run mode first.

The short answer

Organization Policy (组织策略) is a service that lets administrators place constraints (约束) on how resources can be configured across the organization, folders and projects. It is the main preventive guardrail of a landing zone: instead of hoping that every engineer remembers the rule, the platform refuses the request.

What: constraint, policy and rule

  • Constraint. A definition published by Google (a managed or legacy constraint) or written by you (a custom constraint). It has a name such as constraints/compute.vmExternalIpAccess, a type (boolean or list) and a default behaviour.
  • Policy. The setting of one constraint on one node. A node has at most one policy per constraint.
  • Rule. A policy contains rules. A rule says enforce: true (boolean), allowAll, denyAll, or values with allowedValues and deniedValues (list). A rule may carry a condition, typically on a Resource Manager tag.
  • Spec and dry-run spec. The policy has spec (enforced) and, optionally, dryRunSpec (logged, not enforced).

Why it exists: the gap that IAM leaves

IAM decides who may call an API. It cannot say that nobody may create a VM with a public address, or that data must stay in Europe. A project owner has permission to do both. The constraint is the control that remains true whoever the caller is, so it must be set at a level that the project owner does not control.

How it works internally

  1. A user or pipeline calls a service API (for example, instances.insert in Compute Engine).
  2. IAM checks permission first. If IAM denies, the request ends there.
  3. The service reads the effective policy for each constraint relevant to the request. The Organization Policy Service computes it from the organization down to the project.
  4. If the requested configuration violates the effective policy, the API returns FAILED_PRECONDITION (HTTP 400) with the constraint name. Nothing is created.
  5. The decision is recorded in Cloud Audit Logs, which is how you find who tried what.

Inheritance and merging

Setting on the childEffect on the effective policy
No policyThe child inherits the parent's effective policy unchanged.
inheritFromParent: true (list constraints)The child's rules are merged with the parent's: allowed values are added, denied values are added, and a deny wins over an allow.
inheritFromParent: false or an allowAll/denyAll ruleThe child's rules replace the parent's for that node.
reset: trueThe node returns to the constraint's default behaviour, ignoring parent rules.
Boolean constraint enforce: true on a parentInherited. A child may set enforce: false, which turns the rule off for that subtree. Administrators therefore protect the permission orgpolicy.policy.set.
Who may override. Setting a policy needs roles/orgpolicy.policyAdmin (or the permission orgpolicy.policy.set). Grant it on the organization to a very small group, and do not grant it on projects, or a project team can switch off its own guardrails.

Boolean and list constraints

TypeExampleHow a policy is written
Booleaniam.disableServiceAccountKeyCreation, compute.requireOsLoginrules: - enforce: true
Listgcp.resourceLocations, compute.vmExternalIpAccess, iam.allowedPolicyMemberDomainsrules: - values: allowedValues: [...] or denyAll: true or allowAll: true
Customcustom.denyPublicBucketNames (your name, a CEL condition)Defined once with set-custom-constraint, then used in a policy like any other.

Conditional rules with tags

A rule can apply only to resources that carry a Resource Manager tag (for example ORG_ID/environment=sandbox). This allows one folder to hold a strict default and a tagged exception, with a record of who tagged what. It is more precise than a project-level override, and the tag binding is itself governed by IAM.

When to use it

  • A rule must hold for everyone and cannot depend on training: no service account keys, no public SQL, allowed regions.
  • You want prevention, not only detection. For detection, Module 6 (Security Command Center) is the other half.
  • You need an auditable exception path: a tag, a folder, or a time-boxed policy change in a pull request.

What it is confused with

ControlQuestion it answersWhere it applies
IAM allow policyWho may call this API on this resource?Principals and resources
IAM deny policyWho may never call it, even if an allow exists?Principals and permissions
Organization PolicyWhich configurations may exist?Resource configuration, whoever calls
VPC Service ControlsFrom where may Google-managed services be reached?API traffic across a perimeter (Module 4)
Firewall policyWhich network flows are allowed?Packets in a VPC (Hour 4)
AWS SCP / Azure PolicyClosest peers: SCP limits actions of accounts; Azure Policy audits or denies resource properties.Other clouds, for comparison

Common misunderstandings

  • "Organization Policy fixes existing resources." It does not. It blocks new creates and updates. Existing VMs with external IPs keep running until someone changes them, so pair every enforcement with an inventory query.
  • "It needs an organization." The strongest use does, because inheritance starts at the organization. Policies can still be set directly on a project, which is what a personal sandbox can do. Check the current documentation for what your resource supports.
  • "The project owner can change it." Only if the owner also holds orgpolicy.policy.set. Owner and Editor basic roles do not include it.
  • "The constraint name has to include constraints/." The full name does, but current gcloud org-policies commands accept the short form, for example compute.vmExternalIpAccess. Terraform and the API return the full form.
Secure by default. Organizations created from 2024 onward enforce a baseline of constraints automatically, such as no service account key creation and uniform bucket-level access. Older organizations do not. Always read the effective policy instead of assuming.
Organization iam.disableServiceAccountKeyCreation enforce: true Folder: production gcp.resourceLocations allowed: in:eu-locations Project: prj-app-a no own policy inherits both rules Effective policy of prj-app-a key creation blocked · resources only in EU locations Merge rules for list constraints child inheritFromParent: true → union of values, deny wins child inheritFromParent: false → child replaces parent child reset: true → constraint default Boolean: a child can set enforce: false unless nobody below holds orgpolicy.policy.set. Evaluated when a resource is created or changed, never against resources that already exist.

Figure 1. Inheritance. The project has no policy of its own and still obeys both rules. Read the left column top to bottom, then follow the arrow to the result.

Request create VM, bucket IAM who may call? Organization Policy what may exist? VPC Service Controls from where may it be reached? 403 PERMISSION_DENIED 400 FAILED_PRECONDITION 403 VPC_SERVICE_CONTROLS Three independent guardrails: each can stop the request on its own.

Figure 2. The request path. The error text tells you which layer stopped the call, so read it before you change any role.

The animation follows one policy from gcloud org-policies set-policy to a rejected VM request. Notice that the Compute Engine API asks the Org Policy Service at request time; the policy is not copied into the VM service.

Everything below uses the Organization Policy API (orgpolicy.googleapis.com) through gcloud org-policies. Enable the API in the project that runs the commands: gcloud services enable orgpolicy.googleapis.com --project=PROJECT_ID (free). Reading needs roles/orgpolicy.policyViewer; writing needs roles/orgpolicy.policyAdmin.

gcloud org-policies list

Purpose. Shows the policies that are set on a node (organization, folder or project). It does not show inherited policies.

gcloud org-policies list --folder=FOLDER_ID
CONSTRAINT                          LIST_POLICY  BOOLEAN_POLICY  ETAG
compute.vmExternalIpAccess          SET          -               CNzP4coGELCZ4aoD
iam.disableServiceAccountKeyCreation -           SET             CJ_j4coGEMi4qvEB

Flags. Use exactly one of --organization, --folder or --project. Add --show-inherited where your SDK offers it, or use describe --effective for a single constraint. Check gcloud org-policies list --help for the flags in your SDK version. Cost: free.

IDs in the expected output are illustrative.

gcloud org-policies describe --effective

Purpose. Computes the policy that applies after inheritance and merging. This is the command to run when a user says "the policy does not apply" or "I am blocked and I do not know why".

gcloud org-policies describe compute.vmExternalIpAccess --project=PROJECT_ID --effective
name: projects/123456789012/policies/compute.vmExternalIpAccess
spec:
  rules:
  - denyAll: true

Flags. --effective returns the computed result. Without it you get only the policy set on that very node, and the command fails with NOT_FOUND if none is set. Cost: free.

gcloud org-policies set-policy (write)

Purpose. Creates or replaces the policy of one constraint from a YAML file. The file contains the full resource name, so the node is chosen by the file and not by a flag.

# policy.yaml : deny every external IP on VMs under a lab folder
name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
spec:
  rules:
  - denyAll: true
gcloud org-policies set-policy policy.yaml
Updated policy [folders/555555555555/policies/compute.vmExternalIpAccess].

Flags and fields. spec.inheritFromParent (list only), spec.reset, spec.rules[].enforce, allowAll, denyAll, values.allowedValues, values.deniedValues, condition. The etag field, when present in a file you downloaded, makes the update fail if somebody else changed the policy in between. Cost: free (metadata).

Dry-run: the same command with dryRunSpec

Purpose. Logs violations without blocking. Put the proposed rule under dryRunSpec and keep the enforced spec as it is.

name: folders/FOLDER_ID/policies/compute.requireOsLogin
dryRunSpec:
  rules:
  - enforce: true
gcloud org-policies set-policy dryrun.yaml
gcloud logging read 'protoPayload.metadata.dryRun="true" OR protoPayload.metadata.violationInfo.policyType="CUSTOM_CONSTRAINT"' --folder=FOLDER_ID --limit=5 --freshness=1d

Read the result. A would-be violation is written to the audit log of the project that made the request, with the constraint name and the policy type. The exact log field names can change; open one entry in Logs Explorer and copy the filter that matches. Cost: free to set; normal Cloud Logging pricing applies to log volume.

gcloud org-policies delete (write)

Purpose. Removes the policy set on a node, so the node inherits again. This is the cleanup for every lab.

gcloud org-policies delete compute.vmExternalIpAccess --folder=FOLDER_ID
Deleted policy [folders/555555555555/policies/compute.vmExternalIpAccess].

Common errors. PERMISSION_DENIED: ... orgpolicy.policy.set means you lack roles/orgpolicy.policyAdmin on that node. NOT_FOUND means no policy is set there, which is fine for a cleanup.

Old command group. gcloud resource-manager org-policies belongs to the first (v1) API and uses a different file format. New work uses gcloud org-policies. If you find the older group in a script, plan a migration.
Production use. Policies belong in Terraform (google_org_policy_policy) and are changed by pull request. Treat set-policy from a laptop as an emergency or lab tool.

Lab 1: read the effective policy and run a dry-run (about 12 minutes of a 60-minute hour, free)

Goal. Read the effective policy of a sandbox project, set a dry-run policy on a lab folder, confirm it was stored as a dry-run, and remove it. No resource is created and no rule is enforced, so nothing is blocked and nothing is billed.

Prerequisites. roles/orgpolicy.policyAdmin on a lab folder (see the setup page), the Organization Policy API enabled in the project you call from, and gcloud authenticated. If you have no organization, use a sandbox project and replace --folder=FOLDER_ID by --project=PROJECT_ID and the first line of the YAML by projects/PROJECT_ID/policies/.... IDs in the expected output are illustrative.

  1. Set shell variables: export FOLDER_ID=555555555555 and export PROJECT_ID=lab-sandbox-1234 (use your own values).
  2. Enable the API: gcloud services enable orgpolicy.googleapis.com --project=$PROJECT_ID.
  3. Read what is set on the folder: gcloud org-policies list --folder=$FOLDER_ID. Write down the constraints you see.
  4. Read the effective policy of a constraint on the project: gcloud org-policies describe compute.requireOsLogin --project=$PROJECT_ID --effective. Record whether enforce is true.
  5. Create dryrun.yaml with the dry-run content shown in the commands tab, replacing FOLDER_ID.
  6. Apply it: gcloud org-policies set-policy dryrun.yaml.
  7. Verify it was stored as a dry-run only: gcloud org-policies describe compute.requireOsLogin --folder=$FOLDER_ID. The output must contain dryRunSpec: and must not contain an enforced spec: with enforce: true.
  8. Verify the effective policy did not change: repeat step 4. The answer must be the same as before.
  9. Clean up: gcloud org-policies delete compute.requireOsLogin --folder=$FOLDER_ID, then gcloud org-policies list --folder=$FOLDER_ID and confirm the constraint is gone.
name: folders/555555555555/policies/compute.requireOsLogin
dryRunSpec:
  rules:
  - enforce: true

Expected result. Step 7 prints a policy with dryRunSpec only. Step 8 shows the same effective policy as step 4: a dry-run changes nothing for users.

Cost. Free. Policy metadata and API calls have no charge; the Organization Policy API is enabled on an existing project.

Cleanup. Step 9. Optionally disable the API if the project is only for this course: gcloud services disable orgpolicy.googleapis.com --project=$PROJECT_ID.

Lab 2 (optional): predict before you read

On paper, write the effective policy for the diagram in the Diagrams tab, then change one rule (for example, set inheritFromParent: false on the project) and predict the new result. Check your prediction against a sandbox project with --effective. The habit of predicting first prevents most policy accidents.

Real cases (typical, anonymised)

  • Regions by contract. A financial team had to keep customer data in two regions. Setting gcp.resourceLocations on the production folder, with the value group for the allowed regions, made new buckets and datasets in other regions fail. Existing resources were found with an Asset Inventory query and moved during a planned window, not by the policy.
  • The unexpected exception. A project team asked to be allowed one public VM for a vendor test. The platform team did not edit the folder policy. They created a tag value exception-public-ip, bound it to the one project for 30 days, and used a conditional rule. The exception expired and left a record.
  • Dry-run saves a Friday. Before enforcing compute.requireOsLogin on all projects, a team enabled dry-run for two weeks. The log showed an old build pipeline that created instances with project metadata that disabled OS Login. They fixed the pipeline, then enforced the rule with no incident.

Practices

  • One owner, one repository. Every Organization Policy lives in Terraform in the organization layer. Folder-level exceptions are pull requests with a reviewer from security.
  • Dry-run, read, enforce. A new constraint is dry-run for at least one business cycle, then enforced on sandbox, then nonprod, then prod.
  • Short names, clear exceptions. Prefer folders and tags for exceptions. Avoid project-level overrides that set enforce: false, because they are invisible to reviewers who read only the organization file.
  • Protect the switch. Limit roles/orgpolicy.policyAdmin to a platform group. Alert on audit events SetOrgPolicy and on changes to google_org_policy_policy in Terraform plans.
  • Start from the baseline. The enterprise foundations blueprint ships a reviewed list of constraints. Use it as the starting list, and remove entries deliberately, with a reason written next to each.
Security note. The person who can change an Organization Policy can remove every guardrail in this hour. Treat orgpolicy.policy.set like resourcemanager.organizations.setIamPolicy: reviewed membership, strong authentication, and an alert when anyone uses it.
Change risk. Enforcing a list or boolean constraint can break deployments that are running right now, for example a scheduled job that creates a VM with an external IP. Announce, dry-run, enforce, and keep the rollback command (org-policies delete) written in the change ticket.

Symptoms and first checks

SymptomLikely causeFirst check
Constraint constraints/... violated for project ...The effective policy forbids the requested configurationgcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective, then find which ancestor sets the rule
PERMISSION_DENIED ... orgpolicy.policy.set when you set a policyMissing roles/orgpolicy.policyAdmin on that nodegcloud organizations get-iam-policy ORG_ID and the folder equivalent, filtered to your identity
NOT_FOUND from describe without --effectiveNo policy is set on that node (it only inherits)Add --effective, or run list on the parent
Policy is set but a resource still violates itThe resource existed before enforcement; the rule is not retroactiveCloud Asset Inventory search for the property; fix the resource
Project override seems ignoredParent rule is denyAll and the child merges with inheritFromParent: true; deny winsRead the effective policy; set inheritFromParent: false only if the exception is intended
etag mismatch or ABORTED on updateSomeone changed the policy after you downloaded the filegcloud org-policies describe ... again, merge, retry
API error orgpolicy.googleapis.com has not been usedThe API is disabled in the calling projectgcloud services enable orgpolicy.googleapis.com --project=PROJECT_ID
Change takes minutes to applyPolicy propagation is eventually consistentWait a few minutes, then retry the blocked action

Triage order

  1. Read the exact error text. A line that names a constraints/... means Organization Policy, not IAM.
  2. Run describe --effective on the project for that constraint.
  3. Walk up the hierarchy with gcloud projects describe PROJECT_ID --format="value(parent)" and list on each parent to find where the rule is set.
  4. Check for a tag condition on the rule and whether the resource carries the tag.
  5. Decide: fix the request, use the approved exception path, or change the policy through review. Never switch the rule off first and ask later.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Organization Policy Service overview · Understanding hierarchy evaluation · Organization Policy constraints reference · Dry-run policies.

or score ≥ 70% on the quiz

Module 2 · Essential constraint catalogue

06–13 · Eight constraints that every landing zone enforces, what each blocks, and how to test it
ConstraintsBaselineLeast exposure7 min
Learning objectives
  • Name eight baseline constraints and state in one sentence what each one blocks.
  • Write the policy file for a boolean constraint and for a list constraint, and choose the right node for each.
  • Test a constraint safely by checking the effective policy first and by expecting a denial.

The short answer

A landing zone does not enable every constraint. It enables a baseline that removes the commonest causes of incidents: leaked keys, public data, public machines, default networks and resources in the wrong country. Each constraint below is cheap to enforce on a new organization and costly to retrofit, so decide them early and put them in code.

The catalogue

ConstraintTypeWhat it blocksTypical value
iam.disableServiceAccountKeyCreationBooleanCreating user-managed service account keys (JSON or P12 files)enforce: true
iam.allowedPolicyMemberDomainsListGranting roles to identities from other domains, and to allUsers or allAuthenticatedUsersYour Cloud Identity customer ID
gcp.resourceLocationsListCreating resources outside the approved regionsin:eu-locations or a list of regions
compute.vmExternalIpAccessListVMs with a public (external) IP addressdenyAll: true
compute.requireOsLoginBooleanVM access by project or instance SSH keys in metadata; requires IAM-based OS Loginenforce: true
compute.skipDefaultNetworkCreationBooleanThe automatic default network and its default firewall rules in new projectsenforce: true
storage.uniformBucketLevelAccessBooleanNew buckets that use object ACLs; all access goes through IAMenforce: true
sql.restrictPublicIpBooleanCloud SQL instances with a public IPv4 addressenforce: true

What each constraint really does

1. iam.disableServiceAccountKeyCreation

Why. A key file is a password that never expires unless you set an expiry. It is copied to laptops, chat messages and Git history. How. The IAM API refuses serviceAccounts.keys.create. Existing keys still work, so list and rotate them (Module 6 shows how findings help). Alternatives. Attached service accounts on Compute Engine, Cloud Run and GKE; impersonation with --impersonate-service-account; Workload Identity Federation for GitHub and other clouds (Hour 2). Its sibling iam.disableServiceAccountKeyUpload blocks uploading your own public key material.

2. iam.allowedPolicyMemberDomains (domain restricted sharing)

Why. Without it, any project owner can grant a role to a personal email address, or to allUsers, and make a bucket public. How. A list of directory customer IDs; only principals that belong to those accounts can appear in new IAM bindings. Service accounts of your own projects are accepted. Gotcha. Partners, auditors and some Google-managed service agents are outside your domain. Add their customer ID, or use a conditional exception on a dedicated folder.

3. gcp.resourceLocations

Why. Data-residency rules and latency plans. How. Values may be regions (europe-west1), multi-regions, or value groups such as in:eu-locations, in:us-locations, in:asia-southeast1-locations. A deny list also works. Gotcha. Some services have global resources that the constraint cannot restrict, and a few APIs create hidden resources in default locations. Test each service you use. Do not assume that "enforced" means "complete".

4. compute.vmExternalIpAccess

Why. A VM with a public address is reachable by the whole internet unless a firewall says otherwise. How. A list of allowed VM instance URIs (projects/PROJECT_ID/zones/ZONE/instances/NAME) or denyAll: true. This is the constraint you will enforce in the Hour 3 lab. Alternatives. Cloud NAT for outbound traffic, Identity-Aware Proxy for admin access, load balancers for inbound traffic.

5. compute.requireOsLogin

Why. SSH keys in metadata cannot be tied to a Google identity, are rarely rotated and bypass IAM review. How. VMs use OS Login: SSH access is granted with roles/compute.osLogin or roles/compute.osAdminLogin, and every login maps to a user. Gotcha. Old images, service-to-service SSH and third-party agents sometimes rely on metadata keys. Use dry-run first.

6. compute.skipDefaultNetworkCreation

Why. The default network is an auto-mode network with a subnet in every region and rules that allow SSH, RDP and ICMP from anywhere. How. The project starts with no network, and the network team supplies a Shared VPC (Hour 4). Gotcha. It only affects projects created after enforcement. Delete default networks in older projects with a reviewed script.

7. storage.uniformBucketLevelAccess

Why. Object ACLs hide who can read an object. How. New buckets must use uniform bucket-level access, so IAM is the only access system. Pair it with storage.publicAccessPrevention to block public buckets as a second layer.

8. sql.restrictPublicIp

Why. A database on a public address attracts scanning and brute-force traffic. How. New Cloud SQL instances must use private IP. Gotcha. The VPC needs private services access (a peering range) before instances can be created at all, so plan that in the network layer.

When to use which node

ConstraintSet onReason
Key creation, domains, default network, uniform access, public SQLOrganizationNo legitimate exception; consistent everywhere
Resource locationsOrganization with a folder-level overrideDifferent business units may have different regions
External IP, OS LoginOrganization or the production and nonprod foldersA sandbox folder may need a tagged exception

Also consider

  • iam.automaticIamGrantsForDefaultServiceAccounts: stops default service accounts from getting the broad Editor role automatically.
  • storage.publicAccessPrevention: blocks buckets and objects from being public.
  • compute.disableSerialPortAccess, compute.vmCanIpForward, compute.trustedImageProjects, run.allowedIngress.
  • Custom constraints for rules that Google does not provide, written in CEL.

Common misunderstandings

  • "If we enforce all eight, we are secure." They remove common exposures. They do not replace IAM review, network design, logging or detection.
  • "A constraint deletes the bad things that already exist." It does not. Run an inventory query (Module 6) and fix existing resources.
  • "Domain restricted sharing breaks partners." It does if you add no exception. The fix is a customer-ID allow list or a separate folder, not switching the rule off.
Order of rollout. Start with the rules that block risk and rarely break pipelines: key creation, default network, uniform access. Then add the ones that change daily work: external IP, OS Login, locations. Dry-run every one.
Credentials and identity iam.disableServiceAccountKeyCreation iam.allowedPolicyMemberDomains Who can hold a secret, who can be granted access Compute and network exposure compute.vmExternalIpAccess compute.skipDefaultNetworkCreation What is reachable from the internet Data and access paths storage.uniformBucketLevelAccess sql.restrictPublicIp How data is exposed and who sees it Location and operator access gcp.resourceLocations compute.requireOsLogin Where data lives, how admins log in

Figure 1. The baseline grouped by risk. When you are asked "why this constraint?", answer with the group and the incident it prevents.

1. Inventory Asset search for existing violations 2. Dry-run dryRunSpec on a lab folder 3. Read logs fix pipelines and agree exceptions 4. Enforce sandbox, nonprod, then prod Rollback path gcloud org-policies delete CONSTRAINT --folder=FOLDER_ID restores inheritance in one command. Keep the command in the change ticket before you start step 4.

Figure 2. A safe rollout. Never skip the inventory step: the policy will not tell you about resources that already exist.

The animation shows one baseline constraint at work: compute.skipDefaultNetworkCreation. Watch where the decision is made. The Compute Engine API reads the effective policy when it enables the service in the new project and then does not create the default network.

The files below use placeholders. Replace ORG_ID, FOLDER_ID and PROJECT_ID. Each write command is free: it changes policy metadata and creates no billed resource.

Boolean constraint: iam.disableServiceAccountKeyCreation

Purpose. Blocks service account key creation on a folder.

name: folders/FOLDER_ID/policies/iam.disableServiceAccountKeyCreation
spec:
  rules:
  - enforce: true
gcloud org-policies set-policy sa-keys.yaml
gcloud iam service-accounts keys create /dev/null --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com
ERROR: (gcloud.iam.service-accounts.keys.create) FAILED_PRECONDITION: Key creation is not allowed on this service account.
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com
    type: constraints/iam.disableServiceAccountKeyCreation

Flags. --iam-account names the service account. The output file path /dev/null is a safety net: if the constraint is not enforced and the key is created, no file with a secret is written to disk, but the key still exists and must be deleted. Prefer to run this test only after describe --effective says enforce: true. IDs in the expected output are illustrative.

List constraint: iam.allowedPolicyMemberDomains

Purpose. Allows only your own directory to appear in IAM bindings. First read your customer ID.

gcloud organizations list --format="value(displayName,owner.directoryCustomerId)"
example.com	C01abc2de
name: organizations/ORG_ID/policies/iam.allowedPolicyMemberDomains
spec:
  rules:
  - values:
      allowedValues:
      - C01abc2de
gcloud org-policies set-policy domains.yaml

Common errors. After enforcement, adding a person with another domain fails with One or more users named in the policy do not belong to a permitted customer. Do not remove the rule; add the partner's customer ID if there is a contract.

List constraint: gcp.resourceLocations

Purpose. Restricts new resources to European locations on the production folder.

name: folders/FOLDER_ID/policies/gcp.resourceLocations
spec:
  rules:
  - values:
      allowedValues:
      - in:eu-locations
gcloud org-policies set-policy locations.yaml
gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --location=us-central1
ERROR: (gcloud.storage.buckets.create) HTTPError 412: 'us-central1' violates constraint 'constraints/gcp.resourceLocations' on the resource 'projects/123456789012'.

Flags. --location sets the bucket location. Value groups use the prefix in:. If the constraint is not yet enforced, this command creates a bucket (low cost for an empty bucket); delete it with gcloud storage buckets delete gs://BUCKET_NAME. Check gcloud org-policies set-policy --help for the flags in your SDK version.

Terraform equivalent

Purpose. Keeps the baseline in version control, which is how production changes it.

resource "google_org_policy_policy" "no_default_network" {
  name   = "organizations/${var.org_id}/policies/compute.skipDefaultNetworkCreation"
  parent = "organizations/${var.org_id}"

  spec {
    rules {
      enforce = "TRUE"
    }
  }
}

resource "google_org_policy_policy" "no_external_ip" {
  name   = "folders/${var.folder_id}/policies/compute.vmExternalIpAccess"
  parent = "folders/${var.folder_id}"

  spec {
    rules {
      deny_all = "TRUE"
    }
  }
}

Note. Use Terraform 1.x with the Google provider and pin the major version in required_providers. Argument names are those of the provider documentation; run terraform validate to confirm them for your provider version.

Check a whole baseline at once

Purpose. Print the effective state of the eight constraints for one project. Read-only and free.

for C in iam.disableServiceAccountKeyCreation iam.allowedPolicyMemberDomains gcp.resourceLocations \
         compute.vmExternalIpAccess compute.requireOsLogin compute.skipDefaultNetworkCreation \
         storage.uniformBucketLevelAccess sql.restrictPublicIp; do
  echo "== $C"
  gcloud org-policies describe "$C" --project=PROJECT_ID --effective --format="yaml(spec.rules)"
done
== iam.disableServiceAccountKeyCreation
spec:
  rules:
  - enforce: true
== compute.vmExternalIpAccess
spec:
  rules:
  - allowAll: true

Reading it. A line with allowAll: true or enforce: false is a gap. A constraint that returns no rules uses the default of the constraint, which is usually "not restricted".

Production use. Run this loop on a schedule with a read-only identity and send the result to a log. A baseline that is correct on day one and drifts by day ninety is the usual failure.

Lab 2: audit the baseline of your sandbox (about 10 minutes of the module, free)

Goal. Find out which of the eight baseline constraints are already enforced for a sandbox project, record the gaps, and write the policy files for the missing ones, without applying them.

Prerequisites. roles/orgpolicy.policyViewer on the project or its parents, the Organization Policy API enabled, a sandbox project (PROJECT_ID). Applying the files is optional and needs roles/orgpolicy.policyAdmin on a lab folder. IDs in the expected output are illustrative.

  1. Set export PROJECT_ID=lab-sandbox-1234.
  2. Run the loop from the commands tab and save the output: ... | tee baseline-before.txt.
  3. For each constraint, mark it as enforced, not enforced or list restricted in a small table.
  4. Read your customer ID: gcloud organizations list --format="value(owner.directoryCustomerId)". If it is empty, you have no organization; write "none" and skip the domain policy.
  5. Write sa-keys.yaml, domains.yaml and locations.yaml exactly as in the commands tab, with your own IDs. Do not apply them to the organization.
  6. Verify the files parse as YAML: python -c "import yaml,sys; yaml.safe_load(open('sa-keys.yaml'))" (any YAML linter works).
  7. Optional, on a lab folder only: apply sa-keys.yaml and check gcloud org-policies describe iam.disableServiceAccountKeyCreation --folder=FOLDER_ID shows enforce: true.
  8. Optional: confirm the denial with gcloud iam service-accounts keys create /dev/null --iam-account=SA_EMAIL. Expect FAILED_PRECONDITION.
  9. Cleanup the optional step: gcloud org-policies delete iam.disableServiceAccountKeyCreation --folder=FOLDER_ID.
== compute.skipDefaultNetworkCreation
spec:
  rules:
  - enforce: true
== sql.restrictPublicIp
(empty)

Expected result. A table of eight lines with the state of each constraint and a list of gaps. In an organization created after 2024, several lines show enforce: true already; in an older one most are empty.

Verification. Re-run the loop after step 9 and diff against baseline-before.txt. The two files must match, which proves the cleanup restored inheritance.

Cost. Free. No billed resource is created. If you run the optional denial test while the constraint is not enforced, the key is created: delete it with gcloud iam service-accounts keys delete KEY_ID --iam-account=SA_EMAIL.

Cleanup. Step 9, and remove the local YAML files.

Real cases (typical, anonymised)

  • The key in the repository. A scan of a public repository found a service account key from a retired project. The key still worked because nobody had listed keys. The organization then enforced iam.disableServiceAccountKeyCreation, rotated the existing keys into Workload Identity Federation over six weeks, and added a finding alert for any new user-managed key.
  • Public bucket by a helpful engineer. A bucket of exported reports was made public to share one file. iam.allowedPolicyMemberDomains would have blocked the binding; the team had not enforced it because a partner needed access. The fix was the partner's customer ID in the allow list and storage.publicAccessPrevention on the same folder.
  • The default network. A new project created for a demo had the default network, whose rule allowed SSH from 0.0.0.0/0. The security team enforced compute.skipDefaultNetworkCreation, deleted default networks in old projects after a dependency check, and added a Terraform module that creates the project without them.

Practices

  • Version the baseline in the organization layer of Terraform, one resource per constraint, with a comment that states the reason.
  • Write the exception process before you enforce: tag, folder, time limit, approver.
  • Tell project teams in advance which constraints exist and which error text to expect. A short page in the internal wiki saves many tickets.
  • Review the baseline every quarter against the current Google Cloud reference, because new constraints and managed versions are added regularly.
Security note. Do not exempt a whole project by setting enforce: false in the project because "we will fix it later". The override is invisible in the organization file and tends to live for years. Use a tagged, expiring exception.
Service agents. Domain restricted sharing can block Google-managed service agents from receiving roles in some cases. Test infrastructure changes in a sandbox before enforcing on production, and read the denial message to see which member was refused.

Symptoms and first checks

SymptomLikely causeFirst check
Key creation is not allowed on this service accountiam.disableServiceAccountKeyCreation is enforcedUse impersonation or Workload Identity Federation; describe --effective to confirm the rule
One or more users named in the policy do not belong to a permitted customerDomain restricted sharingIdentify the member's domain; add its customer ID only if a contract exists
'REGION' violates constraint 'constraints/gcp.resourceLocations'Region not in the allowed listRead the effective value of the constraint; choose an allowed region
Constraint constraints/compute.vmExternalIpAccess violatedVM requested an external IPRemove --address and external access config; use --no-address with Cloud NAT
Cannot SSH after enabling OS LoginUser lacks roles/compute.osLogin or the VM uses metadata keysgcloud compute instances describe INSTANCE --format="value(metadata.items)" and the IAM role
New project has no network, deployment fails with "network not found"compute.skipDefaultNetworkCreation enforcedAttach the project to a Shared VPC or create a custom network
Bucket creation fails with ACL errorstorage.uniformBucketLevelAccess enforcedCreate with --uniform-bucket-level-access; remove ACL settings from the template
Cloud SQL creation fails on public IPsql.restrictPublicIp enforcedUse --no-assign-ip with private services access, or request an exception

Triage order

  1. Copy the constraint name from the error text.
  2. Run describe --effective on the project and read the rules.
  3. Locate the node that sets the rule (organization, folder or project) with list on each ancestor.
  4. Pick the legitimate fix: change the request, use a tagged exception, or change the policy through review.
  5. Record the decision in the change ticket and, for exceptions, add an expiry date.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Organization Policy constraints reference · Restricting resource locations · Restricting identities by domain · Security foundations guide.

or score ≥ 70% on the quiz

Module 3 · Assured Workloads and regulated folders

13–20 · Compliance regimes, data residency and sovereignty controls, and when a regulated folder is worth its cost
Assured WorkloadsCompliance regimesData residency7 min
Learning objectives
  • Explain what an Assured Workloads folder adds on top of the baseline constraints of Module 2.
  • Decide for a given workload whether it needs a regulated folder, using regime, data location and support-access requirements.
  • Describe the operating rules of a regulated folder: how it is created, what you must not change, and how violations are reported.

The short answer

Assured Workloads is a Google Cloud service that creates a regulated folder (called a workload) for a compliance regime (合规体系) or a data residency requirement. The service configures controls on that folder, such as allowed locations, allowed services, encryption settings and support personnel conditions, and it monitors the folder for violations. It is the step after the baseline constraints: the baseline makes every project safer; a regulated folder makes a few projects match a named framework.

What a regulated folder gives you

  • Location control. New resources can be created only in the regions that the regime allows. This is enforced through gcp.resourceLocations set on the workload folder.
  • Service control. Only the Google Cloud services that are covered by the regime can be used in the folder, enforced through a restriction on service usage. A service that is not covered is not available there.
  • Encryption control. The workload is created with key management settings; some regimes require customer-managed keys or key access justification so that you can see and approve key use.
  • Personnel and support conditions. Some packages limit who at Google can support the workload (for example, personnel located in a region or holding a particular status) and provide transparency into administrative access. These conditions are contractual; they are not something you configure with a flag.
  • Monitoring. The folder is checked against the package. When a policy is changed or a resource breaks a control, a violation is reported with a suggested remediation.

Regimes and packages (examples, check the current list)

FamilyExamplesTypical reason to use it
US governmentFedRAMP Moderate and High, CJIS, DoD Impact Levels, ITARContract with a US agency or its suppliers
Health and financeHIPAA and HITRUST-related packagesProtected health information with specific controls
Regional data residencyData residency and support packages for the EU, Canada, Australia, Japan and other regionsLaw or contract that requires data and support in a region
Sovereign controlsPackages built with local partners for sovereign requirementsGovernment or critical infrastructure customers

The names and availability of regimes, locations and supported services change. Read the Assured Workloads documentation for your region before you commit to a design.

Why it exists

Building the same controls by hand takes weeks and has gaps: a missed service, a forgotten key setting, an old project in a wrong region. A regulated folder turns the regime into a package that is applied once, tracked, and monitored. The auditor then sees one named folder with known controls and a record of changes, instead of a spreadsheet.

How it works internally

  1. An administrator with roles/assuredworkloads.admin on the organization creates a workload: name, regime, location and billing account.
  2. The service creates a folder under the organization (or a parent folder you choose) and the supporting resources that the regime needs, for example resources for key management.
  3. The service sets organization policies on that folder: allowed locations, allowed services and others from the package. They are inherited by every project that you create inside.
  4. You create projects inside the folder. Each project's resources obey the folder's policies.
  5. The service monitors the folder. If the policies are changed or a resource violates a control, a violation appears in the Assured Workloads console, in notifications and in audit logs.

Residency, sovereignty and compliance are different questions

TermAsksTools
Data residencyWhere is the data stored and processed?gcp.resourceLocations, regional services, regional buckets and datasets
Data sovereigntyWho can access it, and under which legal authority?CMEK or external keys, access justification, local support packages, contracts
ComplianceCan you show that required controls are in place?Assured Workloads package, audit logs, evidence, your own control framework
Exfiltration protectionCan data be copied to an unapproved place?VPC Service Controls (Module 4), IAM, egress rules

When to use it

  • A named regime applies by law or contract (a government contract, health data rules, a regional sovereignty rule).
  • The auditor or customer asks for a defined control package and monitoring, not only for locations.
  • The workload is separable: it can live in its own folder with its own projects, network and keys.

When not to use it

  • You only need data in one region and have no regime. A location constraint and a folder do the job.
  • The workload needs a Google Cloud service that the package does not cover. You will be blocked.
  • You cannot afford the extra process: a separate folder, restricted services, quicker reviews and extra cost. Check the pricing page for your package; this course does not quote prices.

What it is confused with

ControlRelation to Assured Workloads
Organization Policy baseline (Modules 1 and 2)Assured Workloads uses Organization Policy to apply its controls. The baseline applies to every project; the regulated folder adds a package on top.
VPC Service Controls (Module 4)A different layer: API perimeters. Regulated workloads commonly use both, because location and service limits do not stop a user from copying data to an allowed place that is outside the perimeter.
CMEK (Module 5)Encryption keys under your control. Some packages require them; Assured Workloads does not remove the need to manage them.
A separate organizationA stronger isolation that is rarely needed. A regulated folder is usually enough, and keeps one identity, one billing view and one policy tree.

Common misunderstandings

  • "Our app is now FedRAMP (or HIPAA) compliant." The platform controls are part of the story. Your application, access reviews, logging, incident handling and documentation are yours.
  • "We can put any project in there later." Existing resources may conflict with the allowed locations and services. Create projects in the folder, and migrate data with a plan.
  • "An administrator can relax a rule for a test." Weakening the folder's policies creates a violation and breaks the evidence. Test in another folder.
  • "Residency means support staff are local." Location of data and location of support personnel are separate; only certain packages address the second.
Scope of this module. This course explains the design and operating rules of Assured Workloads. It does not create a real workload, because creation is tied to your organization, billing and contract. The hands-on lab uses read-only commands and a design worksheet.
Organization baseline constraints (Module 2) Folder: production normal workloads · baseline only Assured Workloads folder regime package · locations · services prj-app-a (any allowed region) prj-eu-app (EU locations only) Added by the workload gcp.resourceLocations (allowed regions) service usage restriction (covered services) key management settings · violation monitoring Create projects inside the regulated folder; do not move old projects in without a plan.

Figure 1. A regulated folder sits beside normal folders and inherits the organization baseline. Look at the shaded box: those controls exist only on the regulated folder.

Does a named regime apply? yes no Are all needed services covered by the package? Is a data location rule the only requirement? yes Assured Workloads folder new projects inside it yes gcp.resourceLocations on a normal folder if no: redesign the workload or ask for a different package if no: baseline plus VPC Service Controls and CMEK

Figure 2. A simple decision path. Start with the legal requirement, then check service coverage, and choose the lightest control that is sufficient.

The animation shows a regulated folder from creation to a blocked request. The first three steps happen once, inside the service. The last three are the daily effect: a project inherits the folder's controls, a disallowed location is refused, and changes are recorded.

This course does not create Assured Workloads folders, because creation depends on your organization, a billing account and a contract. The commands below are read-only and show how to find and inspect a regulated folder that already exists. Check gcloud assured workloads --help for the flags in your SDK version; the group is part of the gcloud assured command family and its availability can differ between release tracks.

gcloud assured workloads list

Purpose. Lists the workloads in an organization and a location, so you can see which folders are regulated. Cost: free (read-only).

gcloud assured workloads list --organization=ORG_ID --location=LOCATION

Flags. --organization is the numeric organization ID; --location is the location of the workload (a region or multi-region such as europe-west3 or us, depending on the package). The output includes the workload resource name and its display name. Check the help for the exact columns.

Common errors. PERMISSION_DENIED means you need roles/assuredworkloads.reader (or admin) on the organization. SERVICE_DISABLED means the Assured Workloads API must be enabled in the project that you call from: gcloud services enable assuredworkloads.googleapis.com --project=PROJECT_ID (free).

gcloud assured workloads describe

Purpose. Shows the compliance regime, the workload folder, the resources that the service created, and the settings of the workload. Cost: free.

gcloud assured workloads describe organizations/ORG_ID/locations/LOCATION/workloads/WORKLOAD_ID

Reading it. Look for the complianceRegime field, the folder name in resources, and any kmsSettings or similar key settings. Copy the folder ID for the next command.

Inspect the policies of the regulated folder

Purpose. Shows what the workload set. This is plain Organization Policy, so you already know the command. Cost: free.

gcloud org-policies list --folder=WORKLOAD_FOLDER_ID
gcloud org-policies describe gcp.resourceLocations --folder=WORKLOAD_FOLDER_ID

Reading it. You should see a location list and a service-usage restriction. The values come from the package. Do not edit these policies; to change a control, change the workload through Assured Workloads or choose another package.

Create a project inside the regulated folder

Purpose. New projects inherit the controls. Creating a project is free; resources you later create inside it can cost money. Cost: free for the project itself.

gcloud projects create PROJECT_ID --folder=WORKLOAD_FOLDER_ID --labels=env=regulated,owner=platform
Create in progress for [https://cloudresourcemanager.googleapis.com/v1/projects/prj-eu-app].
Waiting for [operations/cp.123456789012345678] to finish...done.

Flags. --folder sets the parent; --labels adds labels for cost allocation. Billing must be linked with gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID, and some regimes require a billing account that is attached to the workload. IDs in the expected output are illustrative.

Find the violations

Purpose. Violations appear in the Assured Workloads page of the Google Cloud console and can be sent as notifications. Use the console for the list and use audit logs for who changed the policy:

gcloud logging read 'protoPayload.methodName:"SetOrgPolicy" OR protoPayload.methodName:"SetPolicy"' --folder=WORKLOAD_FOLDER_ID --limit=10 --freshness=7d --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName)"

Note. Method names and fields in audit logs depend on the service version. Open one entry in Logs Explorer and copy the filter. Cost: reading logs is free; log storage follows Cloud Logging pricing.

Production use. Create workloads with Terraform in the organization layer (the Google provider has an Assured Workloads resource; check its documentation for the arguments in your provider version) so that the regime, location and billing account are reviewed in a pull request.

Lab 3: classify workloads and prepare a regulated-folder design (about 10 minutes of the module, free)

Goal. Decide which of four example workloads need a regulated folder, record the controls each needs, and, if an Assured Workloads folder already exists in your environment, inspect it with read-only commands.

Prerequisites. A text editor. For the optional read-only part: roles/assuredworkloads.reader and roles/orgpolicy.policyViewer on the organization. If you have no organization or no workload folder, do only the worksheet. IDs in expected output are illustrative.

  1. Copy this worksheet into a file and complete it. Columns: workload, data type, law or contract, required location, support-staff condition, services needed, decision.
  2. Workload A: a public marketing website with no personal data. Expected decision: baseline only.
  3. Workload B: customer records of an EU retailer, contract says "stored in the EU". Expected decision: baseline plus gcp.resourceLocations with in:eu-locations on the folder.
  4. Workload C: a government agency's case system in the US that must meet FedRAMP High. Expected decision: Assured Workloads folder with the matching regime; verify that every service you need is covered.
  5. Workload D: a research notebook platform that needs a new Google Cloud service. Check the supported-services list for your regime; if the service is not covered, redesign or choose another folder.
  6. Optional, read-only: run gcloud assured workloads list --organization=ORG_ID --location=LOCATION. If a workload exists, run describe and note the regime.
  7. Optional: run gcloud org-policies describe gcp.resourceLocations --folder=WORKLOAD_FOLDER_ID and compare the allowed values with your worksheet.
  8. Write a six-line "rules of the regulated folder" note: create new projects only inside it, never edit the folder's policies, tag every project with an owner, review violations weekly, keep keys under the agreed control, and record each exception.
name: folders/777777777777/policies/gcp.resourceLocations
spec:
  rules:
  - values:
      allowedValues:
      - in:eu-locations

Expected result. A completed worksheet with a decision for each workload, and, if you had access, a note of the regime and allowed locations of an existing regulated folder.

Verification. Ask a colleague to read the worksheet without help. They must be able to say, for each workload, which requirement caused the decision. If they cannot, the "law or contract" column is too vague.

Cost. Free. Read-only commands only. Do not create a workload during this lab.

Cleanup. None. Delete the local worksheet if it contains real contract names.

Real cases (typical, anonymised)

  • One regulated folder, three projects. A healthcare software team put only the patient-data services in a regulated folder: an application project, a data project and a key project. Marketing sites and internal tools stayed in normal folders. The audit scope became small, and the other teams did not inherit the restrictions.
  • The unsupported service. A data-science team designed a pipeline around a service that the chosen package did not cover. The deployment failed at the service-usage restriction. The fix was to move that stage to a normal folder with de-identified data and to keep only identified data in the regulated folder.
  • A policy edited "for a test". An administrator relaxed the location rule on a regulated folder to test a service. The service reported a violation, the auditor asked for an explanation, and the team spent a week documenting it. The new rule: tests run in a sandbox folder; the regulated folder is changed only through pull requests.

Practices

  • Keep the regulated scope as small as possible: fewer projects, fewer services, fewer people with access.
  • Create a separate network (and, if required, a separate VPC Service Controls perimeter) for the regulated projects, so that data cannot flow out by accident.
  • Manage keys with Cloud KMS in a dedicated project; know who can approve key use, and test what happens when a key is disabled (Module 8 does this for CMEK).
  • Send violation notifications to a monitored group. Review them weekly and record each remediation.
  • Keep a mapping from each control in your regime to the evidence: a policy, a log query, a ticket. Auditors ask for evidence, not for settings.
  • Re-check the supported-services and locations list each quarter. They change, and so can the regime.
Security note. A regulated folder does not protect against a compromised administrator. Limit who holds roles/assuredworkloads.admin and roles/orgpolicy.policyAdmin, use strong authentication, and alert on any change of policy inside the folder.
Cost and speed. Regulated packages restrict services, may add costs for support and key operations, and slow product adoption. Record the business reason before you start so that the cost has an owner.

Symptoms and first checks

SymptomLikely causeFirst check
Cannot create a resource in the folder: violates constraint gcp.resourceLocationsRegion is outside the package's allowed locationsgcloud org-policies describe gcp.resourceLocations --project=PROJECT_ID --effective
API or service not available: Request is prohibited by organization's policy or a service-usage violationThe service is not covered by the regime and is restricted in the folderRead the effective gcp.restrictServiceUsage policy and the package's supported-services page
Violation reported on the workloadA policy was changed or a resource breaks a controlOpen the violation in the Assured Workloads page; read audit logs for the change
PERMISSION_DENIED when listing or creating workloadsMissing roles/assuredworkloads.* on the organizationgcloud organizations get-iam-policy ORG_ID filtered to your identity
SERVICE_DISABLED for assuredworkloads.googleapis.comAPI not enabled in the calling projectgcloud services enable assuredworkloads.googleapis.com --project=PROJECT_ID
Project move into the folder fails or creates violationsExisting resources conflict with controlsList resources with gcloud asset search-all-resources --scope=projects/PROJECT_ID and compare locations and services
Key-related error after creating the workloadKey settings of the package are not met, or the key is disabledCheck the key state in Cloud KMS and the workload's key settings

Triage order

  1. Read the full error. Does it name a constraint? Then it is Organization Policy applied by the workload.
  2. Read the effective policy on the project and find which folder sets it.
  3. Decide whether the request is legitimate for this regime. If not, move the work to another folder.
  4. If a control seems wrong, ask the compliance owner and the Assured Workloads documentation, not the project team. Do not weaken the policy to unblock a deployment.
  5. Record the outcome, so the next engineer sees the same answer.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Assured Workloads overview · Supported products · Compliance resource center · Security foundations guide.

or score ≥ 70% on the quiz

Module 4 · VPC Service Controls

20–28 · Service perimeters, access levels, ingress and egress rules, dry-run and the usual blockers
VPC Service ControlsPerimetersAccess Context Manager8 min
Learning objectives
  • Explain how a service perimeter limits the Google APIs of the projects inside it, and why IAM alone does not prevent data exfiltration.
  • Build the objects of a perimeter in the right order: access policy, access level, perimeter in dry-run mode, then enforcement.
  • Read a VPC Service Controls denial and decide whether it needs an access level, an ingress rule or an egress rule.

The short answer

VPC Service Controls (VPC 服务控制) creates a service perimeter (边界) around Google Cloud projects. Inside the perimeter, the restricted services (for example storage.googleapis.com and bigquery.googleapis.com) accept calls from other projects in the same perimeter. A call that crosses the boundary is denied, unless an access level, an ingress rule or an egress rule allows it. The control works at the Google API layer, not at the packet layer, which makes it a complement to firewalls and not a replacement.

Why it exists: the exfiltration gap

Suppose an engineer holds roles/storage.objectViewer on a sensitive bucket and also roles/storage.admin on a personal project. With IAM only, a copy from one to the other is allowed. A stolen token, a mistaken grant, or a compromised service account gives the same power to an attacker. A perimeter denies the copy because the destination project is outside the perimeter. It protects against four things: data exfiltration through APIs, theft of credentials used from unknown networks, misconfigured public access to private data, and copying data to resources owned by someone else.

What: the objects

ObjectWhat it isWhere it lives
Access policyThe container of levels and perimeters. One organization-wide policy; scoped policies can exist for folders or projectsAccess Context Manager, accessPolicies/POLICY_ID
Access levelA named condition: IP ranges, a device policy, regions, or specific identitiesInside the access policy
Service perimeterA set of projects (by number) plus restricted services, optional access levels, ingress and egress rulesInside the access policy
Perimeter bridgeA link that lets two perimeters exchange data. Often replaced by ingress and egress rulesInside the access policy
VPC accessible servicesA list that limits which APIs the VMs in the perimeter can reach on their networkPerimeter setting

How a request is evaluated

  1. A client calls a restricted service (for example, storage.googleapis.com) on a project that is inside a perimeter.
  2. IAM runs as usual. If IAM denies, the request ends.
  3. VPC Service Controls checks the source. If the caller is a resource inside the same perimeter, the call passes.
  4. Otherwise the service looks for an access level that the request satisfies (the perimeter lists the levels it accepts), then for an ingress rule that matches the identity, source and target method.
  5. If the request touches resources in two perimeters, or one inside and one outside, the egress rules of the source side and the ingress rules of the target side are also checked.
  6. If nothing matches, the API returns 403 with Request is prohibited by organization's policy and a vpcServiceControlsUniqueIdentifier. The violation is written to audit logs.

Access levels, ingress and egress: which tool to use

NeedUseExample
Admins on the corporate network or managed laptops reach the console and APIsAccess levelIP subnetworks of the office VPN, device policy
A named pipeline outside the perimeter reads or writes specific services insideIngress ruleCI service account → storage.googleapis.com on one project
Workloads inside the perimeter call a service in another project or perimeterEgress ruleApplication project → shared Artifact Registry or a vendor project
Two perimeters exchange data frequentlyMatching egress and ingress rules (or a bridge)Prod data perimeter and analytics perimeter
Quick troubleshooting of one blocked callThe audit log with the unique identifierLook up violationReason and the target resource

Dry-run mode

Each perimeter has two configurations: the enforced one (status) and the dry-run one (spec). A perimeter that has only a dry-run configuration blocks nothing. Requests that would be denied by the dry-run configuration are written to audit logs with dryRun set to true. When the log is quiet, you enforce the dry-run configuration with a single command.

When to use it

  • Sensitive data in BigQuery, Cloud Storage, Cloud SQL (via supported services), Pub/Sub, Secret Manager or Cloud KMS that must not leave a defined set of projects.
  • Regulated workloads (Module 3), where the control is expected in addition to the location rules.
  • Shared data platforms where many teams read data, and the organization wants to prevent accidental copying to personal projects.

When it is the wrong tool

  • You want to block a network flow between VMs: use firewall policies (Hour 4).
  • You need to forbid one configuration, such as a public IP: use Organization Policy (Module 1).
  • The service you need is not yet supported by VPC Service Controls. Check the supported products list before you design.

What it is confused with

ControlWorks onLimit
VPC Service ControlsGoogle API calls and their contextDoes not stop packets between VMs
Firewall rules and policiesNetwork packetsDo not understand which Google API or project is called
Private Google AccessWhether a VM without external IP can reach Google APIsDoes not restrict which projects it reaches
IAM ConditionsWho and when for a bindingCannot express "only from these projects" for data copy
Organization PolicyResource configurationCannot stop a copy to an allowed place that you do not own

Common misunderstandings

  • "The perimeter is a network." It is not a VPC. A VM in a project inside a perimeter can still be reached on the network according to firewall rules.
  • "Console users are not affected." They are. The console calls the same APIs from the user's browser; users outside an access level are blocked from restricted services inside the perimeter.
  • "Dry-run is just a plan." It is real evaluation of real calls, written to real logs, which is why it is the only trustworthy way to find blockers.
  • "One perimeter for everything is simplest." A very large perimeter becomes a list of exceptions. Use a few perimeters by data sensitivity and wire them with explicit rules.
  • "Changes apply instantly." Perimeter updates can take several minutes to propagate. Wait before you conclude that a rule does not work.
Access policy scope. An organization has one access policy for the whole organization and may add scoped policies for folders or projects, to delegate administration. Decide who holds roles/accesscontextmanager.policyAdmin before you create the first perimeter.
Service perimeter: prod_perimeter restricted: storage · bigquery · secretmanager · cloudkms prj-data BigQuery · buckets project number 111 prj-app Cloud Run · jobs project number 222 calls inside the perimeter pass CI runner outside · service account ci-deployer ingress Office VPN access level corp_ips prj-shared-registry outside perimeter Artifact Registry egress Personal project no rule: copy is denied (403) Order of work: access policy → access levels → perimeter in dry-run → read audit logs → add rules → enforce. Every allowed crossing is an explicit object that a reviewer can read in Terraform.

Figure 1. A perimeter with two projects. Follow the arrows that cross the dashed boundary: each one is an access level, an ingress rule or an egress rule. The red box shows the copy that the perimeter exists to stop.

API call with credentials IAM check role allows? Perimeter check same perimeter? Access level or ingress / egress Allowed API runs 403 IAM permission name 403 VPC Service Controls unique identifier + violationReason Read the error first: a permission name means IAM, a unique identifier means a perimeter.

Figure 2. The two checks are independent. A request must pass IAM and the perimeter. The two error messages look alike for a minute and need different fixes.

The animation follows a call from Cloud Shell, which is outside the perimeter, to a protected bucket. The identity has the right IAM role, but the perimeter still denies the call and records the reason. Notice that the audit log entry is the thing you will use to design the fix.

All commands need the Access Context Manager API (accesscontextmanager.googleapis.com) and a role such as roles/accesscontextmanager.policyAdmin on the organization. Perimeters and access levels are free. Check gcloud access-context-manager --help for the flags in your SDK version; some subcommands and flags have changed between releases.

gcloud access-context-manager policies list

Purpose. Finds the access policy of the organization. You need its ID for every other command. Cost: free.

gcloud access-context-manager policies list --organization=ORG_ID
NAME          ORGANIZATION  SCOPES  TITLE            ETAG
330193482019  123456789012          default policy   42c8d5c9f9a1b0e2

Common errors. An empty list means no policy exists yet. Create the single organization policy with gcloud access-context-manager policies create --organization=ORG_ID --title="default policy" after you agree with the security team who will administer it. IDs in the expected output are illustrative.

gcloud access-context-manager levels create (write)

Purpose. Creates an access level from a YAML specification. Cost: free.

# corp-ips.yaml
- ipSubnetworks:
  - 203.0.113.0/24
  - 198.51.100.0/25
gcloud access-context-manager levels create corp_ips \
  --policy=POLICY_ID \
  --title="Corporate egress IPs" \
  --basic-level-spec=corp-ips.yaml
Create request issued for: [corp_ips]
Waiting for operation [accessPolicies/330193482019/accessLevels/corp_ips/operations/...] to complete...done.

Flags. --policy is the access policy ID; --title is the display name; --basic-level-spec takes the file. The IP ranges above are documentation examples; use your own egress addresses. A basic level can also hold members (identities), regions and device policies.

gcloud access-context-manager perimeters dry-run create (write)

Purpose. Creates a perimeter that only has a dry-run configuration. Nothing is blocked. Cost: free.

PROJECT_NUMBER=$(gcloud projects describe PROJECT_ID --format="value(projectNumber)")

gcloud access-context-manager perimeters dry-run create lab_perimeter \
  --policy=POLICY_ID \
  --perimeter-title="Lab perimeter" \
  --perimeter-type=regular \
  --perimeter-resources="projects/${PROJECT_NUMBER}" \
  --perimeter-restricted-services=storage.googleapis.com \
  --perimeter-access-levels="accessPolicies/POLICY_ID/accessLevels/corp_ips"

Flags. Resources are project numbers, not project IDs. --perimeter-restricted-services takes API names; add bigquery.googleapis.com and others as needed. The dry-run group has its own flags with the --perimeter- prefix; read gcloud access-context-manager perimeters dry-run create --help before you rely on any flag name. After the command, perimeters list --policy=POLICY_ID shows the perimeter with its dry-run configuration.

gcloud access-context-manager perimeters describe and list

Purpose. Shows both the enforced configuration (status) and the dry-run configuration (spec). Cost: free.

gcloud access-context-manager perimeters describe lab_perimeter --policy=POLICY_ID
name: accessPolicies/330193482019/servicePerimeters/lab_perimeter
title: Lab perimeter
perimeterType: PERIMETER_TYPE_REGULAR
spec:
  accessLevels:
  - accessPolicies/330193482019/accessLevels/corp_ips
  resources:
  - projects/987654321098
  restrictedServices:
  - storage.googleapis.com
useExplicitDryRunSpec: true

Reading it. A perimeter with spec and useExplicitDryRunSpec: true and no status is dry-run only.

Ingress and egress rules from a file

Purpose. Allows a named pipeline to call Cloud Storage inside the perimeter. The files are applied to the dry-run configuration or the enforced configuration of a perimeter.

# ingress.yaml
- ingressFrom:
    identities:
    - serviceAccount:ci-deployer@CI_PROJECT_ID.iam.gserviceaccount.com
    sources:
    - accessLevel: '*'
  ingressTo:
    operations:
    - serviceName: storage.googleapis.com
      methodSelectors:
      - method: '*'
    resources:
    - projects/PROJECT_NUMBER
gcloud access-context-manager perimeters update lab_perimeter \
  --policy=POLICY_ID \
  --set-ingress-policies=ingress.yaml

Flags. --set-ingress-policies and --set-egress-policies replace the full list with the file content. For a dry-run configuration use the perimeters dry-run update group and its flags (gcloud access-context-manager perimeters dry-run update --help). Prefer a named identity and a narrow method list over ANY_IDENTITY and '*'; use the wildcard only while you are in dry-run to discover what is needed.

Read the violations

Purpose. Finds calls that were or would be blocked. The audit metadata type is VpcServiceControlAuditMetadata. Cost: reading is free; log storage follows Cloud Logging pricing.

gcloud logging read 'protoPayload.metadata.@type="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata"' \
  --project=PROJECT_ID --freshness=1d --limit=5 \
  --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.serviceName,protoPayload.metadata.violationReason,protoPayload.metadata.dryRun)"
TIMESTAMP                    PRINCIPAL_EMAIL        SERVICE_NAME             VIOLATION_REASON         DRY_RUN
2026-11-25T09:14:03.112Z     dev@example.com        storage.googleapis.com   NO_MATCHING_ACCESS_LEVEL True

Reading it. NO_MATCHING_ACCESS_LEVEL suggests an access level or an ingress rule; RESOURCES_NOT_IN_SAME_SERVICE_PERIMETER suggests an egress or ingress rule between two projects. Violations are logged in the project that is the target of the request (and, for some calls, in the source project). Field names can change; copy the working filter from one entry in Logs Explorer.

gcloud access-context-manager perimeters dry-run enforce (write)

Purpose. Promotes the dry-run configuration of a perimeter to enforced. This is the moment real calls can start failing. Cost: free.

gcloud access-context-manager perimeters dry-run enforce lab_perimeter --policy=POLICY_ID

Rollback. Keep the previous configuration in Terraform. The quick rollback is to delete the perimeter or remove the project from its resources: gcloud access-context-manager perimeters delete lab_perimeter --policy=POLICY_ID.

Production use. Define access policy objects with Terraform (google_access_context_manager_* resources) in a security layer. Changes are made by pull request, and each perimeter has an owner and a documented list of exceptions.

Lab 4: a dry-run perimeter around a sandbox project (about 10 minutes of the module, low cost)

Goal. Create a perimeter in dry-run mode around one sandbox project, trigger a violation from Cloud Shell, read it in audit logs, and delete the perimeter. No call is blocked at any time.

Prerequisites. An organization, an access policy (step 1 tells you), roles/accesscontextmanager.policyAdmin on the organization, roles/logging.viewer on the project, and a sandbox project with billing. If you have no organization, read this tab and use the Diagrams tab: perimeters require an organization. IDs in the expected output are illustrative.

  1. Find the policy ID: gcloud access-context-manager policies list --organization=ORG_ID. Write down the NAME. If the list is empty, ask the owner of the organization to create it; do not create it yourself in a shared organization.
  2. Enable the API in the sandbox project: gcloud services enable accesscontextmanager.googleapis.com storage.googleapis.com --project=PROJECT_ID (free).
  3. Create a bucket for the test. A few kilobytes cost very little (low: usually well under a few USD per day for this lab): gcloud storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --location=REGION --uniform-bucket-level-access.
  4. Put one small object in it: echo hello | gcloud storage cp - gs://BUCKET_NAME/hello.txt.
  5. Read the project number: gcloud projects describe PROJECT_ID --format="value(projectNumber)".
  6. Create the dry-run perimeter with the command from the commands tab (no access level, so every outside caller is a violation).
  7. Verify: gcloud access-context-manager perimeters describe lab_perimeter --policy=POLICY_ID shows a spec section and no status section.
  8. Wait about five minutes for propagation, then read the object again: gcloud storage cat gs://BUCKET_NAME/hello.txt. It must still succeed, because dry-run blocks nothing.
  9. Read the violation log with the query of the commands tab. Expect one or more entries with dryRun true. Log entries can arrive a few minutes late; retry.
  10. Write one sentence for each entry: who called, which service, and which rule would fix it (access level, ingress or egress).
hello

Expected result. The read succeeds, and the log shows a dry-run violation for storage.googleapis.com with a reason such as NO_MATCHING_ACCESS_LEVEL.

Verification. If no log entry appears after ten minutes, check that the project number in resources is right and that storage.googleapis.com is in restrictedServices.

Cost. Perimeters and access levels are free. The bucket and log entries are small: low cost for this lab.

Cleanup.

gcloud access-context-manager perimeters delete lab_perimeter --policy=POLICY_ID
gcloud storage rm --recursive gs://BUCKET_NAME
gcloud access-context-manager perimeters list --policy=POLICY_ID

The last command must no longer list lab_perimeter. Never enforce this lab perimeter on a shared project.

Lab 5 (optional): design a perimeter on paper

For a data platform with a landing project, a processing project and a reporting project, write which projects go in one perimeter, which services are restricted, which identities need an ingress rule (CI, analysts), which egress rules exist (shared registry, vendor), and which access level covers admins. Compare your design with a colleague's.

Real cases (typical, anonymised)

  • Dry-run for a month. A bank placed its analytics projects in a perimeter. Dry-run found a nightly Cloud Build job that exported to a bucket in a vendor project and a business-intelligence tool that connected from an office IP not in any access level. Two ingress rules, one egress rule and one access level fixed both before enforcement.
  • Perimeters by sensitivity. A retail platform used three perimeters: raw customer data, curated analytics and shared tooling. Raw data had no ingress except the ingestion pipeline, curated data accepted analysts from the corporate access level, and a pair of egress and ingress rules moved data one way, from raw to curated.
  • The Terraform state bucket. A platform team placed the state bucket project inside a perimeter without an ingress rule for the CI identity. The next pipeline failed with a VPC Service Controls error. The fix was a narrow ingress rule for the CI service account on storage.googleapis.com for that one project.

Practices

  • Perimeter changes follow the same path as code: pull request, plan, review by security and the data owner, then apply. Emergency edits are logged and imported back.
  • Always start with dry-run and read logs for at least one full business cycle (a month-end for finance).
  • Prefer named identities and methods in rules. Review wildcard rules every quarter.
  • Include the project that holds KMS keys and secrets in the same perimeter, or an unprotected key service becomes the weak side.
  • Give every rule a description with the owner and the ticket, so that an old exception can be questioned.
  • Have a break-glass procedure: a small group that can remove a project from a perimeter during an outage, with an alert and a review after use.
Security note. A perimeter with an ANY_IDENTITY ingress from '*' sources and all methods is an open door with a label on it. Treat broad rules as technical debt with an end date.
Operational risk. Enforcing a perimeter can stop pipelines, scheduled queries, data transfers and console users within minutes. Announce it, enforce at a quiet time, and keep the rollback command ready. Changes may take several minutes to propagate in both directions.

Symptoms and first checks

SymptomLikely causeFirst check
Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: ...Call crossed a perimeter boundary without a matching ruleSearch audit logs for the unique identifier; read violationReason and the source and target
Cloud Build fails to read or write a bucket in the perimeterThe Cloud Build service account runs outside the perimeter or its project is not in itPut the build project in the perimeter, or add an ingress rule for the build service account
BigQuery query fails across projects, or an export to Cloud Storage failsSource and destination are in different perimeters or one is outsideAdd matching egress and ingress rules for bigquery.googleapis.com and storage.googleapis.com, or place both projects in one perimeter
People can no longer open a bucket in the Cloud ConsoleTheir network is not in an access levelCheck the user's IP; add the VPN range to a level or use an identity-based ingress rule
A log sink to a bucket or dataset in the perimeter stops deliveringThe sink's writer identity is outside the perimeterAdd an ingress rule for the writer identity on the destination service
Terraform apply fails with 403 ... VPC_SERVICE_CONTROLSCI identity is outside the perimeter or lacks an ingress ruleRead the unique identifier; add a narrow ingress rule for the CI service account
A rule seems to have no effectPropagation delay, or the rule was added to spec but not to statusWait; run perimeters describe and check which configuration holds the rule
Project cannot be added to a perimeterProject number is wrong, or it already belongs to another regular perimeterCheck the number; a project can be in only one regular perimeter

Triage order

  1. Is the error a VPC Service Controls error (unique identifier) or an IAM error (permission name)?
  2. Find the audit log entry. Read the source (identity, network or access level) and the target (service and project).
  3. Check whether the service is a restricted service of the perimeter and whether both projects are inside.
  4. Choose the narrowest fix: access level for humans, ingress rule for a named outside identity, egress rule for a named outside resource.
  5. Apply to the dry-run configuration first if possible, check the log, then enforce. Remember propagation time.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: VPC Service Controls overview · Supported products · Troubleshooting · Dry-run mode · Access Context Manager.

or score ≥ 70% on the quiz

Module 5 · Keys and secrets

28–35 · Cloud KMS key rings and keys, CMEK, rotation, and Secret Manager for application secrets
Cloud KMSCMEKSecret Manager7 min
Learning objectives
  • Create a Cloud KMS key ring and a symmetric encryption key with automatic rotation, and explain why key rings and keys cannot be deleted.
  • Explain what customer-managed encryption keys (CMEK) change compared with Google-managed encryption, and who must be granted access to the key.
  • Store, version and read an application secret in Secret Manager with a least-privilege role instead of putting it in code or in a key file.

The short answer

Cloud KMS (密钥管理服务) is the service that creates, stores and uses cryptographic keys. Secret Manager (密钥管理) is the service that stores sensitive values such as passwords, API tokens and certificates. They are often confused, but they solve different problems: KMS controls keys that encrypt data, Secret Manager controls values that an application must read.

Google Cloud already encrypts data at rest by default with Google-managed keys. The landing zone question is not "is it encrypted?" but "who controls the key, who can use it, and can we prove and revoke that?". That is what customer-managed encryption keys (CMEK, 客户管理加密密钥) answer.

What: the Cloud KMS resource model

ResourceWhat it isCan it be deleted?
Key ringA named container for keys in one location (region, multi-region or global).No. Key rings cannot be deleted or renamed.
Key (CryptoKey)A named key with a purpose (for example encryption), an algorithm, a protection level and a rotation schedule.No. Keys cannot be deleted; you destroy their versions.
Key versionThe actual key material. States include enabled, disabled, scheduled for destruction and destroyed.Yes, by scheduled destruction (default 24 hours before the material is destroyed).
Protection levelSOFTWARE, HSM (Cloud HSM) or EXTERNAL (Cloud EKM).Chosen at key creation and not changed afterwards.

The key ring location is part of the key's resource name, for example projects/PROJECT_ID/locations/europe-west3/keyRings/app-ring/cryptoKeys/app-key. A CMEK-protected resource must normally be in the same location as its key (or the key must be in a multi-region or global location that the service supports).

How it works internally: envelope encryption

Services do not send your data to Cloud KMS. They use envelope encryption: a data encryption key (DEK) encrypts the data locally, and the DEK is itself encrypted ("wrapped") by your key encryption key (KEK) in Cloud KMS. Only the small wrapped DEK is stored next to the data. To read, the service asks Cloud KMS to unwrap the DEK, and Cloud KMS checks IAM first. This has three consequences you must remember:

  • Disabling the key disables the data. If the key version is disabled or destroyed, the DEK cannot be unwrapped and the data is unreadable. This is a kill switch and also a risk.
  • Rotation is cheap. A new primary version only changes which version wraps new DEKs. Old data keeps working because the ciphertext records its key version.
  • Every key use is logged. Cloud KMS writes Admin Activity logs for key management and Data Access logs for encrypt, decrypt and wrap operations (the latter must be enabled for the project, folder or organization).

Why: reasons to use CMEK

  • Separation of duties. The team that runs the data service is not the team that controls the key. A dedicated security project holds the keys.
  • Revocation. Disabling a key version stops access to the data even if someone holds valid IAM roles on the data resource.
  • Evidence. Key usage is auditable, which regulators and internal auditors ask for.
  • Policy. Organization Policy can require CMEK: constraints/gcp.restrictNonCmekServices blocks creation of unprotected resources in listed services, and constraints/gcp.restrictCmekCryptoKeyProjects limits which projects may provide keys.

Secret Manager in one page

  • A secret is a named object with metadata (labels, replication policy, rotation settings). The value lives in a secret version. Versions are immutable; you add a new version to change the value.
  • Version states: enabled, disabled, destroyed. Disabling is reversible; destroying is not.
  • Replication policy: automatic (Google chooses regions) or user-managed (you choose the regions, which matters for data residency from Module 2).
  • Access is controlled by IAM: roles/secretmanager.secretAccessor reads values, roles/secretmanager.secretVersionAdder adds versions, roles/secretmanager.admin manages everything. Grant roles on the secret, not on the project, whenever possible.
  • Secrets are encrypted at rest by default; you can also protect them with a CMEK.

When to use which

NeedUseNot
Encrypt a bucket, disk, BigQuery dataset or database with a key you controlCloud KMS with CMEKSecret Manager
Give an application a database password or API tokenSecret ManagerCloud KMS (it does not store arbitrary values)
Prove who used the key and whenCloud KMS audit logsApplication logs
Let a CI pipeline call Google APIsWorkload Identity Federation (Hour 2)A service account key file in a secret

What it is confused with

PairDifference
Cloud KMS vs Secret ManagerKMS keys encrypt data and never leave KMS (for non-exportable keys). Secret Manager returns the stored value to an authorised caller.
CMEK vs CSEKCMEK keys live in Cloud KMS. CSEK (customer-supplied keys) are provided by you on each request and are supported only by a few services; CMEK is the normal choice.
CMEK vs Cloud EKMCloud EKM keeps the key in an external key manager outside Google. CMEK with Cloud KMS keeps it in Google Cloud (software or HSM).
Key rotation vs secret rotationKMS rotation creates a new key version automatically. Secret rotation means changing the secret value at the system that owns it (a database user) and then adding a new secret version; Secret Manager only sends rotation reminders to a Pub/Sub topic.

Common misunderstandings

"CMEK means Google cannot see my data." Not exactly. Google still operates the service, and a service that you authorise can use the key. CMEK gives you control, revocation and audit, not exclusion of the provider.
"I can delete the key ring to clean up." You cannot. Key rings and keys stay. Only key versions are destroyed, and key ring names are reserved forever in that project and location, so a lab name you use today cannot be reused.
"Rotating the key re-encrypts my data." It does not. Re-encryption of existing data is a separate action per service. Keep old versions enabled until the data that depends on them is gone.
Security project: prj-kms Key ring: app-ring (europe-west3) Key: app-key (rotation 90d) purpose: encryption · SOFTWARE v1 enabled v2 primary v0 destroyed Data project: prj-app-a Cloud Storage bucket (CMEK) object data encrypted with a DEK Service agent service-PROJECT_NUMBER@gs-project-accounts has cryptoKeyEncrypterDecrypter on app-key Envelope encryption 1. Service creates a data key (DEK) and encrypts the object locally. 2. Cloud KMS wraps the DEK with app-key; only the wrapped DEK is stored. 3. Reads ask Cloud KMS to unwrap; IAM is checked and the call is logged. 4. Key version disabled or destroyed: the DEK cannot be unwrapped, data is unreadable.

Figure 1. Keys live in a security project, data lives elsewhere. The service agent of the data project is the identity that needs access to the key.

Look at the arrow from the service agent to the key: it is the one IAM binding that most CMEK failures are about. Also note that the key ring and the data are in different projects, which is the recommended separation of duties.

What do you need to protect? Start here Data at rest in a service bucket · disk · dataset · database A value an app must read password · token · certificate Cloud KMS key + CMEK org policy can require it Secret Manager secret secretAccessor on the secret

Figure 2. Choosing between the two services. A key protects data inside a Google service; a secret is a value delivered to your application.

The animation follows one CMEK set-up on a Cloud Storage bucket: key creation, granting the service agent, a write that wraps a data key, the audit record, and the effect of disabling the key version. Watch which identity Cloud KMS checks, because that is the identity you must grant.

Run these in a sandbox project. Key rings, keys and secrets are metadata resources; creating them has a very low cost (see each command). Use a security project that you can afford to keep, because key rings and keys cannot be deleted.

IDs in the expected output are illustrative. Check gcloud kms --help and gcloud secrets --help for the flags in your SDK version.

gcloud services enable cloudkms.googleapis.com secretmanager.googleapis.com

Purpose. Enable the two APIs in the project. Free; enabling an API does not create billable resources by itself.

gcloud services enable cloudkms.googleapis.com secretmanager.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-0a1b2c3d" finished successfully.

Common errors. PERMISSION_DENIED means you lack serviceusage.services.enable (role roles/serviceusage.serviceUsageAdmin), or an Organization Policy restricts which services can be enabled.

gcloud kms keyrings create (write, permanent)

Purpose. Create a key ring in one location. A key ring itself is free of charge; keys and key versions are billed according to their protection level and use.

gcloud kms keyrings create app-ring \
  --location=europe-west3 \
  --project=PROJECT_ID

Flags. --location must match the location of the data you will protect (or be a location the service supports). The name is permanent. There is no output on success unless you ask for a format.

gcloud kms keyrings list --location=europe-west3 --project=PROJECT_ID
NAME
projects/PROJECT_ID/locations/europe-west3/keyRings/app-ring

Common errors. ALREADY_EXISTS means that name was used before in this project and location, even if you thought you cleaned up. PERMISSION_DENIED requires roles/cloudkms.admin on the project or key ring.

gcloud kms keys create (write, low cost)

Purpose. Create a symmetric encryption key with an automatic rotation schedule. A software-protected key costs a small amount per active key version per month; operations are metered. Use a sandbox project and destroy the version after the lab.

gcloud kms keys create app-key \
  --keyring=app-ring \
  --location=europe-west3 \
  --purpose=encryption \
  --rotation-period=90d \
  --next-rotation-time=2027-03-01T00:00:00Z \
  --project=PROJECT_ID

Flags. --purpose=encryption creates a symmetric key (other purposes include asymmetric signing and decryption). --rotation-period sets how often a new primary version is created, and --next-rotation-time sets the first rotation; use a future UTC timestamp. --protection-level (default software) can be hsm for Cloud HSM. Check gcloud kms keys create --help for the flags in your SDK version.

gcloud kms keys describe app-key --keyring=app-ring --location=europe-west3 --project=PROJECT_ID
createTime: '2026-11-25T09:30:12.431Z'
name: projects/PROJECT_ID/locations/europe-west3/keyRings/app-ring/cryptoKeys/app-key
nextRotationTime: '2027-03-01T00:00:00Z'
primary:
  algorithm: GOOGLE_SYMMETRIC_ENCRYPTION
  name: projects/PROJECT_ID/locations/europe-west3/keyRings/app-ring/cryptoKeys/app-key/cryptoKeyVersions/1
  protectionLevel: SOFTWARE
  state: ENABLED
purpose: ENCRYPT_DECRYPT
rotationPeriod: 7776000s
versionTemplate:
  algorithm: GOOGLE_SYMMETRIC_ENCRYPTION
  protectionLevel: SOFTWARE

gcloud kms keys add-iam-policy-binding (write, free)

Purpose. Let the service agent of a data service use the key. Bind on the key, not on the project, so a compromise of that agent cannot touch every key.

gcloud kms keys add-iam-policy-binding app-key \
  --keyring=app-ring --location=europe-west3 \
  --member="serviceAccount:service-PROJECT_NUMBER@gs-project-accounts.iam.gserviceaccount.com" \
  --role="roles/cloudkms.cryptoKeyEncrypterDecrypter" \
  --project=PROJECT_ID

Flags. PROJECT_NUMBER is the number of the project that owns the bucket (not its ID). To show the Cloud Storage service agent of a project, run gcloud storage service-agent --project=DATA_PROJECT_ID.

Updated IAM policy for key [app-key].
bindings:
- members:
  - serviceAccount:service-123456789012@gs-project-accounts.iam.gserviceaccount.com
  role: roles/cloudkms.cryptoKeyEncrypterDecrypter
etag: BwXabc123Def=
version: 1

gcloud storage buckets update --default-encryption-key (write, free)

Purpose. Make new objects in a bucket use the CMEK by default. Existing objects keep their old encryption until they are rewritten.

gcloud storage buckets update gs://BUCKET_NAME \
  --default-encryption-key=projects/PROJECT_ID/locations/europe-west3/keyRings/app-ring/cryptoKeys/app-key
Updating gs://BUCKET_NAME/...
  Completed 1

Common errors. 403 ... Permission denied on Cloud KMS key means the service agent binding above is missing. The key is in a different location than the bucket means region mismatch.

gcloud secrets create and versions add (write, very low cost)

Purpose. Create a secret and add its first version. Secret Manager bills per active secret version and per access operation, with a free tier; a lab with one secret stays very low. Never put a real secret in a lab.

gcloud secrets create lab-db-password \
  --replication-policy=automatic \
  --project=PROJECT_ID

printf 'not-a-real-secret' | gcloud secrets versions add lab-db-password \
  --data-file=- \
  --project=PROJECT_ID
Created secret [lab-db-password].
Created version [1] of the secret [lab-db-password].

Flags. --replication-policy=automatic lets Google choose storage regions; for residency requirements use user-managed replication with the documented --locations flag (check gcloud secrets create --help). --data-file=- reads the value from standard input, so it does not appear in the command history of a file.

gcloud secrets versions access (read, per-access cost)

Purpose. Read a secret value. Each access is an audited operation. Pin a numeric version in production and use latest only where a rolling update is acceptable.

gcloud secrets versions access 1 --secret=lab-db-password --project=PROJECT_ID
not-a-real-secret

Common errors. PERMISSION_DENIED: Permission 'secretmanager.versions.access' denied means the caller lacks roles/secretmanager.secretAccessor on the secret. NOT_FOUND usually means a wrong project or a destroyed version.

gcloud secrets add-iam-policy-binding (write, free)

Purpose. Allow one workload identity to read one secret.

gcloud secrets add-iam-policy-binding lab-db-password \
  --member="serviceAccount:app-runtime@PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor" \
  --project=PROJECT_ID

gcloud kms keys versions disable (write, free, reversible)

Purpose. Disable a key version so that the data it protects becomes unreadable. This is the kill switch. Enable it again with enable and the data returns.

gcloud kms keys versions disable 1 \
  --key=app-key --keyring=app-ring --location=europe-west3 --project=PROJECT_ID
Production use. Keep keys in a dedicated project with its own folder policy, rotate at least yearly (many teams use 90 days), grant cryptoKeyEncrypterDecrypter on the key to service agents only, and alert on key version state changes through the audit log. Put the key creation in Terraform, and set prevent_destroy on key resources.
Warning. gcloud kms keys versions destroy is irreversible after the scheduled period. Never destroy a version that protects data you still need.

Lab: a CMEK bucket and a secret, with a kill-switch test (about 20 minutes, low cost)

Goal. Create a key ring and key, protect a bucket with it, prove that disabling the key version blocks reads, and store and read a fake secret with a least-privilege role.

Prerequisites. A sandbox project with a budget set (Hour 1), the Cloud KMS and Secret Manager APIs enabled, and these roles on the project: roles/cloudkms.admin, roles/storage.admin, roles/secretmanager.admin. Use no real secrets. Remember that the key ring and key you create here will remain after cleanup, so use a name such as lab-ring in a sandbox project.

IDs in the expected output are illustrative. Budgets send alerts and do not cap spend.

  1. Set variables.
    export PROJECT_ID=PROJECT_ID
    export REGION=europe-west3
    export BUCKET=lab-cmek-$PROJECT_ID
    export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
  2. Create the key ring and key. Use the two commands from the previous tab with lab-ring and lab-key.

    Verify: gcloud kms keys list --keyring=lab-ring --location=$REGION --project=$PROJECT_ID lists lab-key with state ENABLED for the primary.

  3. Create the Cloud Storage service agent and grant it the key.
    gcloud storage service-agent --project=$PROJECT_ID
    gcloud kms keys add-iam-policy-binding lab-key \
      --keyring=lab-ring --location=$REGION \
      --member="serviceAccount:service-${PROJECT_NUMBER}@gs-project-accounts.iam.gserviceaccount.com" \
      --role="roles/cloudkms.cryptoKeyEncrypterDecrypter" \
      --project=$PROJECT_ID

    Verify: gcloud kms keys get-iam-policy lab-key --keyring=lab-ring --location=$REGION shows the service agent in the binding.

  4. Create the bucket with the default key.
    gcloud storage buckets create gs://$BUCKET \
      --location=$REGION --uniform-bucket-level-access --project=$PROJECT_ID \
      --default-encryption-key=projects/$PROJECT_ID/locations/$REGION/keyRings/lab-ring/cryptoKeys/lab-key

    Verify: gcloud storage buckets describe gs://$BUCKET --format="value(default_kms_key)" prints the key resource name.

  5. Write and read an object.
    echo "hello cmek" | gcloud storage cp - gs://$BUCKET/hello.txt
    gcloud storage cat gs://$BUCKET/hello.txt
    hello cmek
  6. Prove the kill switch. Disable the key version and read again.
    gcloud kms keys versions disable 1 --key=lab-key --keyring=lab-ring --location=$REGION --project=$PROJECT_ID
    gcloud storage cat gs://$BUCKET/hello.txt
    ERROR: (gcloud.storage.cat) HTTPError 403: Permission denied on Cloud KMS key. Please ensure that your Cloud KMS key is enabled and that the Cloud Storage service agent has permission to use it.

    The exact wording may differ. The point is that the read fails although your IAM roles on the bucket did not change. Enable the version again:

    gcloud kms keys versions enable 1 --key=lab-key --keyring=lab-ring --location=$REGION --project=$PROJECT_ID
    gcloud storage cat gs://$BUCKET/hello.txt
  7. Create and read a fake secret. Use the secret commands from the previous tab and name the secret lab-db-password.

    Verify: gcloud secrets versions list lab-db-password --project=$PROJECT_ID shows version 1 as enabled.

  8. Find the key use in the audit log.
    gcloud logging read 'protoPayload.serviceName="cloudkms.googleapis.com" AND protoPayload.methodName:"UpdateCryptoKeyVersion"' --limit=3 --project=$PROJECT_ID --format="value(timestamp,protoPayload.authenticationInfo.principalEmail)"

    The disable and enable operations from step 6 appear with your identity.

Expected result. The bucket is CMEK-protected, reads fail while the key version is disabled and succeed after re-enabling, the secret can be read by you, and the audit log records the key version changes.

Cost. Low (usually well under a few USD per day for this lab): one software key version, one tiny object and one secret version.

Cleanup.

gcloud storage rm -r gs://$BUCKET
gcloud secrets delete lab-db-password --project=$PROJECT_ID --quiet
gcloud kms keys versions destroy 1 --key=lab-key --keyring=lab-ring --location=$REGION --project=$PROJECT_ID

The destroy command schedules destruction (the version is not removed immediately). The key ring and key remain by design; they have no cost when they hold no enabled versions. If you created the project only for this lab, deleting the project removes everything except the reserved names.

Real cases

  • Keys in the application project. A team created CMEK keys in the same project as the data. A developer with project owner rights could disable the key, and the same people who ran the service also controlled access to it. The platform team moved keys into a dedicated security project with a key ring per environment and bound only the service agents on each key.
  • The disabled key outage. A cleanup script disabled "unused" key versions. A database in another project could no longer be read, and the incident lasted until the version was re-enabled. The fix was an alert on key version state changes, a naming convention for keys in use, and removal of destroy rights from automation.
  • Secrets in a Git repository. A service account key and a database password were found in a repository during an audit. The team moved the password to Secret Manager with one secret per environment, replaced the key file with Workload Identity Federation, rotated both, and added a constraint that blocks service account key creation (Module 2).

Practices

  • Centralise keys in a security project, one key ring per environment and location, and keep key creation in Terraform with prevent_destroy.
  • Rotate keys on a schedule, and keep old versions enabled until the data that depends on them is gone. Test the restore path before relying on it.
  • Use roles/cloudkms.cryptoKeyEncrypterDecrypter for services, and keep roles/cloudkms.admin away from anyone who uses the data. Admins manage keys but cannot encrypt or decrypt with them.
  • Enable Data Access audit logs for Cloud KMS and Secret Manager at the organization or folder level, and send them to the central log project (Hour 6).
  • One secret per purpose and environment, read by one service account. Pin versions in production, and plan the rotation of the underlying credential, not only the secret version.
  • Require CMEK for sensitive services with constraints/gcp.restrictNonCmekServices, and restrict key projects with constraints/gcp.restrictCmekCryptoKeyProjects.
  • Consider Cloud HSM for keys whose protection level is mandated, and Cloud EKM only when you must keep key material outside Google; both add cost and latency, and EKM adds an availability dependency.
Security note. Do not create service account key files to read secrets. Use the identity of the workload (attached service account, Workload Identity for GKE, or Workload Identity Federation outside Google Cloud). A secret read from a key file only moves the problem.
Cost note. Key and secret costs grow with active versions and operations. Destroy old key versions and disable unused secret versions when the data lifecycle allows it, and avoid reading a secret on every request; cache it in the process for a short time.

Symptoms and first checks

SymptomLikely causeFirst check
Permission denied on Cloud KMS key when a service writes dataThe service agent lacks cryptoKeyEncrypterDecrypter on the keygcloud kms keys get-iam-policy KEY --keyring=RING --location=LOCATION; confirm the agent for that project number
Data became unreadable overnightKey version disabled or scheduled for destructiongcloud kms keys versions list --key=KEY --keyring=RING --location=LOCATION; then re-enable if destruction is not complete
Cannot create a CMEK resource: location mismatchKey and resource are in different locationsCompare the location in the key name with the resource location
ALREADY_EXISTS creating a key ringKey ring names are permanent in a project and locationgcloud kms keyrings list --location=LOCATION; choose a new name
PERMISSION_DENIED secretmanager.versions.accessCaller lacks roles/secretmanager.secretAccessor on the secret, or the wrong identity is usedgcloud secrets get-iam-policy SECRET; gcloud auth list
Secret read returns an old valueApplication pinned a version or cached the valuegcloud secrets versions list SECRET; check which version the app requests
Creating a resource is blocked: CMEK requiredgcp.restrictNonCmekServices is enforcedgcloud org-policies describe gcp.restrictNonCmekServices --project=PROJECT_ID --effective

Triage order

  1. Read the exact error text; KMS errors name the key and the operation.
  2. Check the key version state, then the key IAM policy, then the location.
  3. Find the caller in the audit log (cloudkms.googleapis.com) to see which identity failed.
  4. Check Organization Policy constraints on CMEK and VPC Service Controls (Module 4) if the call is blocked before IAM.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Cloud KMS documentation · Customer-managed encryption keys · Secret Manager documentation.

or score ≥ 70% on the quiz

Module 6 · Detection and posture

35–42 · Security Command Center findings, Security Health Analytics, Cloud Asset Inventory and finding triage
Security Command CenterAsset InventoryTriage7 min
Learning objectives
  • Explain the difference between preventive guardrails (Organization Policy, VPC Service Controls) and detective controls (Security Command Center findings), and why a landing zone needs both.
  • Query Cloud Asset Inventory with gcloud asset search-all-resources and search-all-iam-policies to answer "what exists and who can access it" across an organization.
  • Triage a Security Command Center finding in a fixed order (severity, exposure, owner, fix or accept) instead of trying to clear every finding.

The short answer

Preventive controls (Organization Policy, VPC Service Controls, IAM) stop actions. Detective controls find what slipped through, what existed before the guardrail, and what a guardrail cannot express. Security Command Center (安全指挥中心, SCC) is the central place to see detective results. Cloud Asset Inventory (云资产清单) is the searchable index of what exists. Together they answer two questions an auditor asks: "what do you have?" and "what is wrong with it?".

What: Security Command Center

  • Findings. Each finding has a category (for example PUBLIC_BUCKET_ACL or OPEN_FIREWALL), a severity (critical, high, medium, low), a state (active or inactive), the affected resource and a source (the detector or service that produced it).
  • Sources and services. Built-in services include Security Health Analytics (misconfigurations), Web Security Scanner (web application scans), Event Threat Detection and Container Threat Detection (threats from logs and runtime, in higher tiers), and Rapid Vulnerability Detection. Third-party tools can also write findings.
  • Tiers. SCC is offered in tiers (Standard, Premium, and Enterprise, which adds multi-cloud and case management). Which detectors are available depends on the tier and on what is activated, so check the current documentation and your contract. Do not assume the paid features exist in a sandbox.
  • Scope. SCC is activated at the organization level. Findings are visible from the organization, and access to them is controlled with IAM roles such as roles/securitycenter.findingsViewer and roles/securitycenter.admin.
  • Mute rules and notifications. You can mute findings that are accepted or expected, and you can publish new findings to a Pub/Sub topic to feed a ticket system.

What: Cloud Asset Inventory

  • Search (search-all-resources, search-all-iam-policies): near-real-time queries across a scope (organization, folder or project) without needing access to each project individually, but only if you have the asset-search permissions at that scope.
  • Export (gcloud asset export): a snapshot of resources or IAM policies to Cloud Storage or BigQuery, which is the base for reports and drift checks (Hour 6).
  • Analysis (gcloud asset analyze-iam-policy): "who can access this resource" and "what can this principal access", including inheritance and group membership.
  • Feeds: Pub/Sub notifications when a resource or policy changes.
  • History: a limited retention of the change history of an asset (documentation lists the current window).

How it works internally: the detection loop

  1. Resources and policies change. Asset Inventory captures the new state from the service APIs.
  2. Detectors compare that state with a rule (for example "a bucket is readable by allUsers").
  3. A finding is created or updated. When the resource is fixed, the next scan sets the state to inactive; a finding does not vanish silently.
  4. Notifications and exports carry the finding to people and ticket systems.
  5. Owners fix the resource, accept the risk with a mute rule, or the platform team adds a guardrail so that the class of problem cannot recur.

Why: preventive and detective together

ControlWhen it actsExampleWeakness
PreventiveBefore the changecompute.vmExternalIpAccess denies external IPsCannot cover rules that depend on context; does not fix old resources
DetectiveAfter the changeSCC finding for a public bucketThe exposure exists until someone acts
CorrectiveAfter detectionAutomation that removes a public ACLNeeds careful testing, or it breaks workloads

When to use it

Turn on SCC and the asset inventory for the organization before you onboard workloads, set up one notification channel, and give a named team ownership of the queue. The first scan on an existing organization will show many findings. That is expected; start with the critical and high findings on internet-facing resources.

What it is confused with

PairDifference
SCC vs Cloud Audit LogsAudit logs record who called which API (Hour 6). SCC evaluates configuration and threats and produces findings. Some SCC threat detectors read audit logs.
SCC vs Cloud MonitoringMonitoring watches metrics and availability. SCC watches security posture.
Asset Inventory vs gcloud ... listlist works per project and per service API. Asset Inventory searches across a scope with one query and one permission.
Security Health Analytics vs Organization PolicySHA reports problems that already exist. Organization Policy prevents new ones. Use SHA to decide which constraints to enforce next.
Recommender vs SCCRecommender (for example IAM recommendations) suggests permission and cost improvements. SCC reports security findings.

Common misunderstandings

"A finding is an incident." Most findings are configuration risks, not proof of compromise. Treat threat findings (for example from Event Threat Detection) as incidents; treat misconfiguration findings as work to schedule by risk.
"Zero findings is the goal." The goal is no unowned, unexplained critical findings. Accepted exceptions are muted with a reason and a review date; they are not deleted.
"SCC is on, so we are protected." SCC reports. It does not block. Without owners, notifications and guardrails, findings simply accumulate.
Resources buckets · firewalls IAM · VMs · keys Asset Inventory index · history search · export · feeds Detectors Security Health Analytics threat detection (tiers) SCC findings category · severity state · resource Pub/Sub notification ticket · chat · SIEM Owner decides fix · accept · prevent fix resource, rescan Reading the picture Asset Inventory is the memory (what exists, who has access). Detectors apply rules to it. SCC holds the results. Owners close the loop: fix the resource, mute with a reason, or add a guardrail (Organization Policy) so the same finding cannot appear again.

Figure 1. The detection loop. A finding is only useful if it reaches an owner and the loop returns to the resource or to a guardrail.

Look at the arrow that returns from "Owner decides" to the resources: that is the part that is missing when SCC "is on" but nothing improves.

1. Severity 2. Exposure 3. Owner 4. Decision critical and high first internet reachable? data? labels · project · folder fix · accept · prevent Fixchange the resource, rescan Acceptmute with reason and review date Preventadd constraint or Terraform check Every finding ends in one of three outcomes; "ignore" is not an outcome.

Figure 2. Triage order. Severity and exposure decide urgency, the owner decides who acts, and the outcome is fix, accept or prevent.

The animation follows one firewall change from creation to a closed finding. Each step is a real interaction: Asset Inventory captures the configuration, a detector evaluates it, SCC stores the finding, a notification goes out, and the owner is found with an asset search.

These commands are read-only unless stated. They need roles at the scope you query, for example roles/cloudasset.viewer on the organization for Asset Inventory and roles/securitycenter.findingsViewer for SCC. Reading metadata is free; exports to BigQuery or Cloud Storage cost for the storage they use.

IDs in the expected output are illustrative. Check gcloud asset --help and gcloud scc --help for the flags in your SDK version; SCC commands have changed across API versions.

gcloud services enable cloudasset.googleapis.com

Purpose. Enable the Cloud Asset API in the project that you use for queries (the quota and billing project). Free.

gcloud services enable cloudasset.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-4e5f6a7b" finished successfully.

gcloud asset search-all-resources (read, free)

Purpose. Find resources across an organization, folder or project. Use it to inventory buckets, VMs or any asset type.

gcloud asset search-all-resources \
  --scope=organizations/ORG_ID \
  --asset-types=storage.googleapis.com/Bucket \
  --format="table(name,location,project)"
NAME                                              LOCATION      PROJECT
//storage.googleapis.com/prod-data-bucket         EUROPE-WEST3  projects/111111111111
//storage.googleapis.com/lab-cmek-prj-sandbox     EUROPE-WEST3  projects/222222222222

Flags. --scope is organizations/ORG_ID, folders/FOLDER_ID or projects/PROJECT_ID. --asset-types filters by type; --query uses the search syntax (for example --query="labels.env=prod"); --format shapes the output.

Common errors. PERMISSION_DENIED: cloudasset.assets.searchAllResources means the role is missing at the scope. A SERVICE_DISABLED error means the API is not enabled in the quota project.

gcloud asset search-all-resources --query (read, free)

Purpose. Find resources by label or name, for example everything that is not labelled with an owner, or every VM that carries a given label.

gcloud asset search-all-resources \
  --scope=organizations/ORG_ID \
  --asset-types=compute.googleapis.com/Instance \
  --query="labels.env=prod" \
  --format="table(name,location,labels)"

Use the same pattern to find resources that violate a convention. Not every label key appears in every asset type, so read the result as a lead, not as proof.

gcloud asset search-all-iam-policies (read, free)

Purpose. Find IAM bindings across a scope, for example everything that grants a role to a specific user or to allUsers.

gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:allUsers" \
  --format="table(resource,policy.bindings.role)"
RESOURCE                                      ROLE
//storage.googleapis.com/public-docs-bucket   ['roles/storage.objectViewer']

Why it matters. A public binding such as allUsers is exactly what SCC reports as a public resource. This query finds them even before the first SCC scan.

gcloud asset analyze-iam-policy (read, free)

Purpose. Answer "who can access this resource" with inheritance and group expansion.

gcloud asset analyze-iam-policy \
  --organization=ORG_ID \
  --full-resource-name="//cloudresourcemanager.googleapis.com/projects/PROJECT_ID" \
  --permissions="storage.buckets.get" \
  --expand-groups

Flags. --full-resource-name uses the full resource name format; --permissions or --roles narrow the question; --expand-groups expands group members. Check gcloud asset analyze-iam-policy --help for the flags in your SDK version.

gcloud asset export (write, storage cost)

Purpose. Write a snapshot of resources to Cloud Storage for reports and drift comparison. It writes objects, so it costs the storage used; use a lab bucket and delete it.

gcloud asset export \
  --organization=ORG_ID \
  --content-type=resource \
  --asset-types=compute.googleapis.com/Firewall \
  --output-path=gs://BUCKET_NAME/firewalls.json \
  --project=PROJECT_ID
Export in progress for root asset [organizations/ORG_ID].
Use [gcloud asset operations describe projects/123456789012/operations/ExportAssets/RESOURCE/987654321] to inspect the status of the operation.

gcloud scc findings list (read, free)

Purpose. List active findings. Filtering at the source keeps the output short enough to triage.

gcloud scc findings list ORG_ID \
  --filter='state="ACTIVE" AND severity="HIGH"' \
  --format="table(finding.category,finding.resourceName,finding.severity)"
CATEGORY       RESOURCE_NAME                                              SEVERITY
OPEN_SSH_PORT  //compute.googleapis.com/projects/PROJECT_ID/global/firewalls/allow-ssh  HIGH

Flags. --filter uses the SCC filter syntax; fields live under finding. in some versions and at top level in others. Check gcloud scc findings list --help for the flags in your SDK version. The command requires SCC to be activated for the organization.

Common errors. PERMISSION_DENIED means no securitycenter.findings.list at the organization. NOT_FOUND or an empty list can simply mean SCC is not activated or the first scan has not finished.

Production use. Export findings and assets to BigQuery, build one dashboard per severity and owner, and review it weekly. Use labels such as owner and cost-center (Hour 1) so that a finding can be routed to a team with one query.

Lab: inventory an organization and triage one finding (about 20 minutes, free, no changes)

Goal. Answer three audit questions with Cloud Asset Inventory (what buckets exist, what is public, who has a role) and write a triage decision for one SCC finding, or for one simulated finding if SCC is not activated in your sandbox.

Prerequisites. A sandbox organization or folder. roles/cloudasset.viewer on the scope you query, and the Cloud Asset API enabled in the quota project. For the SCC step, roles/securitycenter.findingsViewer and SCC activated; if it is not, do the simulated triage at the end. If you have no organization, use --scope=projects/PROJECT_ID.

IDs in the expected output are illustrative. All commands here are read-only.

  1. Set the scope.
    export SCOPE=organizations/ORG_ID
    export PROJECT_ID=PROJECT_ID
    gcloud services enable cloudasset.googleapis.com --project=$PROJECT_ID

    Verify: gcloud services list --enabled --filter="name:cloudasset" --project=$PROJECT_ID lists the Cloud Asset API.

  2. Question 1: what buckets exist?
    gcloud asset search-all-resources --scope=$SCOPE --asset-types=storage.googleapis.com/Bucket --format="table(name,location,project)" --billing-project=$PROJECT_ID

    Verify: the table lists buckets from more than one project (if your sandbox has more than one). Note the count.

  3. Question 2: is anything public?
    gcloud asset search-all-iam-policies --scope=$SCOPE --query="policy:allUsers OR policy:allAuthenticatedUsers" --format="table(resource,policy.bindings.role)" --billing-project=$PROJECT_ID

    Verify: an empty result means no public bindings in the indexed scope. If you see rows, the resource names are the starting list for triage.

  4. Question 3: who has an editing role?
    gcloud asset search-all-iam-policies --scope=$SCOPE --query="policy:roles/editor" --format="table(resource,policy.bindings.members)" --billing-project=$PROJECT_ID

    Verify: basic roles on projects are listed. Basic roles are too broad for production (Hour 2); this is the list of projects to clean up.

  5. List active high or critical findings (skip if SCC is not activated).
    gcloud scc findings list ORG_ID --filter='state="ACTIVE" AND (severity="HIGH" OR severity="CRITICAL")' --format="table(finding.category,finding.resourceName,finding.severity)" | head -n 20

    Verify: you have a list of categories and resources, or a clear message that SCC is not active.

  6. Write the triage decision. Pick one finding (or use this simulated one: category OPEN_SSH_PORT, resource firewall allow-ssh, source range 0.0.0.0/0) and fill in this table in your notes:
    QuestionHow to answerYour answer
    SeverityFrom the finding
    Exposuregcloud compute firewall-rules describe NAME and which instances carry the target tag
    OwnerLabels and parent folder from gcloud projects describe PROJECT_ID
    DecisionFix, accept with review date, or prevent with a guardrail
  7. Choose a guardrail for the cause. For the open SSH example, name one preventive control (for example compute.requireOsLogin with IAP TCP forwarding from Hour 4, or a hierarchical firewall policy deny).

Expected result. Three inventory answers with counts, one triage record with an owner and a decision, and one named guardrail.

Cost. Free. The queries are read-only metadata calls.

Cleanup. None. Remove local notes that contain resource names if they are sensitive.

Real cases

  • Thousands of findings on day one. A newly activated SCC showed several thousand findings, and the security team tried to clear them all. They then filtered to critical and high findings on internet-facing resources, handled those in two weeks, and used the remaining list to choose three new Organization Policy constraints so that the same findings stopped appearing.
  • Public bucket found by search, not by scan. An asset search for allUsers bindings found a bucket that held an export of customer data. The scan had not yet reported it. The fix was a removal of the binding, a review of the audit log for access, and the constraint storage.publicAccessPrevention on the folder.
  • Findings without owners. A security queue had findings with no responsible team because projects had no owner label. The platform team added a mandatory owner label in the project factory (Hour 7) and routed notifications by label.

Practices

  • Activate SCC at the organization level and use a dedicated security project for notifications, exports and the Pub/Sub topic.
  • Give findings an owner and a due date by severity (for example critical in days, medium in a quarter). Track mean time to resolve, not only the count.
  • Mute with a reason and a review date. Review mutes every quarter, because an accepted exception can quietly become permanent.
  • Export assets to BigQuery daily, so you can answer questions at any time and compare snapshots for drift.
  • Prefer prevention for repeat findings: turn each frequent finding class into an Organization Policy constraint, a Terraform check or a hierarchical firewall rule.
  • Test automated remediation in a sandbox folder first. An automated "remove public access" can break a legitimate public website.
Security note. Read access to SCC findings and asset search exposes the structure of your environment. Grant roles/securitycenter.findingsViewer and roles/cloudasset.viewer to the security team and auditors only, through groups, and review the audit logs of those roles.
Cost note. SCC tiers and Asset Inventory exports have different pricing. Confirm the tier and the export volume with the current pricing page before you enable organization-wide features, and keep export buckets on a lifecycle rule that deletes old snapshots.

Symptoms and first checks

SymptomLikely causeFirst check
PERMISSION_DENIED on search-all-resourcesMissing roles/cloudasset.viewer at the scopegcloud organizations get-iam-policy ORG_ID filtered to your identity
SERVICE_DISABLED for cloudasset.googleapis.comAPI not enabled in the quota projectPass --billing-project=PROJECT_ID and enable the API in that project
Search results miss a recent resourceIndex delayWait a few minutes and repeat; use the service API list for an immediate check
scc findings list returns nothingSCC not activated, or first scan not complete, or wrong filter fieldsCheck activation in the console; run the command without --filter
Finding stays ACTIVE after the fixRescan has not run, or the fix did not change the detected propertyRe-describe the resource; wait for the next scan; check the finding's recommendation
Thousands of near-identical findingsOne root cause repeated (a default network in every project)Group by category and parent; fix the cause with a constraint
Notification not deliveredPub/Sub topic or subscription misconfiguredCheck the notification config and the topic's IAM for the SCC service account

Triage order

  1. Is it a threat finding or a configuration finding? Threats go to the incident process.
  2. Severity, then exposure (internet reachable, sensitive data).
  3. Find the owner through labels, parent folder and the asset's IAM policy.
  4. Decide: fix, accept with a review date, or prevent. Record the reason.
  5. Confirm the finding turns inactive after the next scan.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use, since product tiers change.

Official reading: Security Command Center documentation · Cloud Asset Inventory overview.

or score ≥ 70% on the quiz

Module 7 · Lab: enforce and prove a constraint

42–52 · Deny external IPs on a lab folder, watch a VM creation fail, read the evidence, and restore
Organization PolicyEvidenceRollback10 min
Learning objectives
  • Write a list-constraint policy as YAML and apply it to a folder with gcloud org-policies set-policy.
  • Prove that the constraint is effective by reading the effective policy and by seeing a real denial, then find the denial in the audit log.
  • Restore the previous state with gcloud org-policies delete and confirm that the guardrail is gone, so that the lab leaves nothing behind.

The short answer

This module is the proof step of the hour. You will enforce one real constraint, constraints/compute.vmExternalIpAccess, on a lab folder, show that it works by a denied request, find the evidence, and roll back. The method matters more than the constraint: read before write, change small, prove by a negative test, collect evidence, restore.

What: the constraint you will use

  • constraints/compute.vmExternalIpAccess is a list constraint. It defines which VM instances may have an external IP address. If the policy is not set, any instance may have one.
  • The policy value is a list of instance resource names that are allowed, or denyAll: true, or allowAll: true.
  • It is enforced at create and update time. It does not remove an external IP from a VM that already exists; it blocks new requests and changes that add one.
  • It needs roles/orgpolicy.policyAdmin to change, on the organization or folder where you set the policy.

Why: the method

StepWhy it existsWhat goes wrong if skipped
Read the effective policy firstYou learn the starting state and any inherited valueYou overwrite a policy that someone else set
Use a lab folderBlast radius is smallA production deployment is blocked
Write the policy as a fileIt can be reviewed, committed and repeatedThe change cannot be reproduced or audited
Negative testShows that the control works, not only that it is setA policy that has no effect is assumed to protect
Read the audit logProduces evidenceAn auditor has only your word
Rollback and verifyLeaves no hidden guardrail in a shared folderThe next lab fails in a confusing way

How it works internally

  1. You send the policy for the constraint and the folder. Organization Policy stores it. The policy is a set of rules: a rule can allow values, deny values, or allow or deny all.
  2. When a service performs an action that the constraint covers, the service asks Organization Policy for the effective policy of the target resource's project. The effective policy merges the policy on the project with inherited policies from the folder and the organization (unless a policy uses a setting to replace inheritance).
  3. The service compares the request with the effective policy. For vmExternalIpAccess, a VM that asks for an external IP is allowed only if its resource name is in the allowed list. With denyAll, nothing is.
  4. If the request violates the policy, the service returns an error and records the call in Cloud Audit Logs.

When to use this pattern

Use the lab method every time you introduce or change a guardrail: write the YAML, apply it to a sandbox folder, run one allowed and one denied action, read the logs, then promote the same file to a higher folder through a pull request. Do not test guardrails directly on production folders.

What it is confused with

PairDifference
--no-address vs the constraint--no-address is a choice made by the person who creates the VM. The constraint is a rule that cannot be bypassed by that person.
Constraint vs firewall ruleA firewall rule limits traffic to an address. The constraint stops the address from being created.
Dry-run vs enforceA dry-run policy records what would be blocked without blocking. Enforce blocks. Dry-run is for production rollout; the lab uses a folder with no workloads, so it enforces directly.
set-policy vs deleteset-policy replaces the policy on that resource with your file. delete removes your policy; inheritance applies again.

Common misunderstandings

"Existing VMs lose their external IP." They do not. Constraints are evaluated when a resource is created or changed. Clean up existing exposure with a scan (Module 6) and a planned change.
"The policy applied at once, so it must work." An applied policy that nobody tested may not cover the case you care about. The negative test is the proof.
"Deleting the policy deletes the constraint." Constraints are defined by Google. You are only removing your setting of it on that resource.
Organization no change in this lab Folder: lz-lab-h3 policy: compute.vmExternalIpAccess rules: denyAll: true (set by gcloud org-policies set-policy) Project: prj-h3-lab inherits denyAll (effective policy) gcloud CLI instances create Result: denied no VM, no compute cost The folder holds the policy; the project inherits it. The VM request is evaluated against the effective policy. Rollback is one command: delete the policy on the folder and the project inherits from the organization again.

Figure 1. Lab layout. The guardrail sits on the folder, the test runs in a project below it, and the organization is untouched.

Look at where the policy is attached: on the folder, not on the project. That is why a new project created in the folder later is covered without any extra step.

1 Readeffective 2 WriteYAML file 3 Applyset-policy 4 Verify--effective 5 TestVM denied 6 Evidenceaudit log 7 Undodelete Pass criteria Step 4: effective policy shows denyAll · Step 5: error names constraints/compute.vmExternalIpAccess Step 6: the failed insert appears in the audit log · Step 7: describe returns the old state If any pass criterion fails, stop and fix before you continue.

Figure 2. The seven lab steps with their pass criteria. Each step has a check; the lab is not complete until the rollback is verified.

The animation shows the policy being set, the VM request arriving at Compute Engine, the effective policy check, the denial and the audit record. Notice that the denial comes from Compute Engine after it asks Organization Policy, not from the CLI.

These are the commands used in the lab, with what each one does and what it costs. Policy commands are metadata operations and are free. The VM creation command is expected to be refused, so it creates nothing.

IDs in the expected output are illustrative. Check gcloud org-policies --help for the flags in your SDK version.

gcloud org-policies describe --effective (read, free)

Purpose. Read the policy in force for a resource, after inheritance. Always run it before and after a change.

gcloud org-policies describe compute.vmExternalIpAccess \
  --project=PROJECT_ID --effective
name: projects/PROJECT_ID/policies/compute.vmExternalIpAccess
spec:
  rules:
  - allowAll: true

Flags. The first argument is the constraint name without the constraints/ prefix. Use exactly one of --project, --folder or --organization. --effective returns the merged result.

Common errors. NOT_FOUND without --effective means no policy is set directly on that resource; that is normal. PERMISSION_DENIED needs orgpolicy.policy.get (for example roles/orgpolicy.policyViewer).

gcloud org-policies set-policy (write, free)

Purpose. Apply a policy from a YAML file to a resource. It replaces the policy that is set on that resource.

name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
spec:
  rules:
  - denyAll: true
gcloud org-policies set-policy policy.yaml
Updated policy [folders/FOLDER_ID/policies/compute.vmExternalIpAccess].
name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
spec:
  etag: CJbMwL4GEODBvv0B
  rules:
  - denyAll: true
  updateTime: '2026-11-25T10:02:41.209Z'

Flags. The file path is the only required argument. The name inside the file decides which resource and constraint are changed, so read it twice before you apply. For list constraints, a rule is values (with allowedValues or deniedValues), allowAll or denyAll.

Common errors. PERMISSION_DENIED ... orgpolicy.policy.set needs roles/orgpolicy.policyAdmin. INVALID_ARGUMENT usually means a boolean rule used on a list constraint or the other way round.

gcloud org-policies list (read, free)

Purpose. List the policies set directly on a folder, project or organization.

gcloud org-policies list --folder=FOLDER_ID
CONSTRAINT                       LIST_POLICY  BOOLEAN_POLICY  ETAG
compute.vmExternalIpAccess       SET          -               CJbMwL4GEODBvv0B

The columns can differ by SDK version. The point is that compute.vmExternalIpAccess is set on this folder.

gcloud compute instances create (write, expected to fail, free when denied)

Purpose. The negative test. The command asks for a VM with the default network interface, which includes an external IP. With the constraint in place it is refused, so nothing is created.

gcloud compute instances create vm-lab-denied \
  --project=PROJECT_ID --zone=ZONE --machine-type=e2-micro
ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - Constraint constraints/compute.vmExternalIpAccess violated for project PROJECT_ID. Add instance projects/PROJECT_ID/zones/ZONE/instances/vm-lab-denied to the constraint to use external IP with it.

Flags. No --no-address, on purpose. The project needs a VPC network with a subnet in the region (the default network or another one). If the network does not exist you will see a different error, and the test proves nothing; check gcloud compute networks list first.

Cost. None when the request is denied. If the command succeeds because the policy was not applied, it creates a billable VM; delete it at once with gcloud compute instances delete vm-lab-denied --zone=ZONE.

gcloud logging read (read, free within the free allotment)

Purpose. Find the denied call in the audit log.

gcloud logging read \
  'protoPayload.methodName="v1.compute.instances.insert" AND severity=ERROR AND protoPayload.status.message:"vmExternalIpAccess"' \
  --project=PROJECT_ID --limit=1 \
  --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.status.message)"
2026-11-25T10:04:09.331Z  you@example.com  Constraint constraints/compute.vmExternalIpAccess violated for project PROJECT_ID. ...

Note. Method and field names can vary by API version. If the filter returns nothing, remove the message clause and read recent severity=ERROR entries for compute.googleapis.com.

gcloud org-policies delete (write, free)

Purpose. Remove the policy that you set on the folder, which is the rollback.

gcloud org-policies delete compute.vmExternalIpAccess --folder=FOLDER_ID
Deleted policy [folders/FOLDER_ID/policies/compute.vmExternalIpAccess].
Production use. Keep policy YAML files in a repository with the folder IDs as variables. Roll out in three stages: dry-run (record only), enforced on a pilot folder, enforced on production. Use gcloud org-policies set-policy --help to check how your SDK version expresses a dry-run spec.

Lab: deny external IPs on a lab folder, prove it, and restore (10 minutes, free)

Goal. Enforce constraints/compute.vmExternalIpAccess with denyAll on a lab folder, show that a VM with an external IP is refused, find the evidence in the audit log, and restore the original state.

Prerequisites.

  • A sandbox organization with a lab folder that contains one empty or throw-away project (create them as in Hour 1 if you have not). Do not use a folder with real workloads.
  • Your identity has roles/orgpolicy.policyAdmin on the folder (or organization), and roles/compute.instanceAdmin.v1 on the project.
  • The project is linked to a billing account with a budget (Hour 1; budgets alert, they do not cap spend), and the Compute Engine API is enabled: gcloud services enable compute.googleapis.com --project=PROJECT_ID.
  • The project has a VPC network with a subnet in the region of ZONE (check below). Without an organization, you cannot do this lab; use the explanation and expected output as reading.

IDs in the expected output are illustrative. Creation is denied, so there is no compute cost. If the denial does not happen, the VM that is created is billable until you delete it.

  1. Set variables and check the network.
    export FOLDER_ID=FOLDER_ID
    export PROJECT_ID=PROJECT_ID
    export ZONE=ZONE
    gcloud compute networks list --project=$PROJECT_ID

    Verify: at least one network is listed (for example default). If none is listed, create a custom-mode network and subnet (Hour 4) or choose another project. A missing network would make the test fail for the wrong reason.

  2. Read the starting state.
    gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective

    Verify: note the result. A fresh organization shows allowAll: true or no restriction. If it already shows denyAll or a list, someone set a policy above you: stop, record it, and choose another folder, otherwise the cleanup would hide the difference.

  3. Write the policy file. Save as policy.yaml in your working directory:
    name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
    spec:
      rules:
      - denyAll: true

    Verify: the name line contains your lab folder ID and not an organization ID. Print it: cat policy.yaml.

  4. Apply it.
    gcloud org-policies set-policy policy.yaml

    Verify: the output prints Updated policy [folders/FOLDER_ID/policies/compute.vmExternalIpAccess] and the denyAll: true rule.

  5. Check the effective policy of the project.
    gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective
    name: projects/PROJECT_ID/policies/compute.vmExternalIpAccess
    spec:
      rules:
      - denyAll: true

    Verify: the project, which has no policy of its own, shows denyAll: true. Propagation usually takes seconds, but can take a few minutes. Repeat after a minute if it still shows the old value.

  6. Run the negative test.
    gcloud compute instances create vm-lab-denied --project=$PROJECT_ID --zone=$ZONE --machine-type=e2-micro
    ERROR: (gcloud.compute.instances.create) Could not fetch resource:
     - Constraint constraints/compute.vmExternalIpAccess violated for project PROJECT_ID. Add instance projects/PROJECT_ID/zones/ZONE/instances/vm-lab-denied to the constraint to use external IP with it.

    Verify: the error names the constraint, and gcloud compute instances list --project=$PROJECT_ID shows no vm-lab-denied. If the VM exists, the policy is not in force yet: delete the VM, wait, and repeat step 5.

  7. Show that the guardrail is specific. A VM without an external IP is not covered by this constraint, so it would be allowed. Do not create it in this lab (it would cost money); state in your notes that --no-address is the allowed path and that it requires Private Google Access or Cloud NAT for egress (Hour 4).
  8. Collect the evidence.
    gcloud logging read 'protoPayload.methodName="v1.compute.instances.insert" AND severity=ERROR' --project=$PROJECT_ID --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.status.message)"

    Verify: one entry with your identity and a status message that names constraints/compute.vmExternalIpAccess. Audit entries can appear after a short delay; wait one minute and retry. Copy the line into your notes.

  9. Roll back.
    gcloud org-policies delete compute.vmExternalIpAccess --folder=$FOLDER_ID
    gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective

    Verify: the effective policy equals the starting state you recorded in step 2. gcloud org-policies list --folder=$FOLDER_ID no longer lists compute.vmExternalIpAccess.

  10. Clean up the local file. rm policy.yaml. If you created the folder or the project for this lab only, delete the project (gcloud projects delete PROJECT_ID) and then the empty folder (gcloud resource-manager folders delete FOLDER_ID).

Expected result. Before: no restriction. During: the effective policy is denyAll, the VM request fails with a constraint violation, and the audit log has the failed call. After: the original state is back.

Cost. Free. Policy changes are metadata and the VM is never created. Budgets send alerts and do not cap spend.

Cleanup. The rollback in step 9 is the cleanup; step 10 removes local files and the optional lab project and folder.

Stretch (optional, 10 more minutes)

  • Change the file to allow one specific instance by name instead of denyAll, using a values rule with allowedValues and the full instance resource name. Apply it, run the negative test again, and read the new effective policy. This shows what "allow list" means for a list constraint.
  • Repeat the method with the boolean constraint constraints/compute.skipDefaultNetworkCreation on the folder, and create a new project in it to prove that no default network is created (Module 2).

Real cases

  • The unreviewed folder-wide change. An engineer applied a restrictive list constraint on a production folder, and a release pipeline that created a VM with an external IP for a legitimate public service failed. The team now requires every constraint change to be a pull request, tests it on a pilot folder first, and keeps an explicit allow list for the few approved cases.
  • The silent policy that did nothing. A policy was applied with the wrong folder ID. Reports said "enforced", but a negative test, run quarterly as a scheduled job, started to fail and exposed the mistake. The negative test is now part of the repository as an automated check against a sandbox project.
  • Exception handling. A team needed one VM with an external IP for a licensing server. Instead of removing the constraint, the platform team added that single instance to the allowed list by full resource name, with a ticket number and an expiry date in the pull request.

Practices

  • Policy as code: YAML or Terraform (google_org_policy_policy) in a repository with review, plan and a separate pipeline identity that holds roles/orgpolicy.policyAdmin.
  • Promote in stages: dry-run where available, pilot folder, then production. Give teams notice and a date.
  • Record the effective policy before and after every change and attach it to the change ticket.
  • Keep a negative test per critical constraint, run on a schedule against a sandbox project, and alert when it fails.
  • Use tags or folder structure for exceptions rather than weakening the policy at the organization.
  • Alert on SetOrgPolicy and policy changes in the audit log, so that every guardrail change is visible.
Security note. roles/orgpolicy.policyAdmin can switch off every guardrail. Grant it to a small platform group and to the pipeline identity only, require 2-step verification for the humans, and review its audit log. Never use it for day-to-day project work.

Symptoms and first checks

SymptomLikely causeFirst check
PERMISSION_DENIED on set-policyMissing roles/orgpolicy.policyAdmin on the folder or organizationgcloud resource-manager folders get-iam-policy FOLDER_ID, filtered to your identity
Effective policy still shows the old valuePropagation delay, or the policy was set on another resourceWait a minute; gcloud org-policies list --folder=FOLDER_ID; check the name line of the file
VM was created although the policy is setPolicy not yet in force, wrong folder, or the project is under another parentgcloud projects describe PROJECT_ID --format="value(parent)"; delete the VM at once
Different error: network not foundNo default network in the project (skipDefaultNetworkCreation or deleted)gcloud compute networks list --project=PROJECT_ID
INVALID_ARGUMENT on set-policyWrong rule type for the constraint (boolean vs list)Read the constraint page in the Organization Policy constraints list to see whether it is boolean or list
Audit log query returns nothingFilter too narrow, ingestion delay, or wrong projectRemove the message clause; wait a minute; confirm the project
After rollback the effective policy is still denyAllA parent folder or the organization also sets itgcloud org-policies describe compute.vmExternalIpAccess --organization=ORG_ID

Triage order

  1. Confirm identity and scope: gcloud config list account, and the parent of the project.
  2. Read the effective policy; if it is wrong, read the policy at each ancestor.
  3. Read the exact error text of the denied call and compare it with the constraint name.
  4. Check the audit log of the denied call for the principal and the reason.
  5. Only then change the policy, and re-run the effective check after the change.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Organization Policy Service overview · Organization policy constraints · Creating and managing organization policies.

or score ≥ 70% on the quiz

Module 8 · Production and troubleshooting

52–60 · When a policy blocks a deploy, a perimeter breaks a pipeline, a key is disabled, or findings become noise
Policy denialsVPC-SCCMEK outageSCC noise8 min
Learning objectives
  • Diagnose a blocked deployment by reading the exact error, the effective Organization Policy and the audit log, in that order, before changing any policy.
  • Recognise a VPC Service Controls denial by its error text and find its unique identifier and violation details in the audit log.
  • Recover from a disabled CMEK key and turn a noisy Security Command Center queue into a short, owned list.

The short answer

Guardrails work only if people can diagnose them quickly. If the only fix anyone knows is "ask the platform team to switch it off", every control decays. This module gives you a diagnostic method for four incident types that every landing zone meets in its first year, with a rule that applies to all of them: read the error, read the effective state, read the audit log, then change the smallest thing.

What: the four incident types

IncidentTypical error textWhere the truth is
Organization Policy blocks a deployConstraint constraints/... violated for project ... or FAILED_PRECONDITIONgcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective, the audit log of the denied call
VPC Service Controls breaks a pipelineRequest is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: ...Audit log entries with VpcServiceControlAuditMetadata, in the project or at the organization
Disabled or destroyed CMEK keyKey errors from the data service, for example a failed precondition about the key versionCloud KMS key version state and key audit logs
Noisy SCC findingsNo error; a queue nobody ownsSCC findings grouped by category, project and severity

Why: each failure has a design cause

  • Policy blocks a deploy because a team did not know the constraint existed, or because the constraint is correct and the design must change (for example a region that is not allowed). The cause is often missing documentation or a missing pre-deployment check.
  • VPC Service Controls breaks a pipeline because perimeters cut every path that crosses the boundary, including paths that nobody remembered: Cloud Build running outside the perimeter, a BigQuery export to another project, a Terraform runner on a laptop, an on-premises job through a public API. The cause is rollout without dry-run.
  • Key disabled because key lifecycle was handled like any other cleanup. The cause is missing ownership and missing alerts on key version state.
  • Noisy findings because detection was turned on before ownership existed. The cause is a process gap, not a tooling gap.

How the diagnosis works

  1. Classify the error: Organization Policy, VPC Service Controls, IAM, quota, API not enabled, or key. The text of the message is usually enough.
  2. Identify the principal, the resource and the method from the log entry, not from the person's description.
  3. Read the effective state: effective Organization Policy, perimeter configuration (including dry-run), key version state, IAM with gcloud policy-troubleshoot iam where IAM is suspected.
  4. Fix the smallest thing: a precise ingress rule, an allowed value, an enabled version, an owner label, or a guardrail that prevents the cause.
  5. Record the change and the evidence, and add a test so the next change does not repeat the incident.

When to escalate

Escalate to the platform or security owner when the fix would widen a guardrail (a new allowed value, a perimeter exception), when a key version is scheduled for destruction, or when the finding is a threat finding. Do not escalate by default for a plain constraint denial that has a compliant alternative, such as an allowed region.

What it is confused with

Looks likeActuallyHow to tell
An IAM problemVPC Service ControlsIAM errors name a missing permission. VPC-SC errors name the organization's policy and have a unique identifier.
An IAM problemOrganization PolicyThe message names a constraints/... value.
A firewall problemVPC Service ControlsThe failure is from a Google API call, not a TCP timeout to a VM.
A KMS permission problemA disabled key versionIAM on the key is correct but operations still fail; the version state is not ENABLED.
An SCC outageMissing activation or notification configFindings exist in the console but do not reach the ticket system.

Common misunderstandings

"Admin roles bypass perimeters and constraints." They do not. Even a project owner is refused by Organization Policy and by a VPC Service Controls perimeter. That is the point of the controls.
"We can widen the perimeter now and tighten it later." Widening is easy and tightening is rarely done. Add the narrowest ingress or egress rule that matches the log entry.
"Disabling a key is the same as deleting data." Disabling is reversible; scheduled destruction is reversible until it completes; destruction is not. Know which state the key is in before you act.
A request failed read the exact error text constraints/...violatedOrganization Policy prohibited by org policyvpcServiceControlsUniqueIdentifier Permission deniednames a permissionIAM key version errorKMS key or agentCMEK org-policies describe--effective logging readVpcServiceControlAuditMetadata policy-troubleshoot iamget-iam-policy kms keys versions listkms get-iam-policy After the check: fix the smallest thing (allowed value, precise ingress rule, IAM binding, enabled version). Never switch the guardrail off to unblock one request. Record the change and add a test. Out of scope here: quota, API not enabled, network reachability. Each has its own error text.

Figure 1. Classify first. The four error shapes lead to four different first checks, and only one of them is an IAM problem.

Look at the second column: the VPC Service Controls error contains the words "organization's policy" but no constraints/ name. That difference sends you to the audit log, not to org-policies.

1 Dry-runperimeter logs whatit would deny 2 Review logsgroup by service,identity and method 3 Add rulesprecise ingress andegress, access levels 4 Enforceafter a clean weekwith a rollback plan Repeat after every new service or pipeline that crosses the boundary What the log gives you Which service and method were blocked, which identity called, from which network or project, and whether an ingress or egress rule or an access level was missing. That turns "the pipeline broke" into one precise rule you can review.

Figure 2. The rollout loop for a perimeter. The same loop applies to new Organization Policy constraints that use dry-run where available.

The animation follows one broken pipeline: a Cloud Build step calls Cloud Storage, the perimeter denies it, the error returns with a unique identifier, and the audit log holds the detail that an operator needs to write a narrow rule. Notice that the denial is decided at the Google API boundary, not on any network path.

These are the diagnosis commands for the four incident types. All of them are read-only and free unless stated; the fix commands that write are marked. Run them with a principal that has the matching viewer roles, and use placeholders as shown.

IDs in the expected output are illustrative. Check gcloud access-context-manager --help, gcloud kms --help and gcloud scc --help for the flags in your SDK version.

1. Policy blocks a deploy: gcloud org-policies describe --effective (read, free)

Purpose. See what is allowed for the project after inheritance, for the constraint that the error names.

gcloud org-policies describe gcp.resourceLocations \
  --project=PROJECT_ID --effective
name: projects/PROJECT_ID/policies/gcp.resourceLocations
spec:
  rules:
  - values:
      allowedValues:
      - in:eu-locations

Flags. The constraint name is given without constraints/. Value groups such as in:eu-locations are documented value groups; the list in the effective policy is the answer to "where may I deploy?".

Common errors. NOT_FOUND without --effective means no policy is set on that exact resource. Use --effective, or look at the folder and organization.

2. Find where a policy comes from: gcloud org-policies list (read, free)

Purpose. List policies on each ancestor, so you know where to change the rule (or request the change).

gcloud projects describe PROJECT_ID --format="value(parent.id,parent.type)"
gcloud org-policies list --folder=FOLDER_ID
gcloud org-policies list --organization=ORG_ID
987654321098  folder
CONSTRAINT                  LIST_POLICY  BOOLEAN_POLICY  ETAG
gcp.resourceLocations       SET          -               CKmJvL4GEIDw6vUB

3. Find the denied call: gcloud logging read (read, free within the free allotment)

Purpose. Read the audit entry for a denied request. The entry names the principal, the method and the status message.

gcloud logging read \
  'severity=ERROR AND protoPayload.status.message:"constraints/"' \
  --project=PROJECT_ID --freshness=1d --limit=5 \
  --format="table(timestamp,protoPayload.serviceName,protoPayload.methodName,protoPayload.authenticationInfo.principalEmail)"
TIMESTAMP                      SERVICE                  METHOD                    PRINCIPAL_EMAIL
2026-11-25T10:04:09.331Z       compute.googleapis.com   v1.compute.instances.insert  ci-deployer@PROJECT_ID.iam.gserviceaccount.com

Flags. --freshness=1d limits the search window; --limit keeps the output short. Method and field names vary by service; adapt the filter.

4. VPC Service Controls violation: gcloud logging read on VpcServiceControlAuditMetadata (read, free within the allotment)

Purpose. Find the violation entries for a perimeter denial. Use the unique identifier from the error message to select one.

gcloud logging read \
  'protoPayload.metadata.@type="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata" AND protoPayload.metadata.vpcServiceControlsUniqueId="UNIQUE_ID"' \
  --project=PROJECT_ID --freshness=1d --limit=1 --format=json
[
  {
    "protoPayload": {
      "serviceName": "storage.googleapis.com",
      "methodName": "google.storage.objects.create",
      "authenticationInfo": { "principalEmail": "ci-deployer@PROJECT_ID.iam.gserviceaccount.com" },
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata",
        "violationReason": "NO_MATCHING_ACCESS_LEVEL",
        "resourceNames": ["projects/222222222222/buckets/build-artifacts"]
      }
    }
  }
]

Why this matters. The reason (for example no matching access level, or a missing ingress or egress rule) tells you which of the three fixes applies. The field names above follow the documented audit metadata; check the log entry in your environment for the exact fields. The violation is logged where the perimeter protects the resource, so you may need to search the project that is protected or the organization.

Common errors. An empty result usually means you searched the wrong project, the identifier was copied with a typo, or the window is too short.

5. Inspect perimeters: gcloud access-context-manager perimeters (read, free)

Purpose. Show which projects and services are inside a perimeter, and which rules exist. The policy ID is the access policy of the organization.

gcloud access-context-manager policies list --organization=ORG_ID
gcloud access-context-manager perimeters list --policy=POLICY_ID
gcloud access-context-manager perimeters describe PERIMETER_NAME --policy=POLICY_ID
NAME          TITLE
prod_data     Production data perimeter

The describe output includes the status (enforced) and the dry-run configuration (spec) side by side, so you can compare what is enforced with what is being tested. Check gcloud access-context-manager perimeters --help for the subcommands and flags in your SDK version.

6. Disabled CMEK key: gcloud kms keys versions list and enable (read free; write free)

Purpose. Check the state of key versions, and re-enable a version that was disabled by mistake.

gcloud kms keys versions list \
  --key=KEY_NAME --keyring=KEYRING_NAME --location=LOCATION --project=PROJECT_ID
NAME                                                    STATE
.../cryptoKeys/app-key/cryptoKeyVersions/2              ENABLED
.../cryptoKeys/app-key/cryptoKeyVersions/1              DISABLED
gcloud kms keys versions enable 1 \
  --key=KEY_NAME --keyring=KEYRING_NAME --location=LOCATION --project=PROJECT_ID

Common errors. If the state is DESTROY_SCHEDULED, run gcloud kms keys versions restore 1 ... before the scheduled time, then enable. If it is DESTROYED, the material is gone; recovery depends on backups of the data encrypted in another way.

7. Noisy findings: gcloud scc findings list (read, free)

Purpose. Count active findings by category before you decide what to do. Pipe through standard tools to group.

gcloud scc findings list ORG_ID \
  --filter='state="ACTIVE"' \
  --format="value(finding.category)" | sort | uniq -c | sort -rn | head
  1240 PUBLIC_IP_ADDRESS
   890 DEFAULT_NETWORK
   410 OPEN_FIREWALL
    75 SERVICE_ACCOUNT_KEY_NOT_ROTATED

Why this matters. A few categories usually account for most of the noise. Each of the top ones maps to a guardrail from this hour: compute.vmExternalIpAccess, compute.skipDefaultNetworkCreation, hierarchical firewall policies, and iam.disableServiceAccountKeyCreation. Check gcloud scc findings list --help for the field names in your SDK version.

Production use. Keep these seven commands in a runbook with the placeholders already filled for your organization. The person on call should be able to classify an error and run the first check in under five minutes.

Lab: diagnose three simulated incidents without changing anything (about 15 minutes, free)

Goal. Practise the classify, identify, read-state, fix-smallest method on three incidents using the error texts and outputs below. This is a reading and command lab; the commands are read-only, so you can run them against your sandbox to see their real shape.

Prerequisites. Your sandbox project and, if you have one, folder and organization. Viewer roles only. No change is made, so there is no cost and no cleanup.

IDs in the outputs are illustrative. Where your sandbox does not have a perimeter, SCC or a CMEK key, answer from the text and run the commands that apply.

Incident A: a deploy is denied

ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - Constraint constraints/gcp.resourceLocations violated for project PROJECT_ID. The resource projects/PROJECT_ID/zones/us-central1-a/instances/app-1 violates policy.
  1. Classify the error. (It names a constraint: Organization Policy.)
  2. Run gcloud org-policies describe gcp.resourceLocations --project=PROJECT_ID --effective. Record the allowed values.
  3. Decide: deploy to an allowed zone, or request an exception. Write the one-line reason for your choice.
  4. Verify: your decision names a concrete allowed location from step 2.

Incident B: a pipeline fails against Cloud Storage

ERROR: (gcloud.storage.cp) HTTPError 403: Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: 5b1b6c8a9f3e2d41
  1. Classify the error. (VPC Service Controls: the text and the identifier.)
  2. Use the log command from the commands tab with UNIQUE_ID=5b1b6c8a9f3e2d41. In your sandbox, search for any VpcServiceControlAuditMetadata entry; if you have none, read the sample entry in the commands tab.
  3. From the entry, write the three facts you need for a rule: the service and method, the identity, and the violation reason.
  4. Choose the fix: an access level for the caller, an ingress rule for this identity and service, or an egress rule. Write why the perimeter should not be widened.
  5. Verify: your rule is narrower than "allow all services for all identities".

Incident C: reads from a database fail after a key cleanup

  1. Classify: a CMEK key problem (the data service cannot use the key).
  2. Run gcloud kms keys versions list ... for the key. In a sandbox without a key, use the sample output in the commands tab.
  3. If the state is DISABLED, run enable; if DESTROY_SCHEDULED, run restore and then enable. Write which state allows recovery and which does not.
  4. Verify: you can state the recovery rule for the three states: disabled, scheduled for destruction, destroyed.

Bonus: reduce a noisy queue

  1. Run the grouping command from the commands tab (or use the sample output).
  2. For the top two categories, name the guardrail that prevents them and the folder where you would roll it out first.
  3. Verify: each category is paired with one prevention and one owner.

Expected result. Three short written diagnoses, each with a classification, the first command, the smallest fix and a verification, plus two prevention choices for the noisy queue.

Cost. Free. All commands read metadata or logs.

Cleanup. None.

Real cases

  • The weekend build outage. A perimeter was enforced on Friday after a short test in the console. On Saturday, every build that used a Google-managed builder failed against a protected bucket. The team added a narrow ingress rule for the build service identity and the artifact bucket, rolled the perimeter back to dry-run for the other services, and wrote a rule that every perimeter change goes through two weeks of dry-run logs first.
  • Cleanup that disabled data. A hygiene job disabled unused key versions based on "no recent use". A quarterly reporting database used a key only once a quarter. The database failed on the first day of the quarter. The key was re-enabled within the destruction window, and the job was changed to alert and to require a ticket for any key action.
  • Findings fatigue. A security queue grew until it was ignored. The team grouped findings by category, found that default networks, external IPs and old service account keys were most of the volume, enforced three constraints on new projects, scheduled clean-up of old ones with owners, and reduced the active count by an order of magnitude over a quarter.

Practices

  • Write a runbook per incident type with the error text, the first command and the owner. Put it next to the Terraform code that defines the control.
  • Make the error message useful: keep a documented exceptions process and a link to it in the team's deployment documentation.
  • Use dry-run for perimeters and for any policy that supports it. Review the logs weekly during the pilot.
  • Create log-based alerts on policy changes, perimeter changes and key version state changes (Hour 6 covers alerting).
  • Use break-glass procedures with logging for emergencies: a small group, time-limited, reviewed afterwards. Do not leave an emergency exception in place.
  • Run a quarterly game day: break a guardrail in a sandbox on purpose and measure how long classification takes.
Security note. Under pressure, people widen guardrails: they set allowAll, add the whole organization to a perimeter exception, or grant the pipeline owner rights. Each of these removes protection for everyone. Approve exceptions by a reviewed change, with an expiry date, and alert on the change.
Cost note. VPC Service Controls and Organization Policy have no direct charge, but the audit logs you rely on do (ingestion and retention, Hour 6). Include data access logs for the services you diagnose in your logging budget.

Symptoms and first checks

SymptomLikely causeFirst check
Constraint constraints/... violated on deployAn Organization Policy constraint applies to the projectgcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective
Same error only in one projectA tag-conditional or project-level policy overrides the folder policygcloud org-policies list --project=PROJECT_ID; check the tags on the project
Request is prohibited by organization's policy from a pipelineVPC Service Controls perimeter blocks the caller or the destinationSearch the audit log for the vpcServiceControlsUniqueIdentifier
Works from Cloud Shell, fails from CICloud Shell is covered by an access level or ingress rule; the CI runner is outsideCompare the principal and the source network in the violation entry
Terraform plan works, apply fails on a Google APIThe runner sits outside a perimeter, or it lacks an access levelRun the same API call from the runner with gcloud and read the error
BigQuery export or copy to another project failsCrossing a perimeter boundary needs an egress or ingress ruleViolation entry: look for RESOURCES_NOT_IN_SAME_SERVICE_PERIMETER or similar reason
Data service cannot read after a key actionKey version disabled or scheduled for destructiongcloud kms keys versions list --key=KEY --keyring=RING --location=LOCATION
Key is enabled but the service still failsService agent lost cryptoKeyEncrypterDecrypter, or key location mismatchgcloud kms keys get-iam-policy KEY --keyring=RING --location=LOCATION
SCC shows thousands of findingsOne root cause repeated across many projectsGroup by category; fix with a guardrail on new projects, schedule clean-up of old ones
Muted findings come backMute rule filter too narrow, or the resource changedCheck the mute rule filter and its review date

Triage order

  1. Capture the exact error text and the time. Do not rely on a summary.
  2. Classify: constraint, perimeter, IAM, key, API not enabled, quota.
  3. Read the effective state for that class (policy, perimeter and dry-run, key version, IAM policy).
  4. Read the audit log entry for the principal, method and reason.
  5. Apply the smallest fix, record it, and re-run the failed call.
  6. Add the prevention: a test, an alert, a runbook line, or a guardrail.

Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.

Official reading: Troubleshooting VPC Service Controls · Organization Policy Service overview · Cloud KMS key version states.

or score ≥ 70% on the quiz

Command cheat sheet

Guardrails: Organization Policy, VPC Service Controls, keys and detection
Hour 3

Hour 3 command cheat sheet: guardrails, keys and detection

Placeholders are in uppercase: ORG_ID, FOLDER_ID, PROJECT_ID, REGION, ZONE. Read commands are free. Write commands say what they cost. Check gcloud COMMAND --help for the flags in your SDK version before you copy a command into automation.

Organization Policy

CommandPurposeKey flagsGotcha
gcloud org-policies list --folder=FOLDER_IDList policies set directly on a resource--project, --folder, --organization (use one)Does not show inherited policies. Use describe --effective for the real result.
gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effectiveRead the merged policy in force--effective; constraint name without constraints/Without --effective you get NOT_FOUND when the policy is set only on an ancestor.
gcloud org-policies set-policy policy.yamlApply a policy from a file (replaces the policy on that resource)The file path; the name field in the file picks the resource and constraintWrong folder ID in name changes the wrong scope. Needs roles/orgpolicy.policyAdmin. Free.
gcloud org-policies delete CONSTRAINT --folder=FOLDER_IDRemove your policy from a resource (rollback)--project, --folder, --organizationInheritance applies again; a parent may still enforce the constraint. Free.
gcloud resource-manager org-policies list --project=PROJECT_IDOlder command group for the same dataSame scopesPrefer gcloud org-policies. Do not mix the two in scripts.
name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
spec:
  rules:
  - denyAll: true

Constraints to remember

ConstraintTypeWhat it blocksGotcha
iam.disableServiceAccountKeyCreationBooleanCreation of service account key filesExisting keys keep working; find them first with Asset Inventory.
iam.allowedPolicyMemberDomainsListIAM members from domains that are not allowedValues are customer IDs, not domain names. Partner access needs an exception.
gcp.resourceLocationsListResources in locations that are not allowedUse value groups such as in:eu-locations; some services are global.
compute.vmExternalIpAccessListVMs with an external IPEvaluated at create and update; existing VMs keep their IP.
compute.requireOsLoginBooleanMetadata-based SSH keysUsers need roles/compute.osLogin or osAdminLogin.
compute.skipDefaultNetworkCreationBooleanAuto-creation of the default networkApplies to new projects only; projects without a network need one before VMs.
storage.uniformBucketLevelAccessBooleanBucket ACLs (forces IAM-only access)Old buckets are unaffected; legacy ACL tools stop working on new ones.
sql.restrictPublicIpBooleanCloud SQL instances with a public IPPrivate services access is required for private instances.
gcp.restrictNonCmekServicesListCreating resources without CMEK in listed servicesApplies at creation; make sure keys and grants exist first.

VPC Service Controls and Access Context Manager

CommandPurposeKey flagsGotcha
gcloud access-context-manager policies list --organization=ORG_IDFind the access policy ID of the organization--organizationAn organization has one access policy (scoped policies exist for folders and projects).
gcloud access-context-manager perimeters list --policy=POLICY_IDList service perimeters--policyOutput shows enforced configuration; dry-run configuration appears in describe.
gcloud access-context-manager perimeters describe NAME --policy=POLICY_IDShow projects, services and rules of a perimeter--policyCompare enforced status with dry-run spec before promoting.
gcloud access-context-manager levels list --policy=POLICY_IDList access levels--policyAccess levels are conditions (IP ranges, device, identity), not permissions.
gcloud logging read 'protoPayload.metadata.@type="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata"' --freshness=1dFind perimeter violations--freshness, --limit, --format=jsonSearch the protected project or the organization; the entry holds the violation reason.

Creating or changing perimeters is a write operation that can break pipelines at once. Roll out in dry-run first. Check gcloud access-context-manager perimeters --help for the create and update flags in your SDK version.

Cloud KMS

CommandPurposeKey flagsGotcha
gcloud kms keyrings create RING --location=REGIONCreate a key ring--locationKey rings cannot be deleted or renamed. Free of charge itself.
gcloud kms keys create KEY --keyring=RING --location=REGION --purpose=encryption --rotation-period=90d --next-rotation-time=TIMESTAMPCreate a symmetric key with automatic rotation--purpose, --rotation-period, --next-rotation-time, --protection-levelKeys cannot be deleted. Low cost per active version; Cloud HSM costs more.
gcloud kms keys describe KEY --keyring=RING --location=REGIONShow purpose, primary version and rotationSame resource flagsRotation does not re-encrypt old data.
gcloud kms keys add-iam-policy-binding KEY --keyring=RING --location=REGION --member=... --role=roles/cloudkms.cryptoKeyEncrypterDecrypterAllow a service agent to use the key--member, --roleThe member is the service agent of the data project (by project number). Free.
gcloud kms keys versions list --key=KEY --keyring=RING --location=REGIONShow states of key versionsSame resource flagsFirst check when data becomes unreadable.
gcloud kms keys versions disable VERSION --key=KEY --keyring=RING --location=REGIONKill switch: block use of a version--key, --keyring, --locationData protected by it is unreadable until you enable it again. Free.
gcloud kms keys versions destroy VERSION ...Schedule destruction of a versionSameIrreversible after the scheduled time. Use restore before then.
gcloud storage buckets update gs://BUCKET --default-encryption-key=KEY_RESOURCESet the CMEK default for a bucket--default-encryption-keyExisting objects keep their current encryption until rewritten.

Secret Manager

CommandPurposeKey flagsGotcha
gcloud secrets create NAME --replication-policy=automaticCreate a secret (no value yet)--replication-policy, --labelsUse user-managed replication when data residency requires specific regions.
printf 'VALUE' | gcloud secrets versions add NAME --data-file=-Add a version from standard input--data-file (- for stdin)Do not type a real secret into a shared terminal history; use a lab value in training.
gcloud secrets versions access VERSION --secret=NAMERead a version valuelatest or a numberPin a version in production. Each access is audited and billed.
gcloud secrets versions list NAMEShow versions and states--filterDisabled versions cannot be read; destroyed versions are gone.
gcloud secrets add-iam-policy-binding NAME --member=... --role=roles/secretmanager.secretAccessorAllow one identity to read one secret--member, --roleGrant on the secret, not on the project.
gcloud secrets delete NAME --quietDelete a secret and all versions--quietIrreversible. Applications that read it fail immediately.

Cloud Asset Inventory and Security Command Center

CommandPurposeKey flagsGotcha
gcloud asset search-all-resources --scope=organizations/ORG_ID --asset-types=TYPEFind resources across a scope--scope, --asset-types, --query, --formatNeeds roles/cloudasset.viewer at the scope and the API enabled in the quota project.
gcloud asset search-all-iam-policies --scope=organizations/ORG_ID --query="policy:allUsers"Find IAM bindings across a scope--scope, --queryIndex is near-real-time, not instant.
gcloud asset analyze-iam-policy --organization=ORG_ID --full-resource-name=NAME --permissions=PERMWho can access a resource--expand-groups, --rolesFull resource name format is required. Check the help for current flags.
gcloud asset export --organization=ORG_ID --content-type=resource --output-path=gs://BUCKET/file.jsonSnapshot of resources to Cloud Storage--content-type, --asset-types, --output-pathWrites objects (storage cost). Use a lifecycle rule on the bucket.
gcloud scc findings list ORG_ID --filter='state="ACTIVE"'List active security findings--filter, --formatSCC must be activated. Field paths differ between API versions.

Audit and verification

CommandPurposeKey flagsGotcha
gcloud logging read 'severity=ERROR AND protoPayload.status.message:"constraints/"' --freshness=1dFind calls denied by Organization Policy--freshness, --limit, --formatEntries can lag by a minute. Method names vary by service.
gcloud projects describe PROJECT_ID --format="value(parent.id,parent.type)"Find the parent folder of a project--formatFirst step when a policy is "not applied": check the parent.
gcloud services enable cloudkms.googleapis.com secretmanager.googleapis.com cloudasset.googleapis.comEnable the APIs used in this hour--projectFree by itself; the resources created afterwards may cost.

Memory aids

  • Prevent, detect, prove. Organization Policy and VPC Service Controls prevent, Security Command Center and Asset Inventory detect, audit logs prove.
  • Effective first. Always read --effective before you change a policy, and again after.
  • Dry-run before enforce. Perimeters first log, then block.
  • Keys cannot be deleted, versions can. Name key rings carefully; disable before you destroy.
  • Secrets are values, keys are protection. Secret Manager for passwords, Cloud KMS for data encryption.

Capstone lab and final quiz

Guardrails: Organization Policy, VPC Service Controls, keys and detection
Hour 3

Capstone lab for Hour 3: guardrails with proof, a CMEK bucket, and a posture report

Goal. Build a small, safe guardrail layer in a sandbox and prove that it works. You will (1) enforce two Organization Policy constraints on a lab folder and show that each one blocks a real request, (2) protect a bucket with a customer-managed key and prove the kill switch, (3) store a fake secret with a least-privilege binding, and (4) produce a short posture report from Cloud Asset Inventory. Everything ends with a verified rollback.

Prerequisites

  • A sandbox organization with a lab folder that contains one throw-away project. Do not use a folder that holds real workloads. Without an organization, do parts 3 and 4 at project scope and read parts 1 and 2 as explanation.
  • Identity roles: roles/orgpolicy.policyAdmin on the lab folder, roles/cloudkms.admin, roles/storage.admin, roles/secretmanager.admin and roles/compute.instanceAdmin.v1 on the project, and roles/cloudasset.viewer on the folder.
  • The project is linked to a billing account that has a budget with alerts (Hour 1). Budgets send alerts and do not cap spend.
  • gcloud CLI (current release channel) in Cloud Shell or a local shell. Run gcloud version and gcloud auth list first.
  • No real secrets and no service account key files at any point.

IDs in the expected output are illustrative. Check gcloud COMMAND --help for the flags in your SDK version. Note that key rings and keys cannot be deleted: use a sandbox project and the name capstone-ring.

Setup

export FOLDER_ID=FOLDER_ID
export PROJECT_ID=PROJECT_ID
export REGION=europe-west3
export ZONE=europe-west3-a
export BUCKET=capstone-cmek-$PROJECT_ID
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
gcloud services enable compute.googleapis.com cloudkms.googleapis.com secretmanager.googleapis.com cloudasset.googleapis.com storage.googleapis.com --project=$PROJECT_ID

Verify. gcloud projects describe $PROJECT_ID --format="value(parent.id,parent.type)" prints the lab folder ID and folder. If it prints something else, stop: the policies below would apply to the wrong scope.

Part 1. Enforce and prove two constraints (about 15 minutes)

  1. Record the starting state.
    gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective
    gcloud org-policies describe compute.skipDefaultNetworkCreation --project=$PROJECT_ID --effective

    Verify. Save both outputs in your notes. If either already shows a restriction, someone set it above the lab folder; record it, because rollback will return to that state, not to "none".

  2. Write policy-ip.yaml for external IPs.
    name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess
    spec:
      rules:
      - denyAll: true

    Verify. The name line contains the lab folder ID. Replace FOLDER_ID in the file by the real number.

  3. Write policy-net.yaml for the default network.
    name: folders/FOLDER_ID/policies/compute.skipDefaultNetworkCreation
    spec:
      rules:
      - enforce: true

    Verify. The constraint is boolean, so the rule is enforce: true, not denyAll.

  4. Apply both.
    gcloud org-policies set-policy policy-ip.yaml
    gcloud org-policies set-policy policy-net.yaml

    Verify. Each command prints Updated policy [folders/.../policies/...].

  5. Check the effective policy of the project.
    gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective
    gcloud org-policies describe compute.skipDefaultNetworkCreation --project=$PROJECT_ID --effective
    name: projects/PROJECT_ID/policies/compute.vmExternalIpAccess
    spec:
      rules:
      - denyAll: true
    name: projects/PROJECT_ID/policies/compute.skipDefaultNetworkCreation
    spec:
      rules:
      - enforce: true

    Verify. Both show the new values. If not, wait one minute and repeat; propagation can take a short time.

  6. Negative test 1: external IP. The project must have a VPC network (existing projects usually have default; check gcloud compute networks list --project=$PROJECT_ID).
    gcloud compute instances create capstone-vm-denied --project=$PROJECT_ID --zone=$ZONE --machine-type=e2-micro
    ERROR: (gcloud.compute.instances.create) Could not fetch resource:
     - Constraint constraints/compute.vmExternalIpAccess violated for project PROJECT_ID. Add instance projects/PROJECT_ID/zones/ZONE/instances/capstone-vm-denied to the constraint to use external IP with it.

    Verify. The error names the constraint, and gcloud compute instances list --project=$PROJECT_ID shows no such VM. If the VM was created, delete it immediately (gcloud compute instances delete capstone-vm-denied --zone=$ZONE --project=$PROJECT_ID --quiet) and re-check step 5.

  7. Negative test 2: default network (new project). Create a project in the lab folder and look for a network.
    gcloud projects create capstone-net-PROJECT_SUFFIX --folder=$FOLDER_ID
    gcloud services enable compute.googleapis.com --project=capstone-net-PROJECT_SUFFIX
    gcloud compute networks list --project=capstone-net-PROJECT_SUFFIX
    Listed 0 items.

    Verify. The list is empty: no default network was created. Choose a globally unique suffix for PROJECT_SUFFIX, link the project to the budgeted billing account only if the API enable requires it (Compute Engine needs billing), and delete the project in the cleanup. If you cannot create projects, skip this step and mark it "not tested" in the report.

  8. Collect the evidence for test 1.
    gcloud logging read 'protoPayload.methodName="v1.compute.instances.insert" AND severity=ERROR' --project=$PROJECT_ID --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.status.message)"

    Verify. One entry with your identity and the constraint name. Entries can lag by a minute. Copy it to your notes.

Part 2. A CMEK bucket and a kill switch (about 15 minutes, low cost)

  1. Create the key ring and key.
    gcloud kms keyrings create capstone-ring --location=$REGION --project=$PROJECT_ID
    gcloud kms keys create capstone-key --keyring=capstone-ring --location=$REGION --purpose=encryption --rotation-period=90d --next-rotation-time=2027-03-01T00:00:00Z --project=$PROJECT_ID

    Verify. gcloud kms keys describe capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_ID --format="value(primary.state,rotationPeriod)" prints ENABLED and 7776000s.

  2. Grant the Cloud Storage service agent.
    gcloud storage service-agent --project=$PROJECT_ID
    gcloud kms keys add-iam-policy-binding capstone-key --keyring=capstone-ring --location=$REGION \
      --member="serviceAccount:service-${PROJECT_NUMBER}@gs-project-accounts.iam.gserviceaccount.com" \
      --role="roles/cloudkms.cryptoKeyEncrypterDecrypter" --project=$PROJECT_ID

    Verify. gcloud kms keys get-iam-policy capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_ID lists the service agent with the role.

  3. Create the bucket with the default key and write an object.
    gcloud storage buckets create gs://$BUCKET --location=$REGION --uniform-bucket-level-access --project=$PROJECT_ID \
      --default-encryption-key=projects/$PROJECT_ID/locations/$REGION/keyRings/capstone-ring/cryptoKeys/capstone-key
    echo "capstone" | gcloud storage cp - gs://$BUCKET/proof.txt
    gcloud storage cat gs://$BUCKET/proof.txt
    capstone

    Verify. gcloud storage objects describe gs://$BUCKET/proof.txt --format="value(kms_key)" shows the key version used.

  4. Prove the kill switch.
    gcloud kms keys versions disable 1 --key=capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_ID
    gcloud storage cat gs://$BUCKET/proof.txt

    Verify. The read fails with a 403 that mentions the Cloud KMS key (exact wording may differ). Then enable the version and read again:

    gcloud kms keys versions enable 1 --key=capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_ID
    gcloud storage cat gs://$BUCKET/proof.txt

    Verify. The object reads again and prints capstone.

  5. Store a fake secret with a least-privilege binding.
    gcloud secrets create capstone-secret --replication-policy=automatic --project=$PROJECT_ID
    printf 'not-a-real-secret' | gcloud secrets versions add capstone-secret --data-file=- --project=$PROJECT_ID
    gcloud secrets versions access 1 --secret=capstone-secret --project=$PROJECT_ID

    Verify. The last command prints not-a-real-secret. Then list who can read it: gcloud secrets get-iam-policy capstone-secret --project=$PROJECT_ID. Only you (via the project role) appear; no allUsers, no broad group.

Part 3. A posture report (about 10 minutes, free)

  1. Inventory buckets in the lab folder.
    gcloud asset search-all-resources --scope=folders/$FOLDER_ID --asset-types=storage.googleapis.com/Bucket --format="table(name,location,project)" --billing-project=$PROJECT_ID

    Verify. The capstone bucket appears. The index can lag by a few minutes after creation; repeat if needed.

  2. Check for public bindings.
    gcloud asset search-all-iam-policies --scope=folders/$FOLDER_ID --query="policy:allUsers OR policy:allAuthenticatedUsers" --billing-project=$PROJECT_ID

    Verify. The result is empty. If it is not, the listed resources are your first triage items.

  3. Write the report. In a text file list: (a) the two constraints, the folder and the evidence line from the audit log; (b) the key, rotation period and the result of the kill-switch test; (c) the secret name and who can read it; (d) the inventory counts; (e) one finding or risk you would triage next, with owner and decision (fix, accept, prevent).

Expected result

  • Both policies are effective on the project; the VM with an external IP is refused with the constraint name; a new project in the folder has no default network.
  • The bucket is CMEK-protected; reads fail while the key version is disabled and work after enabling it.
  • The fake secret is readable by you only.
  • The report has audit evidence, key details, inventory counts and one triage decision.

Cost

Low (usually well under a few USD per day for this lab): one software key version, one tiny object, one secret version. The VM is never created and policy changes are free. Budgets send alerts and do not cap spend. If a VM was created by mistake, delete it at once.

Cleanup (in this order)

  1. Remove the guardrails (rollback).
    gcloud org-policies delete compute.vmExternalIpAccess --folder=$FOLDER_ID
    gcloud org-policies delete compute.skipDefaultNetworkCreation --folder=$FOLDER_ID
    gcloud org-policies list --folder=$FOLDER_ID

    Verify. Neither constraint is listed on the folder, and the effective policy of the project equals the starting state from Part 1, step 1.

  2. Delete the bucket and the secret.
    gcloud storage rm -r gs://$BUCKET
    gcloud secrets delete capstone-secret --project=$PROJECT_ID --quiet
  3. Schedule destruction of the key version (the key ring and key remain by design and cost nothing without an enabled version).
    gcloud kms keys versions destroy 1 --key=capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_ID
  4. Delete the extra project and, if you created them only for this lab, the main project and the folder.
    gcloud projects delete capstone-net-PROJECT_SUFFIX
    gcloud projects delete $PROJECT_ID
    gcloud resource-manager folders delete $FOLDER_ID

    Verify. gcloud projects list --filter="parent.id=$FOLDER_ID" is empty before you delete the folder. Projects stay recoverable for a short period after deletion.

  5. Delete the local YAML files and the report if it contains resource names that you do not want to keep.

Troubleshooting the capstone

SymptomLikely causeFirst check
set-policy says PERMISSION_DENIEDMissing roles/orgpolicy.policyAdminFolder IAM policy for your identity
The VM is created although the policy is setPolicy not in force yet, wrong folder, or the project has a different parentgcloud projects describe PROJECT_ID --format="value(parent)"
Bucket creation fails with a KMS permission errorService agent binding missing or in the wrong project numbergcloud kms keys get-iam-policy ...
ALREADY_EXISTS for the key ringKey ring names are permanentChoose a new name such as capstone-ring-2
Asset search shows nothingAPI not enabled in the quota project, or index delayPass --billing-project; wait a few minutes

Knowledge check

Sources and versions

Guardrails: Organization Policy, VPC Service Controls, keys and detection
Hour 3

Reference documentation for Hour 3

These are the official pages behind the commands and concepts of this hour. Product documentation changes often, so use the page itself as the final reference when it differs from this course.

Organization Policy

Assured Workloads and VPC Service Controls

Cloud KMS and Secret Manager

Detection and posture

Architecture guidance and infrastructure as code

Tools and versions used

ToolVersion used in this hourNote
gcloud CLICurrent release channelCheck with gcloud version; update with gcloud components update where the component manager is available.
Cloud ShellManaged by GoogleComes with a recent gcloud CLI installed.
Terraform (for the optional policy-as-code mentions)Terraform 1.x with the Google providerPin the major version in required_providers.
APIscloudkms, secretmanager, cloudasset, orgpolicy, accesscontextmanager, securitycenterEnabled per project (or at organization level for some services).
Check before production use. Flags, constraint names, SCC tiers and detector names, and product features change between releases. The commands in this course use the documented forms we are confident about, and several lessons say "check gcloud ... --help for the flags in your SDK version". Do that, test in a sandbox folder, and read the current documentation page for each service before you copy a command into automation or a production runbook. Expected outputs use illustrative IDs and are not measurements. No pricing is stated here: use the current pricing pages and budget alerts, and remember that budgets alert and do not cap spend.