Hour 3: Guardrails: Organization Policy, VPC Service Controls, keys and detection
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)
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
| Module | What the lab does | Billable resources | Cost class |
|---|---|---|---|
| 1 | Reads effective policy; sets and deletes a dry-run policy on a lab folder | None | Free |
| 2 | Audits the eight baseline constraints; optional policy on a lab folder | None (an optional test key would be deleted) | Free |
| 3 | Worksheet and read-only inspection of a regulated folder; no workload is created | None | Free |
| 4 | Dry-run perimeter around a sandbox project with one test bucket | One bucket with one tiny object, log entries | Low (usually well under a few USD per day for this lab) |
| 5 | KMS key ring and key, a CMEK bucket, a secret, a disable test | One software key version, one tiny object, one secret version | Low |
| 6 | Read-only inventory and triage of one finding | None | Free |
| 7 | Deny external IPs on a lab folder, try to create a VM, restore | None, because creation is denied | Free |
| 8 | Diagnose simulated incidents with read-only commands | None | Free |
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.
ORG_ID and FOLDER_ID in the commands. IDs in the expected output are illustrative.Setup
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
| Option | What works | What does not |
|---|---|---|
| Sandbox organization (recommended): a Cloud Identity Free domain you own, or a training organization | Everything: 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 roles | Policies and read commands scoped to your lab folder; projects below it; KMS and Secret Manager in your lab project | Organization-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 reads | Folder policies, VPC Service Controls (perimeters need an organization), organization inventory, Security Command Center organization features |
--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 needroles/orgpolicy.policyVieweron 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.
| For | Role | Scope |
|---|---|---|
| Reading policies | roles/orgpolicy.policyViewer | Lab folder |
| Setting and deleting policies (Modules 1, 2, 7) | roles/orgpolicy.policyAdmin | Lab 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.reader | Organization |
| Keys and secrets (Module 5) | roles/cloudkms.admin, roles/secretmanager.admin | Lab project |
| Inventory and findings (Module 6) | roles/cloudasset.viewer, roles/securitycenter.findingsViewer | Lab folder or project (organization if allowed) |
| VM request in the lab (Module 7) | roles/compute.instanceAdmin.v1 | Lab project |
| Reading audit logs | roles/logging.viewer (or roles/logging.privateLogViewer for data access logs) | Lab project or folder |
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_IDand 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.
Module 1 · Organization Policy
- 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, orvalueswithallowedValuesanddeniedValues(list). A rule may carry acondition, 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
- A user or pipeline calls a service API (for example,
instances.insertin Compute Engine). - IAM checks permission first. If IAM denies, the request ends there.
- 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.
- If the requested configuration violates the effective policy, the API returns
FAILED_PRECONDITION(HTTP 400) with the constraint name. Nothing is created. - The decision is recorded in Cloud Audit Logs, which is how you find who tried what.
Inheritance and merging
| Setting on the child | Effect on the effective policy |
|---|---|
| No policy | The 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 rule | The child's rules replace the parent's for that node. |
reset: true | The node returns to the constraint's default behaviour, ignoring parent rules. |
Boolean constraint enforce: true on a parent | Inherited. A child may set enforce: false, which turns the rule off for that subtree. Administrators therefore protect the permission orgpolicy.policy.set. |
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
| Type | Example | How a policy is written |
|---|---|---|
| Boolean | iam.disableServiceAccountKeyCreation, compute.requireOsLogin | rules: - enforce: true |
| List | gcp.resourceLocations, compute.vmExternalIpAccess, iam.allowedPolicyMemberDomains | rules: - values: allowedValues: [...] or denyAll: true or allowAll: true |
| Custom | custom.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
| Control | Question it answers | Where it applies |
|---|---|---|
| IAM allow policy | Who may call this API on this resource? | Principals and resources |
| IAM deny policy | Who may never call it, even if an allow exists? | Principals and permissions |
| Organization Policy | Which configurations may exist? | Resource configuration, whoever calls |
| VPC Service Controls | From where may Google-managed services be reached? | API traffic across a perimeter (Module 4) |
| Firewall policy | Which network flows are allowed? | Packets in a VPC (Hour 4) |
| AWS SCP / Azure Policy | Closest 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 currentgcloud org-policiescommands accept the short form, for examplecompute.vmExternalIpAccess. Terraform and the API return the full form.
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.
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.
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.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.
- Set shell variables:
export FOLDER_ID=555555555555andexport PROJECT_ID=lab-sandbox-1234(use your own values). - Enable the API:
gcloud services enable orgpolicy.googleapis.com --project=$PROJECT_ID. - Read what is set on the folder:
gcloud org-policies list --folder=$FOLDER_ID. Write down the constraints you see. - Read the effective policy of a constraint on the project:
gcloud org-policies describe compute.requireOsLogin --project=$PROJECT_ID --effective. Record whetherenforceistrue. - Create
dryrun.yamlwith the dry-run content shown in the commands tab, replacingFOLDER_ID. - Apply it:
gcloud org-policies set-policy dryrun.yaml. - Verify it was stored as a dry-run only:
gcloud org-policies describe compute.requireOsLogin --folder=$FOLDER_ID. The output must containdryRunSpec:and must not contain an enforcedspec:withenforce: true. - Verify the effective policy did not change: repeat step 4. The answer must be the same as before.
- Clean up:
gcloud org-policies delete compute.requireOsLogin --folder=$FOLDER_ID, thengcloud org-policies list --folder=$FOLDER_IDand 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.resourceLocationson 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.requireOsLoginon 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, thennonprod, thenprod. - 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.policyAdminto a platform group. Alert on audit eventsSetOrgPolicyand on changes togoogle_org_policy_policyin 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.
orgpolicy.policy.set like resourcemanager.organizations.setIamPolicy: reviewed membership, strong authentication, and an alert when anyone uses it.org-policies delete) written in the change ticket.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Constraint constraints/... violated for project ... | The effective policy forbids the requested configuration | gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective, then find which ancestor sets the rule |
PERMISSION_DENIED ... orgpolicy.policy.set when you set a policy | Missing roles/orgpolicy.policyAdmin on that node | gcloud organizations get-iam-policy ORG_ID and the folder equivalent, filtered to your identity |
NOT_FOUND from describe without --effective | No 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 it | The resource existed before enforcement; the rule is not retroactive | Cloud Asset Inventory search for the property; fix the resource |
| Project override seems ignored | Parent rule is denyAll and the child merges with inheritFromParent: true; deny wins | Read the effective policy; set inheritFromParent: false only if the exception is intended |
etag mismatch or ABORTED on update | Someone changed the policy after you downloaded the file | gcloud org-policies describe ... again, merge, retry |
API error orgpolicy.googleapis.com has not been used | The API is disabled in the calling project | gcloud services enable orgpolicy.googleapis.com --project=PROJECT_ID |
| Change takes minutes to apply | Policy propagation is eventually consistent | Wait a few minutes, then retry the blocked action |
Triage order
- Read the exact error text. A line that names a
constraints/...means Organization Policy, not IAM. - Run
describe --effectiveon the project for that constraint. - Walk up the hierarchy with
gcloud projects describe PROJECT_ID --format="value(parent)"andliston each parent to find where the rule is set. - Check for a tag condition on the rule and whether the resource carries the tag.
- 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.
- YouTube search: Google Cloud Organization Policy constraints
- YouTube search: Organization Policy dry-run
- YouTube search: custom Organization Policy constraints
Official reading: Organization Policy Service overview · Understanding hierarchy evaluation · Organization Policy constraints reference · Dry-run policies.
Module 2 · Essential constraint catalogue
- 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
| Constraint | Type | What it blocks | Typical value |
|---|---|---|---|
iam.disableServiceAccountKeyCreation | Boolean | Creating user-managed service account keys (JSON or P12 files) | enforce: true |
iam.allowedPolicyMemberDomains | List | Granting roles to identities from other domains, and to allUsers or allAuthenticatedUsers | Your Cloud Identity customer ID |
gcp.resourceLocations | List | Creating resources outside the approved regions | in:eu-locations or a list of regions |
compute.vmExternalIpAccess | List | VMs with a public (external) IP address | denyAll: true |
compute.requireOsLogin | Boolean | VM access by project or instance SSH keys in metadata; requires IAM-based OS Login | enforce: true |
compute.skipDefaultNetworkCreation | Boolean | The automatic default network and its default firewall rules in new projects | enforce: true |
storage.uniformBucketLevelAccess | Boolean | New buckets that use object ACLs; all access goes through IAM | enforce: true |
sql.restrictPublicIp | Boolean | Cloud SQL instances with a public IPv4 address | enforce: 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
| Constraint | Set on | Reason |
|---|---|---|
| Key creation, domains, default network, uniform access, public SQL | Organization | No legitimate exception; consistent everywhere |
| Resource locations | Organization with a folder-level override | Different business units may have different regions |
| External IP, OS Login | Organization or the production and nonprod folders | A 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.
Figure 1. The baseline grouped by risk. When you are asked "why this constraint?", answer with the group and the incident it prevents.
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".
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.
- Set
export PROJECT_ID=lab-sandbox-1234. - Run the loop from the commands tab and save the output:
... | tee baseline-before.txt. - For each constraint, mark it as enforced, not enforced or list restricted in a small table.
- 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. - Write
sa-keys.yaml,domains.yamlandlocations.yamlexactly as in the commands tab, with your own IDs. Do not apply them to the organization. - Verify the files parse as YAML:
python -c "import yaml,sys; yaml.safe_load(open('sa-keys.yaml'))"(any YAML linter works). - Optional, on a lab folder only: apply
sa-keys.yamland checkgcloud org-policies describe iam.disableServiceAccountKeyCreation --folder=FOLDER_IDshowsenforce: true. - Optional: confirm the denial with
gcloud iam service-accounts keys create /dev/null --iam-account=SA_EMAIL. ExpectFAILED_PRECONDITION. - 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.allowedPolicyMemberDomainswould 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 andstorage.publicAccessPreventionon 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 enforcedcompute.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.
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.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Key creation is not allowed on this service account | iam.disableServiceAccountKeyCreation is enforced | Use 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 customer | Domain restricted sharing | Identify the member's domain; add its customer ID only if a contract exists |
'REGION' violates constraint 'constraints/gcp.resourceLocations' | Region not in the allowed list | Read the effective value of the constraint; choose an allowed region |
Constraint constraints/compute.vmExternalIpAccess violated | VM requested an external IP | Remove --address and external access config; use --no-address with Cloud NAT |
| Cannot SSH after enabling OS Login | User lacks roles/compute.osLogin or the VM uses metadata keys | gcloud 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 enforced | Attach the project to a Shared VPC or create a custom network |
| Bucket creation fails with ACL error | storage.uniformBucketLevelAccess enforced | Create with --uniform-bucket-level-access; remove ACL settings from the template |
| Cloud SQL creation fails on public IP | sql.restrictPublicIp enforced | Use --no-assign-ip with private services access, or request an exception |
Triage order
- Copy the constraint name from the error text.
- Run
describe --effectiveon the project and read the rules. - Locate the node that sets the rule (organization, folder or project) with
liston each ancestor. - Pick the legitimate fix: change the request, use a tagged exception, or change the policy through review.
- 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.
- YouTube search: domain restricted sharing
- YouTube search: disable service account key creation
- YouTube search: resource location restriction
Official reading: Organization Policy constraints reference · Restricting resource locations · Restricting identities by domain · Security foundations guide.
Module 3 · Assured Workloads and regulated folders
- 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.resourceLocationsset 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)
| Family | Examples | Typical reason to use it |
|---|---|---|
| US government | FedRAMP Moderate and High, CJIS, DoD Impact Levels, ITAR | Contract with a US agency or its suppliers |
| Health and finance | HIPAA and HITRUST-related packages | Protected health information with specific controls |
| Regional data residency | Data residency and support packages for the EU, Canada, Australia, Japan and other regions | Law or contract that requires data and support in a region |
| Sovereign controls | Packages built with local partners for sovereign requirements | Government 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
- An administrator with
roles/assuredworkloads.adminon the organization creates a workload: name, regime, location and billing account. - 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.
- 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.
- You create projects inside the folder. Each project's resources obey the folder's policies.
- 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
| Term | Asks | Tools |
|---|---|---|
| Data residency | Where is the data stored and processed? | gcp.resourceLocations, regional services, regional buckets and datasets |
| Data sovereignty | Who can access it, and under which legal authority? | CMEK or external keys, access justification, local support packages, contracts |
| Compliance | Can you show that required controls are in place? | Assured Workloads package, audit logs, evidence, your own control framework |
| Exfiltration protection | Can 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
| Control | Relation 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 organization | A 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.
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.
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.
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.
- Copy this worksheet into a file and complete it. Columns: workload, data type, law or contract, required location, support-staff condition, services needed, decision.
- Workload A: a public marketing website with no personal data. Expected decision: baseline only.
- Workload B: customer records of an EU retailer, contract says "stored in the EU". Expected decision: baseline plus
gcp.resourceLocationswithin:eu-locationson the folder. - 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.
- 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.
- Optional, read-only: run
gcloud assured workloads list --organization=ORG_ID --location=LOCATION. If a workload exists, rundescribeand note the regime. - Optional: run
gcloud org-policies describe gcp.resourceLocations --folder=WORKLOAD_FOLDER_IDand compare the allowed values with your worksheet. - 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.
roles/assuredworkloads.admin and roles/orgpolicy.policyAdmin, use strong authentication, and alert on any change of policy inside the folder.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Cannot create a resource in the folder: violates constraint gcp.resourceLocations | Region is outside the package's allowed locations | gcloud 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 violation | The service is not covered by the regime and is restricted in the folder | Read the effective gcp.restrictServiceUsage policy and the package's supported-services page |
| Violation reported on the workload | A policy was changed or a resource breaks a control | Open the violation in the Assured Workloads page; read audit logs for the change |
PERMISSION_DENIED when listing or creating workloads | Missing roles/assuredworkloads.* on the organization | gcloud organizations get-iam-policy ORG_ID filtered to your identity |
SERVICE_DISABLED for assuredworkloads.googleapis.com | API not enabled in the calling project | gcloud services enable assuredworkloads.googleapis.com --project=PROJECT_ID |
| Project move into the folder fails or creates violations | Existing resources conflict with controls | List resources with gcloud asset search-all-resources --scope=projects/PROJECT_ID and compare locations and services |
| Key-related error after creating the workload | Key settings of the package are not met, or the key is disabled | Check the key state in Cloud KMS and the workload's key settings |
Triage order
- Read the full error. Does it name a constraint? Then it is Organization Policy applied by the workload.
- Read the effective policy on the project and find which folder sets it.
- Decide whether the request is legitimate for this regime. If not, move the work to another folder.
- 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.
- 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.
- YouTube search: Assured Workloads overview
- YouTube search: data residency and sovereignty on Google Cloud
- YouTube search: compliance and shared responsibility on Google Cloud
Official reading: Assured Workloads overview · Supported products · Compliance resource center · Security foundations guide.
Module 4 · VPC Service Controls
- 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
| Object | What it is | Where it lives |
|---|---|---|
| Access policy | The container of levels and perimeters. One organization-wide policy; scoped policies can exist for folders or projects | Access Context Manager, accessPolicies/POLICY_ID |
| Access level | A named condition: IP ranges, a device policy, regions, or specific identities | Inside the access policy |
| Service perimeter | A set of projects (by number) plus restricted services, optional access levels, ingress and egress rules | Inside the access policy |
| Perimeter bridge | A link that lets two perimeters exchange data. Often replaced by ingress and egress rules | Inside the access policy |
| VPC accessible services | A list that limits which APIs the VMs in the perimeter can reach on their network | Perimeter setting |
How a request is evaluated
- A client calls a restricted service (for example,
storage.googleapis.com) on a project that is inside a perimeter. - IAM runs as usual. If IAM denies, the request ends.
- VPC Service Controls checks the source. If the caller is a resource inside the same perimeter, the call passes.
- 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.
- 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.
- If nothing matches, the API returns
403withRequest is prohibited by organization's policyand avpcServiceControlsUniqueIdentifier. The violation is written to audit logs.
Access levels, ingress and egress: which tool to use
| Need | Use | Example |
|---|---|---|
| Admins on the corporate network or managed laptops reach the console and APIs | Access level | IP subnetworks of the office VPN, device policy |
| A named pipeline outside the perimeter reads or writes specific services inside | Ingress rule | CI service account → storage.googleapis.com on one project |
| Workloads inside the perimeter call a service in another project or perimeter | Egress rule | Application project → shared Artifact Registry or a vendor project |
| Two perimeters exchange data frequently | Matching egress and ingress rules (or a bridge) | Prod data perimeter and analytics perimeter |
| Quick troubleshooting of one blocked call | The audit log with the unique identifier | Look 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
| Control | Works on | Limit |
|---|---|---|
| VPC Service Controls | Google API calls and their context | Does not stop packets between VMs |
| Firewall rules and policies | Network packets | Do not understand which Google API or project is called |
| Private Google Access | Whether a VM without external IP can reach Google APIs | Does not restrict which projects it reaches |
| IAM Conditions | Who and when for a binding | Cannot express "only from these projects" for data copy |
| Organization Policy | Resource configuration | Cannot 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.
roles/accesscontextmanager.policyAdmin before you create the first perimeter.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.
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.
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.
- 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. - Enable the API in the sandbox project:
gcloud services enable accesscontextmanager.googleapis.com storage.googleapis.com --project=PROJECT_ID(free). - 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. - Put one small object in it:
echo hello | gcloud storage cp - gs://BUCKET_NAME/hello.txt. - Read the project number:
gcloud projects describe PROJECT_ID --format="value(projectNumber)". - Create the dry-run perimeter with the command from the commands tab (no access level, so every outside caller is a violation).
- Verify:
gcloud access-context-manager perimeters describe lab_perimeter --policy=POLICY_IDshows aspecsection and nostatussection. - 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. - Read the violation log with the query of the commands tab. Expect one or more entries with
dryRuntrue. Log entries can arrive a few minutes late; retry. - 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.comfor 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.
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.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: ... | Call crossed a perimeter boundary without a matching rule | Search audit logs for the unique identifier; read violationReason and the source and target |
| Cloud Build fails to read or write a bucket in the perimeter | The Cloud Build service account runs outside the perimeter or its project is not in it | Put 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 fails | Source and destination are in different perimeters or one is outside | Add 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 Console | Their network is not in an access level | Check 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 delivering | The sink's writer identity is outside the perimeter | Add an ingress rule for the writer identity on the destination service |
Terraform apply fails with 403 ... VPC_SERVICE_CONTROLS | CI identity is outside the perimeter or lacks an ingress rule | Read the unique identifier; add a narrow ingress rule for the CI service account |
| A rule seems to have no effect | Propagation delay, or the rule was added to spec but not to status | Wait; run perimeters describe and check which configuration holds the rule |
| Project cannot be added to a perimeter | Project number is wrong, or it already belongs to another regular perimeter | Check the number; a project can be in only one regular perimeter |
Triage order
- Is the error a VPC Service Controls error (unique identifier) or an IAM error (permission name)?
- Find the audit log entry. Read the source (identity, network or access level) and the target (service and project).
- Check whether the service is a restricted service of the perimeter and whether both projects are inside.
- Choose the narrowest fix: access level for humans, ingress rule for a named outside identity, egress rule for a named outside resource.
- 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.
- YouTube search: VPC Service Controls overview
- YouTube search: VPC Service Controls dry-run, ingress and egress rules
- YouTube search: Access Context Manager access levels
Official reading: VPC Service Controls overview · Supported products · Troubleshooting · Dry-run mode · Access Context Manager.
Module 5 · Keys and secrets
- 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
| Resource | What it is | Can it be deleted? |
|---|---|---|
| Key ring | A 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 version | The 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 level | SOFTWARE, 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.restrictNonCmekServicesblocks creation of unprotected resources in listed services, andconstraints/gcp.restrictCmekCryptoKeyProjectslimits 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.secretAccessorreads values,roles/secretmanager.secretVersionAdderadds versions,roles/secretmanager.adminmanages 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
| Need | Use | Not |
|---|---|---|
| Encrypt a bucket, disk, BigQuery dataset or database with a key you control | Cloud KMS with CMEK | Secret Manager |
| Give an application a database password or API token | Secret Manager | Cloud KMS (it does not store arbitrary values) |
| Prove who used the key and when | Cloud KMS audit logs | Application logs |
| Let a CI pipeline call Google APIs | Workload Identity Federation (Hour 2) | A service account key file in a secret |
What it is confused with
| Pair | Difference |
|---|---|
| Cloud KMS vs Secret Manager | KMS keys encrypt data and never leave KMS (for non-exportable keys). Secret Manager returns the stored value to an authorised caller. |
| CMEK vs CSEK | CMEK 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 EKM | Cloud 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 rotation | KMS 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
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.
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
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.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.
- 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)")
- Create the key ring and key. Use the two commands from the previous tab with
lab-ringandlab-key.Verify:
gcloud kms keys list --keyring=lab-ring --location=$REGION --project=$PROJECT_IDlistslab-keywith stateENABLEDfor the primary. - 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_IDVerify:
gcloud kms keys get-iam-policy lab-key --keyring=lab-ring --location=$REGIONshows the service agent in the binding. - 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. - Write and read an object.
echo "hello cmek" | gcloud storage cp - gs://$BUCKET/hello.txt gcloud storage cat gs://$BUCKET/hello.txt
hello cmek
- 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
- 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_IDshows version 1 asenabled. - 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.cryptoKeyEncrypterDecrypterfor services, and keeproles/cloudkms.adminaway 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 withconstraints/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.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Permission denied on Cloud KMS key when a service writes data | The service agent lacks cryptoKeyEncrypterDecrypter on the key | gcloud kms keys get-iam-policy KEY --keyring=RING --location=LOCATION; confirm the agent for that project number |
| Data became unreadable overnight | Key version disabled or scheduled for destruction | gcloud kms keys versions list --key=KEY --keyring=RING --location=LOCATION; then re-enable if destruction is not complete |
| Cannot create a CMEK resource: location mismatch | Key and resource are in different locations | Compare the location in the key name with the resource location |
ALREADY_EXISTS creating a key ring | Key ring names are permanent in a project and location | gcloud kms keyrings list --location=LOCATION; choose a new name |
PERMISSION_DENIED secretmanager.versions.access | Caller lacks roles/secretmanager.secretAccessor on the secret, or the wrong identity is used | gcloud secrets get-iam-policy SECRET; gcloud auth list |
| Secret read returns an old value | Application pinned a version or cached the value | gcloud secrets versions list SECRET; check which version the app requests |
| Creating a resource is blocked: CMEK required | gcp.restrictNonCmekServices is enforced | gcloud org-policies describe gcp.restrictNonCmekServices --project=PROJECT_ID --effective |
Triage order
- Read the exact error text; KMS errors name the key and the operation.
- Check the key version state, then the key IAM policy, then the location.
- Find the caller in the audit log (
cloudkms.googleapis.com) to see which identity failed. - 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.
- YouTube search: Cloud KMS and CMEK
- YouTube search: Secret Manager best practices
- YouTube search: envelope encryption on Google Cloud
Official reading: Cloud KMS documentation · Customer-managed encryption keys · Secret Manager documentation.
Module 6 · Detection and posture
- 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-resourcesandsearch-all-iam-policiesto 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_ACLorOPEN_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.findingsViewerandroles/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
- Resources and policies change. Asset Inventory captures the new state from the service APIs.
- Detectors compare that state with a rule (for example "a bucket is readable by allUsers").
- 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.
- Notifications and exports carry the finding to people and ticket systems.
- 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
| Control | When it acts | Example | Weakness |
|---|---|---|---|
| Preventive | Before the change | compute.vmExternalIpAccess denies external IPs | Cannot cover rules that depend on context; does not fix old resources |
| Detective | After the change | SCC finding for a public bucket | The exposure exists until someone acts |
| Corrective | After detection | Automation that removes a public ACL | Needs 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
| Pair | Difference |
|---|---|
| SCC vs Cloud Audit Logs | Audit 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 Monitoring | Monitoring watches metrics and availability. SCC watches security posture. |
Asset Inventory vs gcloud ... list | list works per project and per service API. Asset Inventory searches across a scope with one query and one permission. |
| Security Health Analytics vs Organization Policy | SHA reports problems that already exist. Organization Policy prevents new ones. Use SHA to decide which constraints to enforce next. |
| Recommender vs SCC | Recommender (for example IAM recommendations) suggests permission and cost improvements. SCC reports security findings. |
Common misunderstandings
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.
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.
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.
- 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_IDlists the Cloud Asset API. - 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.
- 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.
- 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.
- 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.
- Write the triage decision. Pick one finding (or use this simulated one: category
OPEN_SSH_PORT, resource firewallallow-ssh, source range0.0.0.0/0) and fill in this table in your notes:Question How to answer Your answer Severity From the finding Exposure gcloud compute firewall-rules describe NAMEand which instances carry the target tagOwner Labels and parent folder from gcloud projects describe PROJECT_IDDecision Fix, accept with review date, or prevent with a guardrail - Choose a guardrail for the cause. For the open SSH example, name one preventive control (for example
compute.requireOsLoginwith 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
allUsersbindings 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 constraintstorage.publicAccessPreventionon 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
ownerlabel 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.
roles/securitycenter.findingsViewer and roles/cloudasset.viewer to the security team and auditors only, through groups, and review the audit logs of those roles.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
PERMISSION_DENIED on search-all-resources | Missing roles/cloudasset.viewer at the scope | gcloud organizations get-iam-policy ORG_ID filtered to your identity |
SERVICE_DISABLED for cloudasset.googleapis.com | API not enabled in the quota project | Pass --billing-project=PROJECT_ID and enable the API in that project |
| Search results miss a recent resource | Index delay | Wait a few minutes and repeat; use the service API list for an immediate check |
scc findings list returns nothing | SCC not activated, or first scan not complete, or wrong filter fields | Check activation in the console; run the command without --filter |
| Finding stays ACTIVE after the fix | Rescan has not run, or the fix did not change the detected property | Re-describe the resource; wait for the next scan; check the finding's recommendation |
| Thousands of near-identical findings | One root cause repeated (a default network in every project) | Group by category and parent; fix the cause with a constraint |
| Notification not delivered | Pub/Sub topic or subscription misconfigured | Check the notification config and the topic's IAM for the SCC service account |
Triage order
- Is it a threat finding or a configuration finding? Threats go to the incident process.
- Severity, then exposure (internet reachable, sensitive data).
- Find the owner through labels, parent folder and the asset's IAM policy.
- Decide: fix, accept with a review date, or prevent. Record the reason.
- 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.
- YouTube search: Security Command Center overview
- YouTube search: Cloud Asset Inventory
- YouTube search: Security Health Analytics findings
Official reading: Security Command Center documentation · Cloud Asset Inventory overview.
Module 7 · Lab: enforce and prove a constraint
- 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 deleteand 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.vmExternalIpAccessis 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, orallowAll: 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.policyAdminto change, on the organization or folder where you set the policy.
Why: the method
| Step | Why it exists | What goes wrong if skipped |
|---|---|---|
| Read the effective policy first | You learn the starting state and any inherited value | You overwrite a policy that someone else set |
| Use a lab folder | Blast radius is small | A production deployment is blocked |
| Write the policy as a file | It can be reviewed, committed and repeated | The change cannot be reproduced or audited |
| Negative test | Shows that the control works, not only that it is set | A policy that has no effect is assumed to protect |
| Read the audit log | Produces evidence | An auditor has only your word |
| Rollback and verify | Leaves no hidden guardrail in a shared folder | The next lab fails in a confusing way |
How it works internally
- 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.
- 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).
- 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. WithdenyAll, nothing is. - 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
| Pair | Difference |
|---|---|
--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 rule | A firewall rule limits traffic to an address. The constraint stops the address from being created. |
| Dry-run vs enforce | A 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 delete | set-policy replaces the policy on that resource with your file. delete removes your policy; inheritance applies again. |
Common misunderstandings
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.
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].
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.policyAdminon the folder (or organization), androles/compute.instanceAdmin.v1on 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.
- 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. - Read the starting state.
gcloud org-policies describe compute.vmExternalIpAccess --project=$PROJECT_ID --effective
Verify: note the result. A fresh organization shows
allowAll: trueor no restriction. If it already showsdenyAllor a list, someone set a policy above you: stop, record it, and choose another folder, otherwise the cleanup would hide the difference. - Write the policy file. Save as
policy.yamlin your working directory:name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess spec: rules: - denyAll: true
Verify: the
nameline contains your lab folder ID and not an organization ID. Print it:cat policy.yaml. - Apply it.
gcloud org-policies set-policy policy.yaml
Verify: the output prints
Updated policy [folders/FOLDER_ID/policies/compute.vmExternalIpAccess]and thedenyAll: truerule. - 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. - 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_IDshows novm-lab-denied. If the VM exists, the policy is not in force yet: delete the VM, wait, and repeat step 5. - 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-addressis the allowed path and that it requires Private Google Access or Cloud NAT for egress (Hour 4). - 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. - 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_IDno longer listscompute.vmExternalIpAccess. - 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 avaluesrule withallowedValuesand 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.skipDefaultNetworkCreationon the folder, and create a new project in it to prove that nodefaultnetwork 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 holdsroles/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
SetOrgPolicyand policy changes in the audit log, so that every guardrail change is visible.
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
| Symptom | Likely cause | First check |
|---|---|---|
PERMISSION_DENIED on set-policy | Missing roles/orgpolicy.policyAdmin on the folder or organization | gcloud resource-manager folders get-iam-policy FOLDER_ID, filtered to your identity |
| Effective policy still shows the old value | Propagation delay, or the policy was set on another resource | Wait a minute; gcloud org-policies list --folder=FOLDER_ID; check the name line of the file |
| VM was created although the policy is set | Policy not yet in force, wrong folder, or the project is under another parent | gcloud projects describe PROJECT_ID --format="value(parent)"; delete the VM at once |
| Different error: network not found | No default network in the project (skipDefaultNetworkCreation or deleted) | gcloud compute networks list --project=PROJECT_ID |
INVALID_ARGUMENT on set-policy | Wrong 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 nothing | Filter too narrow, ingestion delay, or wrong project | Remove the message clause; wait a minute; confirm the project |
| After rollback the effective policy is still denyAll | A parent folder or the organization also sets it | gcloud org-policies describe compute.vmExternalIpAccess --organization=ORG_ID |
Triage order
- Confirm identity and scope:
gcloud config list account, and the parent of the project. - Read the effective policy; if it is wrong, read the policy at each ancestor.
- Read the exact error text of the denied call and compare it with the constraint name.
- Check the audit log of the denied call for the principal and the reason.
- 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.
Module 8 · Production and troubleshooting
- 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
| Incident | Typical error text | Where the truth is |
|---|---|---|
| Organization Policy blocks a deploy | Constraint constraints/... violated for project ... or FAILED_PRECONDITION | gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective, the audit log of the denied call |
| VPC Service Controls breaks a pipeline | Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: ... | Audit log entries with VpcServiceControlAuditMetadata, in the project or at the organization |
| Disabled or destroyed CMEK key | Key errors from the data service, for example a failed precondition about the key version | Cloud KMS key version state and key audit logs |
| Noisy SCC findings | No error; a queue nobody owns | SCC 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
- Classify the error: Organization Policy, VPC Service Controls, IAM, quota, API not enabled, or key. The text of the message is usually enough.
- Identify the principal, the resource and the method from the log entry, not from the person's description.
- Read the effective state: effective Organization Policy, perimeter configuration (including dry-run), key version state, IAM with
gcloud policy-troubleshoot iamwhere IAM is suspected. - Fix the smallest thing: a precise ingress rule, an allowed value, an enabled version, an owner label, or a guardrail that prevents the cause.
- 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 like | Actually | How to tell |
|---|---|---|
| An IAM problem | VPC Service Controls | IAM errors name a missing permission. VPC-SC errors name the organization's policy and have a unique identifier. |
| An IAM problem | Organization Policy | The message names a constraints/... value. |
| A firewall problem | VPC Service Controls | The failure is from a Google API call, not a TCP timeout to a VM. |
| A KMS permission problem | A disabled key version | IAM on the key is correct but operations still fail; the version state is not ENABLED. |
| An SCC outage | Missing activation or notification config | Findings exist in the console but do not reach the ticket system. |
Common misunderstandings
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.
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.
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.
- Classify the error. (It names a constraint: Organization Policy.)
- Run
gcloud org-policies describe gcp.resourceLocations --project=PROJECT_ID --effective. Record the allowed values. - Decide: deploy to an allowed zone, or request an exception. Write the one-line reason for your choice.
- 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
- Classify the error. (VPC Service Controls: the text and the identifier.)
- Use the log command from the commands tab with
UNIQUE_ID=5b1b6c8a9f3e2d41. In your sandbox, search for anyVpcServiceControlAuditMetadataentry; if you have none, read the sample entry in the commands tab. - From the entry, write the three facts you need for a rule: the service and method, the identity, and the violation reason.
- 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.
- Verify: your rule is narrower than "allow all services for all identities".
Incident C: reads from a database fail after a key cleanup
- Classify: a CMEK key problem (the data service cannot use the key).
- Run
gcloud kms keys versions list ...for the key. In a sandbox without a key, use the sample output in the commands tab. - If the state is
DISABLED, runenable; ifDESTROY_SCHEDULED, runrestoreand thenenable. Write which state allows recovery and which does not. - Verify: you can state the recovery rule for the three states: disabled, scheduled for destruction, destroyed.
Bonus: reduce a noisy queue
- Run the grouping command from the commands tab (or use the sample output).
- For the top two categories, name the guardrail that prevents them and the folder where you would roll it out first.
- 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.
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.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Constraint constraints/... violated on deploy | An Organization Policy constraint applies to the project | gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective |
| Same error only in one project | A tag-conditional or project-level policy overrides the folder policy | gcloud org-policies list --project=PROJECT_ID; check the tags on the project |
Request is prohibited by organization's policy from a pipeline | VPC Service Controls perimeter blocks the caller or the destination | Search the audit log for the vpcServiceControlsUniqueIdentifier |
| Works from Cloud Shell, fails from CI | Cloud Shell is covered by an access level or ingress rule; the CI runner is outside | Compare the principal and the source network in the violation entry |
| Terraform plan works, apply fails on a Google API | The runner sits outside a perimeter, or it lacks an access level | Run the same API call from the runner with gcloud and read the error |
| BigQuery export or copy to another project fails | Crossing a perimeter boundary needs an egress or ingress rule | Violation entry: look for RESOURCES_NOT_IN_SAME_SERVICE_PERIMETER or similar reason |
| Data service cannot read after a key action | Key version disabled or scheduled for destruction | gcloud kms keys versions list --key=KEY --keyring=RING --location=LOCATION |
| Key is enabled but the service still fails | Service agent lost cryptoKeyEncrypterDecrypter, or key location mismatch | gcloud kms keys get-iam-policy KEY --keyring=RING --location=LOCATION |
| SCC shows thousands of findings | One root cause repeated across many projects | Group by category; fix with a guardrail on new projects, schedule clean-up of old ones |
| Muted findings come back | Mute rule filter too narrow, or the resource changed | Check the mute rule filter and its review date |
Triage order
- Capture the exact error text and the time. Do not rely on a summary.
- Classify: constraint, perimeter, IAM, key, API not enabled, quota.
- Read the effective state for that class (policy, perimeter and dry-run, key version, IAM policy).
- Read the audit log entry for the principal, method and reason.
- Apply the smallest fix, record it, and re-run the failed call.
- 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.
- YouTube search: VPC Service Controls troubleshooting
- YouTube search: Organization Policy troubleshooting
- YouTube search: Cloud KMS key version states
Official reading: Troubleshooting VPC Service Controls · Organization Policy Service overview · Cloud KMS key version states.
Command cheat sheet
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
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud org-policies list --folder=FOLDER_ID | List 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 --effective | Read 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.yaml | Apply a policy from a file (replaces the policy on that resource) | The file path; the name field in the file picks the resource and constraint | Wrong folder ID in name changes the wrong scope. Needs roles/orgpolicy.policyAdmin. Free. |
gcloud org-policies delete CONSTRAINT --folder=FOLDER_ID | Remove your policy from a resource (rollback) | --project, --folder, --organization | Inheritance applies again; a parent may still enforce the constraint. Free. |
gcloud resource-manager org-policies list --project=PROJECT_ID | Older command group for the same data | Same scopes | Prefer gcloud org-policies. Do not mix the two in scripts. |
name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess spec: rules: - denyAll: true
Constraints to remember
| Constraint | Type | What it blocks | Gotcha |
|---|---|---|---|
iam.disableServiceAccountKeyCreation | Boolean | Creation of service account key files | Existing keys keep working; find them first with Asset Inventory. |
iam.allowedPolicyMemberDomains | List | IAM members from domains that are not allowed | Values are customer IDs, not domain names. Partner access needs an exception. |
gcp.resourceLocations | List | Resources in locations that are not allowed | Use value groups such as in:eu-locations; some services are global. |
compute.vmExternalIpAccess | List | VMs with an external IP | Evaluated at create and update; existing VMs keep their IP. |
compute.requireOsLogin | Boolean | Metadata-based SSH keys | Users need roles/compute.osLogin or osAdminLogin. |
compute.skipDefaultNetworkCreation | Boolean | Auto-creation of the default network | Applies to new projects only; projects without a network need one before VMs. |
storage.uniformBucketLevelAccess | Boolean | Bucket ACLs (forces IAM-only access) | Old buckets are unaffected; legacy ACL tools stop working on new ones. |
sql.restrictPublicIp | Boolean | Cloud SQL instances with a public IP | Private services access is required for private instances. |
gcp.restrictNonCmekServices | List | Creating resources without CMEK in listed services | Applies at creation; make sure keys and grants exist first. |
VPC Service Controls and Access Context Manager
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud access-context-manager policies list --organization=ORG_ID | Find the access policy ID of the organization | --organization | An organization has one access policy (scoped policies exist for folders and projects). |
gcloud access-context-manager perimeters list --policy=POLICY_ID | List service perimeters | --policy | Output shows enforced configuration; dry-run configuration appears in describe. |
gcloud access-context-manager perimeters describe NAME --policy=POLICY_ID | Show projects, services and rules of a perimeter | --policy | Compare enforced status with dry-run spec before promoting. |
gcloud access-context-manager levels list --policy=POLICY_ID | List access levels | --policy | Access levels are conditions (IP ranges, device, identity), not permissions. |
gcloud logging read 'protoPayload.metadata.@type="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata"' --freshness=1d | Find perimeter violations | --freshness, --limit, --format=json | Search 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
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud kms keyrings create RING --location=REGION | Create a key ring | --location | Key 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=TIMESTAMP | Create a symmetric key with automatic rotation | --purpose, --rotation-period, --next-rotation-time, --protection-level | Keys cannot be deleted. Low cost per active version; Cloud HSM costs more. |
gcloud kms keys describe KEY --keyring=RING --location=REGION | Show purpose, primary version and rotation | Same resource flags | Rotation does not re-encrypt old data. |
gcloud kms keys add-iam-policy-binding KEY --keyring=RING --location=REGION --member=... --role=roles/cloudkms.cryptoKeyEncrypterDecrypter | Allow a service agent to use the key | --member, --role | The member is the service agent of the data project (by project number). Free. |
gcloud kms keys versions list --key=KEY --keyring=RING --location=REGION | Show states of key versions | Same resource flags | First check when data becomes unreadable. |
gcloud kms keys versions disable VERSION --key=KEY --keyring=RING --location=REGION | Kill switch: block use of a version | --key, --keyring, --location | Data protected by it is unreadable until you enable it again. Free. |
gcloud kms keys versions destroy VERSION ... | Schedule destruction of a version | Same | Irreversible after the scheduled time. Use restore before then. |
gcloud storage buckets update gs://BUCKET --default-encryption-key=KEY_RESOURCE | Set the CMEK default for a bucket | --default-encryption-key | Existing objects keep their current encryption until rewritten. |
Secret Manager
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud secrets create NAME --replication-policy=automatic | Create a secret (no value yet) | --replication-policy, --labels | Use 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=NAME | Read a version value | latest or a number | Pin a version in production. Each access is audited and billed. |
gcloud secrets versions list NAME | Show versions and states | --filter | Disabled versions cannot be read; destroyed versions are gone. |
gcloud secrets add-iam-policy-binding NAME --member=... --role=roles/secretmanager.secretAccessor | Allow one identity to read one secret | --member, --role | Grant on the secret, not on the project. |
gcloud secrets delete NAME --quiet | Delete a secret and all versions | --quiet | Irreversible. Applications that read it fail immediately. |
Cloud Asset Inventory and Security Command Center
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud asset search-all-resources --scope=organizations/ORG_ID --asset-types=TYPE | Find resources across a scope | --scope, --asset-types, --query, --format | Needs 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, --query | Index is near-real-time, not instant. |
gcloud asset analyze-iam-policy --organization=ORG_ID --full-resource-name=NAME --permissions=PERM | Who can access a resource | --expand-groups, --roles | Full 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.json | Snapshot of resources to Cloud Storage | --content-type, --asset-types, --output-path | Writes objects (storage cost). Use a lifecycle rule on the bucket. |
gcloud scc findings list ORG_ID --filter='state="ACTIVE"' | List active security findings | --filter, --format | SCC must be activated. Field paths differ between API versions. |
Audit and verification
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud logging read 'severity=ERROR AND protoPayload.status.message:"constraints/"' --freshness=1d | Find calls denied by Organization Policy | --freshness, --limit, --format | Entries 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 | --format | First step when a policy is "not applied": check the parent. |
gcloud services enable cloudkms.googleapis.com secretmanager.googleapis.com cloudasset.googleapis.com | Enable the APIs used in this hour | --project | Free 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
--effectivebefore 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
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.policyAdminon the lab folder,roles/cloudkms.admin,roles/storage.admin,roles/secretmanager.adminandroles/compute.instanceAdmin.v1on the project, androles/cloudasset.vieweron 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 versionandgcloud auth listfirst. - 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)
- 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".
- Write
policy-ip.yamlfor external IPs.name: folders/FOLDER_ID/policies/compute.vmExternalIpAccess spec: rules: - denyAll: true
Verify. The
nameline contains the lab folder ID. ReplaceFOLDER_IDin the file by the real number. - Write
policy-net.yamlfor 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, notdenyAll. - 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/...]. - 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.
- Negative test 1: external IP. The project must have a VPC network (existing projects usually have
default; checkgcloud 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_IDshows 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. - 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
defaultnetwork was created. Choose a globally unique suffix forPROJECT_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. - 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)
- 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)"printsENABLEDand7776000s. - 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_IDVerify.
gcloud kms keys get-iam-policy capstone-key --keyring=capstone-ring --location=$REGION --project=$PROJECT_IDlists the service agent with the role. - 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. - 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. - 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; noallUsers, no broad group.
Part 3. A posture report (about 10 minutes, free)
- 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.
- 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.
- 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
defaultnetwork. - 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)
- 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.
- Delete the bucket and the secret.
gcloud storage rm -r gs://$BUCKET gcloud secrets delete capstone-secret --project=$PROJECT_ID --quiet
- 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
- 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. - Delete the local YAML files and the report if it contains resource names that you do not want to keep.
Troubleshooting the capstone
| Symptom | Likely cause | First check |
|---|---|---|
set-policy says PERMISSION_DENIED | Missing roles/orgpolicy.policyAdmin | Folder IAM policy for your identity |
| The VM is created although the policy is set | Policy not in force yet, wrong folder, or the project has a different parent | gcloud projects describe PROJECT_ID --format="value(parent)" |
| Bucket creation fails with a KMS permission error | Service agent binding missing or in the wrong project number | gcloud kms keys get-iam-policy ... |
ALREADY_EXISTS for the key ring | Key ring names are permanent | Choose a new name such as capstone-ring-2 |
| Asset search shows nothing | API not enabled in the quota project, or index delay | Pass --billing-project; wait a few minutes |
Knowledge check
Sources and versions
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
- Organization Policy Service: introduction
- Organization policy constraints (list of predefined constraints)
- Creating and managing organization policies
- Understanding hierarchy evaluation
- gcloud org-policies reference
Assured Workloads and VPC Service Controls
- Assured Workloads overview
- VPC Service Controls overview
- Troubleshooting VPC Service Controls
- Access Context Manager overview
- gcloud access-context-manager reference
Cloud KMS and Secret Manager
- Cloud KMS documentation
- Customer-managed encryption keys (CMEK)
- Key version states
- Envelope encryption
- gcloud kms reference
- Secret Manager documentation
- gcloud secrets reference
Detection and posture
- Security Command Center documentation
- Security Health Analytics
- Cloud Asset Inventory overview
- gcloud asset reference
- gcloud scc reference
Architecture guidance and infrastructure as code
- Google Cloud enterprise foundations blueprint (security foundations)
- terraform-example-foundation on GitHub
- terraform-google-org-policy module on GitHub
Tools and versions used
| Tool | Version used in this hour | Note |
|---|---|---|
| gcloud CLI | Current release channel | Check with gcloud version; update with gcloud components update where the component manager is available. |
| Cloud Shell | Managed by Google | Comes with a recent gcloud CLI installed. |
| Terraform (for the optional policy-as-code mentions) | Terraform 1.x with the Google provider | Pin the major version in required_providers. |
| APIs | cloudkms, secretmanager, cloudasset, orgpolicy, accesscontextmanager, securitycenter | Enabled per project (or at organization level for some services). |
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.