Hour 1: Foundations: resource hierarchy, billing and identity

Organization, folders and projects; billing accounts; Cloud Identity; naming and labels; the layers of a landing zone.
Hour 1Resource ManagerBillingCloud Identity

Hour 1: Foundations, resource hierarchy, billing and identity

A landing zone is the governed starting point that every workload inherits. Before any network, policy or pipeline exists, three foundations must be in place: a resource hierarchy that decides where things live, a billing structure that decides who pays and who is warned, and an identity foundation that decides who the people are and how they are grouped. If these are wrong, every later hour has to work around them; if they are right, the rest of the landing zone is mostly configuration.

This hour is hands-on from the first module. You read the hierarchy with gcloud, create a folder and a project, link billing, create a budget, and review who holds powerful roles. Every command has an expected output, the common error it produces, and a note on cost.

The eight modules build on each other: the vocabulary and the design areas first, then the organization, folders and projects, then billing and quotas, then identity. After that you cover naming, labels and tags, the layers of the enterprise foundations blueprint, a complete lab that builds and verifies the hierarchy, and a module of production cases and troubleshooting.

The module pages are written for people who run production platforms. They explain the inheritance rules, the permanent decisions (such as the project ID), the roles that matter, and the controls that prevent the incidents most teams experience in their first year.

What you will be able to do after this hour

  • Explain what a landing zone is and map its design areas to Google Cloud services, and to the AWS and Azure equivalents you may already know.
  • Draw the organization, folder and project hierarchy, and predict which IAM bindings and Organization Policy constraints a project inherits.
  • Create folders and projects with gcloud, verify their parent, move them, and delete and restore a project.
  • Link a project to a billing account, create budget alerts, and say clearly why a budget does not cap spend.
  • Read project quotas and recognise a quota error from a permission error.
  • Describe how Cloud Identity or Google Workspace creates the organization, design a small set of administrator groups, and protect super admin and break-glass accounts.
  • Choose project IDs, names, labels and tags with a convention that survives reorganizations.
  • Build and verify a hierarchy in a sandbox and troubleshoot the five most common foundation problems.

Schedule (60 minutes)

#ModuleMinutes
1What a landing zone is6
2Organization, folders and projects7
3Billing accounts, budgets and quotas7
4Identity foundation8
5Naming, labels and tags7
6Landing-zone layers and the enterprise foundations blueprint8
7Lab: build and verify the hierarchy10
8Production cases and troubleshooting7
Total60

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

What you need

  • A Google Cloud identity. A sandbox organization is best, because folders, organization policies and organization-level roles need one. If you have none, the setup page explains what you can still do.
  • The Google Cloud CLI (gcloud) or Cloud Shell in a browser. Nothing else needs to be installed for this hour.
  • A billing account for the billing module, and permission to link projects to it and to create budgets. Without one, run the read steps only.
  • Basic command-line skills and a text editor.

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

Cost. The labs in this hour create folders, projects, billing links, budgets and groups. These are metadata operations and are free. A lab creates billable resources only where its text says so, and each such step names the cost class and the cleanup. Set a budget before you run any lab that enables billable services. Budgets send alerts; they do not cap spending, so always clean up at the end of each lab.
Safety. Use a sandbox organization or a personal project. Do not run labs in a production organization, and do not change organization-wide IAM or policy there. Use placeholders such as PROJECT_ID and ORG_ID in the commands and replace them with your own values; the IDs in the expected output are illustrative.

Setup

Foundations: resource hierarchy, billing and identity
Hour 1

Environment for Hour 1

This hour needs an identity that can read, and ideally create, parts of the resource hierarchy, a way to run gcloud, and a billing account with a budget in place before any lab that could cost money. The steps below are ordered so that you can stop at the point your environment allows.

1. Choose your environment

OptionWhat worksWhat does not
Sandbox organization (recommended): a Cloud Identity Free domain you own, or a training organizationEverything in the hour: folders, IAM on folders, groups, billing links, budgetsNothing is missing. You must be the administrator, or have admin help.
Company organization with a sandbox folder and delegated rolesFolders below your sandbox folder, projects, labels, billing link if allowedOrganization-level steps (reading organization IAM) may be read-only or denied
No organization (personal Google account, project at root)Projects, labels, billing link, budgets, quotas, gcloud basicsFolders, organization policies, organization IAM, organization log sinks, gcloud organizations and group commands
What to do without an organization. Run the read steps, use one personal project for the commands that accept PROJECT_ID, and treat the folder and organization steps as reading exercises. You can create a free Cloud Identity account with a domain you own to get an organization for the later hours; do this in a separate account from your company one.

2. 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, git, jq and dig, and a persistent home directory. Cloud Shell sessions are free to use, but any resource you create from it is billed to its project.

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

gcloud init
gcloud auth login

Use the account that holds your lab roles. Keep a separate gcloud configuration for the lab so that you cannot affect another environment by mistake:

gcloud config configurations create lz-lab
gcloud config set account YOUR_EMAIL
gcloud config configurations list

3. Check commands

Run these and compare with the expected result.

gcloud --version
gcloud auth list
gcloud config list
gcloud organizations list
Google Cloud SDK 5xx.x.x
bq 2.x.x
core 20xx.xx.xx
gcloud-crc32c x.x.x
gsutil 5.xx

      Credentialed Accounts
ACTIVE  ACCOUNT
*       you@example.com

[core]
account = you@example.com
disable_usage_reporting = True

DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Version numbers in the output are placeholders. Any current gcloud release works. If the version is old, run gcloud components update (local install) or open a new Cloud Shell session.

  • Empty organization list. You are not in an organization, or you lack permission to see it. Use the "no organization" path above.
  • No active account. Run gcloud auth login (local) or sign in again to Cloud Shell.
  • Wrong project. Set a lab project with gcloud config set project PROJECT_ID after you create it in Module 2. Prefer the --project flag in commands.

4. Roles you need

ForRoleScope
Reading the hierarchyroles/browserOrganization or lab folder
Creating foldersroles/resourcemanager.folderAdmin (or folderCreator)Lab folder or organization
Creating projectsroles/resourcemanager.projectCreatorLab folder or organization
Linking billingroles/billing.user on the billing account, and roles/owner or roles/billing.projectManager on the projectBilling account and project
Creating budgetsroles/billing.costsManager or roles/billing.adminBilling account
Creating groupsGroups admin role in the Admin console (or ask your identity admin)Identity account

In a company environment, ask your platform team for these on a sandbox folder only. Do not ask for organization-level roles for a course.

5. Set a budget before the labs

Module 3 creates a budget with the command line. If you have a billing account and the roles above, create the budget first, in the console under Billing, Budgets & alerts, with a small amount in your billing currency and alerts at 50, 90 and 100 percent. Add your email as a recipient. Remember that a budget alerts and does not stop spending, and that billing data can lag by hours.

Enable the Budget API on the project you use for budget calls:

gcloud services enable billingbudgets.googleapis.com --project=PROJECT_ID

6. Prepare variables

Keep the IDs you collect in one shell file (not in the commands you copy). Use placeholders, then replace them.

export ORG_ID=123456789012
export BILLING_ACCOUNT_ID=0X0X0X-0X0X0X-0X0X0X
export SUFFIX=$(date +%s | tail -c 5)
echo "$ORG_ID $BILLING_ACCOUNT_ID $SUFFIX"

Replace the example values with yours. IDs in the expected outputs of the modules are illustrative.

7. Cleanup habit

  • Use one prefix for everything you create, such as lz-lab or prj-lz-lab-.
  • At the end of every lab run the cleanup block, then check with gcloud projects list --filter="labels.env=lab".
  • Deleted projects stay restorable for about 30 days, so a mistake is recoverable; use gcloud projects undelete PROJECT_ID.
  • Never run a delete command for a resource that does not carry your prefix.
Security. Do not paste service account keys, passwords or tokens into commands or chat. Use your own user identity for these labs. In later hours you will use impersonation and Workload Identity Federation instead of keys.

Module 1 · What a landing zone is

00–06 · Design areas, the Google Cloud resource model, and how it maps to AWS and Azure
Landing zoneDesign areasResource model6 min
Learning objectives
  • Define a landing zone as the pre-built, governed foundation that every workload lands on, and list its design areas.
  • Map the Google Cloud resource hierarchy (organization, folders, projects) to the AWS and Azure equivalents you already know.
  • Explain why guardrails and automation are part of the landing zone, not an afterthought.

The short answer

A landing zone (着陆区) is the set of decisions and automation that every new workload inherits: who can do what, where resources may live, how networks connect, what is logged, and how cost is tracked. Application teams then deploy into an environment that is already safe, instead of rebuilding these controls for each project.

The design areas

Design areaQuestion it answersTypical Google Cloud building blocks
IdentityWho are the people and workloads, and what may they do?Cloud Identity or Google Workspace, groups, IAM, service accounts
Resource hierarchyWhere do resources live, and which policies apply to them?Organization, folders, projects, labels
NetworkHow do workloads reach each other, on-premises and the internet?Shared VPC, Cloud NAT, Cloud DNS, HA VPN, Cloud Interconnect
SecurityWhich limits are enforced automatically?Organization Policy, VPC Service Controls, Cloud KMS, Security Command Center
Logging and monitoringCan we prove what happened, and are we alerted?Cloud Audit Logs, log sinks, log buckets, Cloud Monitoring
CostWho pays for what, and are we warned early?Billing accounts, budgets, labels, billing export to BigQuery
AutomationHow is all of this created and changed safely?Terraform, Cloud Build or GitHub Actions, Workload Identity Federation

What: the Google Cloud resource model

  • Organization (组织): the root. It exists only when the domain is verified with Google Workspace or Cloud Identity. Without it you can still create projects, but you cannot use folders, organization policies or organization-level log sinks.
  • Folder (文件夹): a grouping level, up to 10 levels deep in the hierarchy. Folders are how you model business units, environments (prod, nonprod) and the platform itself.
  • Project (项目): the boundary for resources, APIs, quotas and billing. Every resource belongs to exactly one project.
  • Billing account (结算账号): paid by an invoice or a card. A project can be linked to one billing account, and one billing account can pay for many projects.

Why: the same idea, three vocabularies

ConceptGoogle CloudAWSAzure
Root of the hierarchyOrganizationOrganization (management account)Tenant and root management group
Grouping levelFolderOrganizational unit (OU)Management group
Unit of resources and billingProjectAccountSubscription
Policy guardrailOrganization PolicyService control policy (SCP)Azure Policy
Permission modelIAM allow policies, deny policiesIAM policies, permission boundariesAzure RBAC
Common misunderstanding. A folder is not a billing unit, and billing is not a security boundary. Billing accounts pay for projects; access and policy are decided in the hierarchy and in IAM.

When to use a landing zone pattern

Use it whenever more than one team or more than one environment will share an organization. A single small project for a proof of concept does not need folders or organization policies, but the moment a second project appears, the cost of retrofitting the same controls grows quickly.

Mental model: inheritance

Policies and IAM bindings flow down the hierarchy. A rule set on the organization applies to every folder and project below it. A rule set on a folder applies to every project in that folder. A project can add restrictions but cannot remove an inherited Organization Policy that is enforced at a higher level.

Organization example.com · org policies · org log sink Folder: platform shared network · logging · KMS Folder: production strict policies · budgets prj-net-hub prj-logging prj-app-a prj-app-b Billing account (结算账号) pays for the projects above · labels and budgets are set per project Policies flow down: a rule on the organization or a folder applies to every project below it.

Figure 1. The hierarchy in one picture. Policies and IAM bindings are inherited downwards; billing is attached to projects, not to folders.

Identity: Cloud Identity · groups · IAM · service accounts Resource hierarchy: organization · folders · projects · labels Network: Shared VPC · Cloud NAT · Cloud DNS · HA VPN · Interconnect Security: Organization Policy · VPC Service Controls · KMS · SCC Logging, cost and automation: audit logs · sinks · budgets · Terraform

Figure 2. The landing zone as layers. Each layer is a design decision that must be made once and then enforced automatically.

The animation follows one change from Terraform to the moment a new project is governed. Each step is a real interaction: an API call, a policy inheritance, or a billing link.

Read-only commands first. Run them in Cloud Shell or any shell where the Google Cloud CLI (gcloud) is installed and authenticated.

gcloud organizations list

Purpose. Shows the organizations your identity can see. An empty result means the project is not under an organization (typical for a personal account), so folder and organization-policy labs will not be possible.

gcloud organizations list
DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Common errors. Listed 0 items. means you are not in an organization or you lack resourcemanager.organizations.get. In production, use a dedicated admin identity rather than a personal account.

gcloud resource-manager folders list

Purpose. Lists folders directly under the organization, so you can confirm the structure before creating projects.

gcloud resource-manager folders list --organization=123456789012
DISPLAY_NAME  PARENT                  ID
platform      organizations/123456789012  987654321098

gcloud projects list --filter

Purpose. Shows projects under a given folder. Filtering on parent.id is the quickest way to check whether a folder is empty before you move or delete it.

gcloud projects list --filter="parent.id=987654321098 AND parent.type=folder" --format="table(projectId,name,lifecycleState)"

gcloud billing accounts list

Purpose. Lists the billing accounts your identity can link to projects. The OPEN column tells you whether the account can accept new spend.

gcloud billing accounts list
ACCOUNT_ID            NAME              OPEN  MASTER_BILLING_ACCOUNT
0X0X0X-0X0X0X-0X0X0X  Platform billing  True

gcloud resource-manager folders create (write, lab only)

Purpose. Creates a folder under the organization. It is a metadata change and costs nothing, which makes it a safe first write in a lab. The command prints an operation ID; the folder ID appears in folders list a few seconds later.

gcloud resource-manager folders create --display-name="lz-lab" --organization=123456789012
Create in progress for folder [folders/555555555555].
Production use. Organization, folder and billing account IDs are the inputs to every later module. Keep them in Terraform variables or a configuration file, never in a script that people copy by hand.

Lab 1: read the hierarchy and find the gaps (about 15 minutes, no cost)

Goal. Confirm the organization, folders, billing accounts and projects you can see, and write down what is missing before the landing zone is built.

Prerequisites. A Google Cloud identity with roles/browser (or resourcemanager.organizations.get and resourcemanager.folders.list) on the organization. If you do not have an organization, complete the note in step 5 and use a personal project instead.

  1. Open Cloud Shell (or a local terminal with gcloud init completed) and set your identity: gcloud auth list.
  2. List organizations: gcloud organizations list. Record the numeric ID.
  3. List folders and projects using the commands from the previous tab. Record the number of folders and projects.
  4. List billing accounts and record which ones are OPEN.
  5. If you have no organization, run gcloud projects list and note that folders, organization policies and organization log sinks are not available in this environment.

Expected result. A short written inventory: organization ID (or "none"), folder count, project count, open billing accounts, and a list of gaps (for example: no folder for production, billing not separated by environment).

Verification. Run gcloud projects describe PROJECT_ID --format="value(parent)". The output must show organizations/... or folders/..., which confirms where the project sits.

organizations/123456789012

Cost. None. These are read-only calls.

Cleanup. None. If you created the lab folder in the command tab, delete it: gcloud resource-manager folders delete FOLDER_ID (a folder must be empty first).

Lab 2 (optional): compare two environments

Repeat Lab 1 in a second environment (for example, a second organization or a sandbox project) and compare the two inventories. The differences are the first list of design decisions for your landing zone.

Real cases

  • Acquisition with an unmanaged domain. A subsidiary had hundreds of projects owned by personal Gmail accounts. Verifying the domain under Cloud Identity and moving projects into an organization gave one place to set policy, but it required an inventory of owners first.
  • Production and development in one folder. Engineers could see production data because the policy was set on each project, not on a folder. Moving the production projects into their own folder with an inherited constraint closed the gap in one change.
  • Billing without structure. A single billing account paid for everything, so a runaway test in one team triggered an invoice alarm for the whole company. Separate billing accounts per business unit (or at least budgets and labels per project) fixed the blast radius.

Practices

  • Use a verified domain and a Cloud Identity or Google Workspace group for every administrative role. Do not grant roles to individual personal accounts.
  • Keep the organization root nearly empty: grant organization-level roles only to the platform team, and put workloads under folders.
  • Name folders for their purpose (platform, prod, nonprod, sandbox), not for people.
  • Document each design area in one page, and keep the page next to the Terraform code that implements it.
Security note. Anyone with Organization Administrator (roles/resourcemanager.organizationAdmin) can change policies for the whole company. Keep this role for a small, reviewed group and use break-glass accounts with strong authentication for emergencies.

Symptoms and first checks

SymptomLikely causeFirst check
Listed 0 items for organizationsNo organization, or missing permissiongcloud auth list; check the domain in the admin console
PERMISSION_DENIED when creating a folderMissing resourcemanager.folders.creategcloud organizations get-iam-policy ORG_ID (filter to your identity)
Folder created but not visiblePropagation delayWait a minute, then run folders list again
Project not under the folder you expectedCreated with no --folder flaggcloud projects describe PROJECT_ID --format="value(parent)"

Triage order

  1. Confirm the identity: gcloud config list account.
  2. Confirm the scope: organization, folder or project.
  3. Read the effective policy before you change anything: gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effective.
  4. Check the audit log for the denied call (Module 6 covers this in detail).

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: Resource hierarchy · Security foundations guide.

or score ≥ 70% on the quiz

Module 2 · Organization, folders and projects

06–13 · Hierarchy, inheritance, resource IDs and the first gcloud commands that read and build it
OrganizationFoldersProjectsInheritance7 min
Learning objectives
  • Draw the hierarchy (organization, folders, projects) and predict which policy or IAM binding a project inherits.
  • Distinguish project name, project ID and project number, and explain which of them can change.
  • Create a folder and a project with gcloud, verify where the project sits, and move or delete it safely.

The short answer

The organization (组织), folders (文件夹) and projects (项目) form a tree stored by the Resource Manager service. Everything you create, from a virtual machine to a bucket, sits inside exactly one project, and each project has exactly one parent, either a folder or the organization. IAM bindings and Organization Policy constraints are evaluated along the path from the resource up to the organization, so the tree is the main tool for governing many teams with few rules.

What each level is

LevelWhat it holdsWho normally manages itNotes
OrganizationFolders, projects, organization-wide policies, log sinks, tagsPlatform team (small group)Created when a domain is verified in Cloud Identity or Google Workspace. One per domain; there is no parent above it.
FolderProjects and other foldersPlatform team creates; business units can get roles/resourcemanager.folderAdmin on their own folderNeeds an organization. Folder names are not globally unique, but must be unique among siblings.
ProjectResources, enabled APIs, quotas, service accounts, IAM allow policy, billing linkApplication team, within guardrailsThe unit of isolation, quota and billing association.

Three identifiers, three behaviours

IdentifierExampleWho chooses itCan it change?Where it appears
Project nameShop productionYouYes, any timeConsole, billing reports
Project IDprj-shop-prod-7k2You (or generated)No, and never reusable after deletiongcloud flags, API paths, Terraform, resource names
Project number301234567890Google CloudNoService agents such as service-301234567890@..., IAM conditions, some APIs

Project ID rules: 6 to 30 characters, lowercase letters, digits and hyphens, starting with a letter and not ending with a hyphen. Module 5 covers naming conventions in detail; here the point is that the ID is a permanent decision.

Why: the hierarchy exists to be inherited

Without a hierarchy, every rule would have to be applied to every project. With it, the platform team writes the rule once at the organization or a folder, and each project below is governed from the moment it is created. This works for two systems:

  • IAM allow policies are additive down the tree. A role granted on a folder is effective in every project below. A child cannot remove a role that was granted above it (a deny policy is the separate mechanism for that; Hour 2).
  • Organization Policy constraints are evaluated down the tree. A child may inherit the parent policy, merge with it, or (for boolean and list constraints, where the parent allows it) override it. Hour 3 covers the exact rules.

How it works internally

  1. Each resource carries a name such as projects/prj-shop-prod-7k2 or folders/555555555555. Resource Manager stores the parent link for every node.
  2. When a request arrives (for example, "create a VM in this project"), IAM and Org Policy ask Resource Manager for the ancestry: project, then each folder upward, then the organization.
  3. IAM takes the union of the allow policies along that path and checks the permission; Organization Policy resolves the constraint along the same path.
  4. Because the ancestry is looked up at request time, moving a project to a new parent immediately changes the effective policy. Propagation of IAM changes can take a few minutes.

When to use folders

  • When two groups of projects need different policy (production versus sandbox) or different administrators (a business unit that manages its own projects).
  • When you want a place for platform-owned shared projects (network host project, logging project, secrets) that application teams must not edit.
  • Not for every team or every application. A flat folder with fifty projects is fine if they share the same rules.

What it is confused with

Often confusedWhy it differs
Folder and labelA folder is a node in the tree that carries policy and IAM. A label is key-value metadata on a resource, used for cost allocation and filtering. Labels never change access.
Folder and tag (Resource Manager tag)A tag is a governed key-value that can be bound to a resource and used in IAM conditions and Organization Policy. It complements folders when the boundary does not follow the tree (Module 5).
Project and VPC networkA project is a container of many resources. A VPC network is one resource in it, though Shared VPC lets projects share a network (Hour 4).
Organization and billing accountThe organization is the root of governance. A billing account pays the invoice and is linked to projects. A project can sit in organization A and be billed by a billing account that belongs to organization B.
Project and AWS account or Azure subscriptionClose in spirit (isolation and billing unit), but a project has no separate root user and is created by API in seconds. Quotas are per project.

Common misunderstandings

"Owner on the project is the most powerful role." Owner is powerful in one project, but a role at the organization or folder level reaches many projects. The most dangerous roles are the ones granted high in the tree.
"I can fix a bad project ID later." You cannot. If the ID is wrong you create a new project, migrate resources and delete the old one. Decide the naming convention before the first project.
"No organization is fine for production." Projects with no organization have no folders, no organization policies, no organization log sinks and no central IAM. They are suitable for a personal sandbox only.

Roles you will meet

RoleGrantsGive it to
roles/resourcemanager.organizationAdminManage organization IAM and policiesPlatform admins group (very few people)
roles/resourcemanager.folderAdminCreate, move and delete folders; set folder IAMPlatform team, or a business unit for its own folder
roles/resourcemanager.projectCreatorCreate projects under the resource where it is grantedThe project-factory service account (Hour 7)
roles/resourcemanager.projectDeleterDelete projectsRarely; keep in the platform team
roles/browserRead the hierarchy (list and get)Auditors and the learners in this course
Secure by default. In older organizations every user in the domain can receive Project Creator and Billing Account Creator at the organization level by default. Newer organizations are created with safer defaults, but you should still check the organization IAM policy and remove broad grants so that projects are created only through your factory or approved groups.
organizations/123456789012 IAM: gcp-organization-admins · Org Policy: baseline folders/111 platform IAM: platform team folders/222 production Org Policy: strict · budgets folders/333 sandbox Org Policy: relaxed · small quotas prj-shop-prod prj-erp-prod prj-net-hub prj-sbx-anna Effective policy of prj-shop-prod = organization + folders/222 + project itself (IAM is a union of all three). Move the project to folders/333 and the effective policy becomes organization + folders/333 + project. Every project has exactly one parent. A folder or an organization can have many children. Names shown are examples; IDs in real life are numeric for folders and organizations.

Figure 1. Inheritance along the ancestry path. The three policy layers apply from the top down, and a project's effective policy changes the moment its parent changes.

Look at the dashed box: the effective policy is computed from the path, not copied into the project. That is why a single change to a folder is enough to govern all its projects, and why moving a project is a security change, not a tidy-up.

Project name Shop production mutable · not unique Project ID prj-shop-prod-7k2 immutable · globally unique Project number 301234567890 immutable · assigned by Google Console, reports for humans gcloud, Terraform, APIs for automation Service agents, IAM for the platform

Figure 2. Which identifier is used where. Scripts and Terraform use the project ID; service agents are named after the project number.

The animation creates a folder, creates a project inside it, and then shows how Organization Policy and IAM resolve the project's ancestry. Watch the fifth and sixth steps: nothing is copied into the new project; the policies are looked up from its parents on every request.

All commands run in Cloud Shell or a shell with the gcloud CLI (current release channel) signed in. Placeholders are uppercase. Read commands are free. Creating a folder or a project is a metadata operation and is free; resources you later place in the project are what cost money.

gcloud organizations list and gcloud organizations describe

Purpose. Finds the numeric organization ID that every later command needs.

gcloud organizations list
gcloud organizations describe ORG_ID

Flags. ORG_ID is the numeric ID, not the domain name. --format can narrow the output.

DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Common errors. Listed 0 items. means no organization is visible to your identity. Production use. Store the ID as a Terraform variable; never type it into scripts by hand.

gcloud resource-manager folders create (write, free)

Purpose. Creates a folder under the organization or another folder.

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

Flags. --display-name is the folder name (unique among siblings). Use --organization=ORG_ID for a top-level folder or --folder=FOLDER_ID for a nested one. Check gcloud resource-manager folders create --help for the flags in your SDK version.

Waiting for operation [operations/cf.7312345678901234567] to complete...done.
Created folder [lz-lab].
createTime: '2026-11-25T09:14:03.211Z'
displayName: lz-lab
lifecycleState: ACTIVE
name: folders/555555555555
parent: organizations/123456789012

Common errors. PERMISSION_DENIED: ... resourcemanager.folders.create means you lack roles/resourcemanager.folderCreator or folderAdmin on the parent. A duplicate display name under the same parent is rejected. Production use. Folders are created by Terraform in the organization layer, so the structure is reviewed in a pull request.

gcloud resource-manager folders list and describe

Purpose. Lists the children of an organization or folder, and shows one folder.

gcloud resource-manager folders list --organization=ORG_ID
gcloud resource-manager folders list --folder=FOLDER_ID
gcloud resource-manager folders describe FOLDER_ID
DISPLAY_NAME  PARENT_NAME                 ID
platform      organizations/123456789012  111111111111
production    organizations/123456789012  222222222222
lz-lab        organizations/123456789012  555555555555

Flags. Listing is one level only. To see everything, use Cloud Asset Inventory (Hour 6). Common errors. An empty list under a folder means it has no sub-folders; use gcloud projects list for projects.

gcloud projects create (write, free)

Purpose. Creates a project under a folder or the organization.

gcloud projects create PROJECT_ID \
  --name="Landing zone lab" \
  --folder=FOLDER_ID \
  --labels=env=lab,owner=platform

Flags. PROJECT_ID must follow the ID rules. --folder or --organization chooses the parent; without either and with an organization present, the project is created at the organization root, which is rarely what you want. --labels sets labels at creation (Module 5). --set-as-default would switch your gcloud configuration to the new project; omit it in scripts.

Create in progress for [https://cloudresourcemanager.googleapis.com/v1/projects/prj-lz-lab-7k2].
Waiting for [operations/pc.1234567890123456789] to complete...done.
Enabling service [cloudapis.googleapis.com] on project [prj-lz-lab-7k2]...
Operation "operations/acat.p2-301234567890-abcd" finished successfully.

IDs in the expected output are illustrative.

Common errors. The project ID you specified is already in use by another project means the ID is taken (IDs are global and are not reusable after deletion). PERMISSION_DENIED means you lack resourcemanager.projects.create on the parent. An Organization Policy or an organization setting can also restrict who may create projects. Production use. A project factory (Hour 7) creates every project, and humans lose the right to create them by hand.

gcloud projects describe and get-ancestors

Purpose. Confirms the parent and the full path to the organization. This is the first command to run when a policy behaves unexpectedly.

gcloud projects describe PROJECT_ID
gcloud projects describe PROJECT_ID --format="value(parent.type,parent.id)"
gcloud projects get-ancestors PROJECT_ID
createTime: '2026-11-25T09:20:41.003Z'
labels:
  env: lab
  owner: platform
lifecycleState: ACTIVE
name: Landing zone lab
parent:
  id: '555555555555'
  type: folder
projectId: prj-lz-lab-7k2
projectNumber: '301234567890'

ID              TYPE
prj-lz-lab-7k2  project
555555555555    folder
123456789012    organization

Flags. --format="value(...)" prints bare values for scripts. Common errors. lifecycleState: DELETE_REQUESTED means the project is pending deletion.

gcloud projects list with a filter

Purpose. Finds projects by parent, label or name.

gcloud projects list \
  --filter="parent.id=FOLDER_ID AND parent.type=folder" \
  --format="table(projectId,name,projectNumber,lifecycleState)"
gcloud projects list --filter="labels.env=lab"

Flags. Filters use the field paths shown by describe. Quote the whole expression. Production use. Run this before moving or deleting a folder so you know what it contains.

gcloud projects move and gcloud resource-manager folders move (write, free)

Purpose. Re-parents a project or a folder. This changes the policy and IAM it inherits.

gcloud projects move PROJECT_ID --folder=NEW_FOLDER_ID
gcloud resource-manager folders move FOLDER_ID --folder=NEW_PARENT_FOLDER_ID

Common errors. You need move permission on the project and create permission on the destination. Review the destination's effective policy first. Production use. Treat a move like a change request: record the old and new parent, run the comparison, then move.

gcloud projects delete and undelete (write, free)

Purpose. Schedules a project for deletion and restores it within the recovery window.

gcloud projects delete PROJECT_ID
gcloud projects undelete PROJECT_ID
Your project will be deleted on [2026-12-25T09:30:00.000Z]. You can undelete it until then.
Deleted [https://cloudresourcemanager.googleapis.com/v1/projects/prj-lz-lab-7k2].

Common errors. A lien on the project blocks deletion: list it with gcloud alpha resource-manager liens list --project=PROJECT_ID (alpha command; check --help) or in the console. Resources stop serving when deletion starts, and billing for them ends. Production use. Deletion goes through the factory with a lien or deletion protection on production projects.

Production use. Use --format=json and jq to feed hierarchy data into reports, and keep the numeric IDs in Terraform variables. Never paste IDs from a screenshot into automation.

Lab 2: build a folder and a project, then verify and move them (about 20 minutes)

Goal. Create a lab folder and two projects, read the ancestry, move one project to a second folder, and delete everything.

Prerequisites. A sandbox organization or a folder where you hold roles/resourcemanager.folderAdmin and roles/resourcemanager.projectCreator. Without an organization, only steps 4 and 6 apply (projects at root; folders are not available). A billing account is not needed for this lab, because no billable resource is created.

Cost. Free. Folder and project creation are metadata operations. Do not enable billable APIs in these projects. IDs in the expected output are illustrative.

  1. Set variables. Use a unique suffix because project IDs are global.
    ORG_ID=123456789012
    SUFFIX=$(date +%s | tail -c 5)
    echo "$SUFFIX"
  2. Create two folders.
    gcloud resource-manager folders create --display-name="lz-lab-a" --organization=$ORG_ID
    gcloud resource-manager folders create --display-name="lz-lab-b" --organization=$ORG_ID
    gcloud resource-manager folders list --organization=$ORG_ID --filter="displayName:lz-lab"
    Record both folder IDs as FOLDER_A and FOLDER_B.
  3. Verify. The list shows both folders with parent organizations/123456789012.
  4. Create a project in folder A.
    gcloud projects create prj-lz-lab-$SUFFIX --name="LZ lab" --folder=$FOLDER_A --labels=env=lab,owner=platform
  5. Verify placement.
    gcloud projects describe prj-lz-lab-$SUFFIX --format="value(parent.type,parent.id)"
    gcloud projects get-ancestors prj-lz-lab-$SUFFIX
    folder	555555555555
    ID                  TYPE
    prj-lz-lab-4821     project
    555555555555        folder
    123456789012        organization
  6. Read the effective policy. This shows an inherited constraint without changing anything. If you have no policy set, the effective value is the default.
    gcloud org-policies describe constraints/compute.skipDefaultNetworkCreation --project=prj-lz-lab-$SUFFIX --effective
    Check gcloud org-policies describe --help for the flags in your SDK version.
  7. Move the project to folder B and verify again.
    gcloud projects move prj-lz-lab-$SUFFIX --folder=$FOLDER_B
    gcloud projects get-ancestors prj-lz-lab-$SUFFIX
    The ancestry now lists folder B.
  8. Try the failure paths. Create a project with the same ID (expect "already in use") and with an ID that is too short such as abc (expect an ID format error). Record the messages.

Expected result. Two folders, one project that moved from A to B, and the ancestry output proving the move.

Cleanup. Delete in this order, because a folder must be empty:

gcloud projects delete prj-lz-lab-$SUFFIX --quiet
gcloud resource-manager folders delete $FOLDER_A
gcloud resource-manager folders delete $FOLDER_B

A deleted project stays restorable for about 30 days; the folder delete succeeds once the project is in the pending-deletion state, or may need a wait of a short time. If it fails with "folder is not empty", run gcloud projects list --filter="parent.id=FOLDER_B".

Safety. Use only IDs that start with your lab prefix. Never run projects delete on a project you did not create in this lab.

Real cases

  • One folder per team, thirty folders, one policy. A company mirrored its org chart, then reorganized twice in a year. Each reorganization needed folder moves and IAM re-checks. The fix was a stable four-folder skeleton (platform, production, non-production, sandbox) with team identity in labels and project names, so reorganizations touched labels only.
  • Hundreds of "temporary" projects. A sandbox folder allowed anyone to create projects, and none were deleted. The platform team added a sandbox folder with a small default quota, mandatory owner and expiry labels, and a weekly job that lists projects past expiry and deletes them after notice.
  • A production project moved in by accident. An engineer tidied the console and dragged a production project into a folder with relaxed constraints. External IP creation became possible. A custom role with resourcemanager.projects.move now sits only with the platform group, and an audit-log alert fires on MoveProject events.

Practices

  • Keep the tree shallow: organization, a few environment folders, projects. Add nesting only for a real policy or ownership boundary.
  • Create the hierarchy with Terraform and review changes in pull requests. Every folder should exist for a documented reason.
  • Put shared platform projects (network host, logging, KMS, secrets, CI) under a platform folder that only the platform team can edit.
  • Remove broad default grants on the organization (project creator for all users) and give projectCreator to the factory service account on specific folders.
  • Turn on deletion protection for production: liens block deletion, and Terraform's deletion_policy on projects prevents accidental destroy.
  • Choose project IDs once, with a convention (Module 5). Keep a mapping of ID, number, owner, environment and cost centre in a register.
Security note. Granting roles/owner or roles/editor at the organization or a folder gives that access in every project below, including projects created tomorrow. Use predefined roles on the smallest scope, and keep basic roles out of the hierarchy root.
Moving projects is not neutral. A project moved from production to sandbox loses the production constraints immediately. Always compare the effective policy of the old and new parents before moving.

Symptoms and first checks

SymptomLikely causeFirst check
The project ID you specified is already in useThe ID is taken globally, or belongs to a deleted project that is still reservedChoose a new ID with a random suffix; run gcloud projects list --filter="projectId=ID"
PERMISSION_DENIED on projects createNo projectCreator on the parent folder or organizationgcloud resource-manager folders get-iam-policy FOLDER_ID (or organizations get-iam-policy ORG_ID)
Project created at the organization rootNo --folder or --organization flag was used, or the default parent was the organizationgcloud projects describe PROJECT_ID --format="value(parent)", then projects move
Folder delete fails: not emptyIt still contains projects or folders, including projects pending deletiongcloud projects list --filter="parent.id=FOLDER_ID" and folders list --folder=FOLDER_ID
Project delete failsA lien protects the project, or you lack resourcemanager.projects.deleteList liens in the console or with the alpha liens command; remove the lien only after approval
A new project already has policies you did not setInherited from the folder or organizationgcloud org-policies list --project=PROJECT_ID and describe ... --effective
Cannot see folders at allProject is not under an organization, or missing roles/browsergcloud organizations list; check the account in gcloud auth list
Project moved but access did not changeIAM propagation delay (usually minutes) or a cached tokenWait a few minutes and retry; check ancestry with get-ancestors

Triage order

  1. Confirm the identity: gcloud config list account.
  2. Confirm the project and its ancestry: gcloud projects get-ancestors PROJECT_ID.
  3. Check the lifecycle state: ACTIVE versus DELETE_REQUESTED.
  4. Read IAM on each ancestor and the effective policy for any constraint involved.
  5. Read the audit log for the denied call (Hour 6 covers the filters).

Video search links are shown instead of pinned videos because titles and recommendations change. Prefer videos newer than the documentation version you use.

Official reading: Resource hierarchy · Creating and managing folders · Creating and managing projects · Access control inheritance.

or score ≥ 70% on the quiz

Module 3 · Billing accounts, budgets and quotas

13–20 · Linking projects to billing, budget alerts that do not cap spend, and quota basics
Billing accountBudgetsQuotas7 min
Learning objectives
  • Explain how a billing account, a project and its billing link relate, and which roles control each part.
  • Create a budget with threshold alerts, and state clearly that a budget notifies but does not stop spending.
  • Read project quotas and request an increase before a deployment fails.

The short answer

A billing account (结算账号) pays for the projects linked to it. It is a separate object from the resource hierarchy: it has its own IAM policy, its own payment profile, and its own roles. A project is linked to one billing account at a time, and until it is linked, billable services in that project cannot be used. A budget (预算) watches spend on the account or on selected projects and sends alerts. A quota (配额) caps resource usage per project. Together they answer: who pays, who is warned, and what stops runaway use.

What: the pieces

ObjectWhat it isKey facts
Billing accountPayment relationship (card or invoiced terms) with a payments profileHas an ID like 0X0X0X-0X0X0X-0X0X0X; can be open or closed; has its own IAM.
Billing linkProject attribute: billing enabled and the account nameRemoving it stops billable services; free tier use may continue.
BudgetAmount plus threshold rules plus a scope (account, projects, services, labels)Alerts only; notifications by email or Pub/Sub.
QuotaPer-project limit on rates or allocationRate quotas (requests per minute) and allocation quotas (CPUs, IP addresses).
Billing exportDetailed cost data written to BigQueryNeeded for allocation by label (Hour 6).

Billing roles

RoleCan doTypical holder
roles/billing.creatorCreate billing accounts (granted on the organization)Finance platform owner, very few
roles/billing.adminManage the billing account, its IAM, payment detailsBilling admins group
roles/billing.userLink projects to the billing accountProject factory service account; platform team
roles/billing.projectManagerLink and unlink a specific projectProject owners, where needed
roles/billing.costsManagerManage budgets and cost views, not paymentFinOps team
roles/billing.viewerRead costs and reportsFinance, auditors

Linking a project needs two permissions: billing.resourceAssociations.create on the billing account (included in roles/billing.user) and resourcemanager.projects.createBillingAssignment on the project (included in roles/owner and roles/billing.projectManager). Billing admins who are not project owners cannot link by themselves.

Why billing needs design

  • Allocation. Finance asks "which team spent this?" Without projects per application, labels and export, the answer is a guess.
  • Blast radius. One billing account for the whole company means one alert threshold and one set of administrators. Separate accounts per business unit or environment can isolate invoices and limit who can change payment settings.
  • Early warning. A mistake in a lab or a misconfigured autoscaler can cost more in a day than the project budget for a month. Budgets and quotas shorten the time to notice.

How budgets work

  1. You choose a scope: the whole billing account, specific projects, services or labels.
  2. You set an amount (a fixed value or "last period's spend") and threshold rules, for example 50, 90 and 100 percent of actual spend and 100 percent of forecasted spend.
  3. Cloud Billing evaluates the cost several times a day. Data can be delayed by hours, so alerts are not instant.
  4. When a threshold is crossed, it emails the billing administrators and users (and recipients you add) and, if configured, publishes a message to a Pub/Sub topic.
  5. Nothing else happens. Resources keep running and costs keep accruing.
Budgets alert; they do not cap. If you need a hard stop, you must build it: a Pub/Sub-triggered function that disables billing on a non-production project (this stops services and may destroy data availability) or limits resources with quotas and Organization Policy. Do this only for sandboxes, never for production.

How quotas work

  • Allocation quotas limit how many resources of a kind exist, for example CPUs per region, static IP addresses, or networks per project.
  • Rate quotas limit API calls per time unit, for example Compute Engine read requests per minute.
  • New projects and new accounts start with conservative defaults. Quotas grow with usage and billing history, and you can request an increase. Some requests are approved automatically; others are reviewed.
  • A quota can also be lowered by you on supported services, which is a useful limit on a sandbox project.
  • Exceeding a quota returns an error (for example, QUOTA_EXCEEDED or Quota 'CPUS' exceeded) and nothing is created.

When to use separate billing accounts

SituationChoice
One company, one finance owner, projects per application with labelsOne billing account, budgets per project, billing export with labels
Subsidiaries invoiced separately, or different payment currenciesOne billing account per legal entity
Sandbox and training with strict spending controlA separate billing account with low budget alerts and a quota policy
Reseller or managed-service providerSub-accounts of a reseller master account (contract-dependent)

What it is confused with

Often confusedWhy it differs
Billing account and organizationThe organization governs resources; the billing account pays for them. They are separate, with separate IAM.
Budget and quotaA budget watches money and alerts. A quota limits resource use and blocks the request.
Quota and capacityA quota is your allowed ceiling. A resource may still fail if the zone has no capacity (a stockout), even when you are below quota.
Disabling billing and deleting the projectDisabling billing stops billable services and keeps the project and its data for a while. Deleting schedules removal of everything.

Common misunderstandings

"The budget will stop the spending." It will not. Read the alert, then act.
"A billing admin can create resources everywhere." Billing roles do not grant resource permissions. A billing administrator needs separate project roles to use or inspect resources.
"Costs show instantly." Billing data lags. A budget alert can arrive hours after the spend, so keep headroom between the budget and the real limit.
Billing account 0X0X0X-0X0X0X-0X0X0X · own IAM prj-shop-prod billingEnabled: true prj-erp-prod billingEnabled: true prj-sbx-anna billingEnabled: true Budget: 80% · 100% Budget: 50% · 90% Quota: 8 CPUs A project has one billing account at a time. A billing account pays for many projects. Budgets (green) alert on spend. Quotas (red) block resource creation. Neither is a security boundary. The billing account is not a node of the folder tree and does not inherit folder IAM.

Figure 1. Billing is a separate relationship from the hierarchy. Budgets watch money; quotas limit resources.

Look at the colours: green boxes send alerts, the red box blocks. When a sandbox needs a hard limit, the quota (or a policy) is the control and the budget is the notification.

100% 90% 50% 0 email 50% email 90% alert 100% spend continues days of the month

Figure 2. A budget raises alerts as spend crosses thresholds, and then the line keeps rising. Nothing in the budget stops it.

The animation links a project to a billing account, creates a budget with three thresholds, and shows the notification when spend crosses 90 percent. Notice the last step: the notification is only a message, and the next action belongs to a person or to automation you build.

Billing commands act on the billing account and the project link. Reading is free; linking and budget changes are metadata changes and cost nothing. Spend comes from resources you create, not from these commands. The Cloud Billing Budget API (billingbudgets.googleapis.com) must be enabled on the project you use for budget calls.

gcloud billing accounts list and describe

Purpose. Lists the billing accounts your identity can use and their state.

gcloud billing accounts list
gcloud billing accounts describe BILLING_ACCOUNT_ID
ACCOUNT_ID            NAME                OPEN  MASTER_ACCOUNT_ID
0X0X0X-0X0X0X-0X0X0X  Platform billing    True
0Y0Y0Y-0Y0Y0Y-0Y0Y0Y  Sandbox billing     True

Flags. --filter="open=true" hides closed accounts. Common errors. An empty list means you hold no billing role on any account (roles/billing.user or higher is the minimum to see it). IDs in the expected output are illustrative.

gcloud billing projects link (write, free)

Purpose. Links a project to a billing account, which enables billable services.

gcloud billing projects link PROJECT_ID \
  --billing-account=BILLING_ACCOUNT_ID
billingAccountName: billingAccounts/0X0X0X-0X0X0X-0X0X0X
billingEnabled: true
name: projects/prj-lz-lab-7k2/billingInfo
projectId: prj-lz-lab-7k2

Common errors. PERMISSION_DENIED: The caller does not have permission means one of the two sides is missing (see the role table). Billing account ... is closed means pick an open account. Production use. The project factory links billing at creation, so no project exists without a billing account.

gcloud billing projects describe and unlink

Purpose. Verifies that billing is enabled, or removes the link.

gcloud billing projects describe PROJECT_ID
gcloud billing projects unlink PROJECT_ID

Common errors. billingEnabled: false explains BILLING_DISABLED errors when enabling a billable API. Unlinking stops billable services in the project, so never unlink a production project without a change request. Cost: unlinking can only reduce cost.

gcloud billing accounts get-iam-policy and add-iam-policy-binding (write)

Purpose. Reads or changes who can use or administer a billing account.

gcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID
gcloud billing accounts add-iam-policy-binding BILLING_ACCOUNT_ID \
  --member="group:GROUP_EMAIL" \
  --role="roles/billing.user"

Flags. --member takes group:, user: or serviceAccount: prefixes. Use groups. Common errors. You need roles/billing.admin on the account. Production use. Keep the number of billing admins small and use billing.user for the factory.

gcloud billing budgets create (write, free)

Purpose. Creates a budget on a billing account, scoped to one or more projects, with threshold alerts.

gcloud services enable billingbudgets.googleapis.com --project=PROJECT_ID

gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="lz-lab-budget" \
  --budget-amount=20USD \
  --filter-projects=projects/PROJECT_ID \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0

Flags. --budget-amount is an amount with currency code. Use a value that matches your billing currency; the 20 USD above is a lab example, not a recommendation. --threshold-rule=percent=0.5 is a fraction of the amount, and the basis=forecasted-spend option adds a forecast-based rule. --filter-projects scopes the budget to projects. Check gcloud billing budgets create --help for the flags in your SDK version.

Created budget [billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/a1b2c3d4-0000-0000-0000-000000000000].

Common errors. API [billingbudgets.googleapis.com] not enabled means enable the API on the quota project. PERMISSION_DENIED means you need roles/billing.costsManager or billing.admin on the account. A mismatched currency also fails. Production use. Budgets live in Terraform with a Pub/Sub topic for notifications.

gcloud billing budgets list and describe

Purpose. Reviews existing budgets.

gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID
gcloud billing budgets describe BUDGET_ID --billing-account=BILLING_ACCOUNT_ID
NAME                                                          DISPLAY_NAME    AMOUNT
billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/a1b2c3d4-0000    lz-lab-budget   20USD

Quota commands

Purpose. Reads current limits and usage for Compute Engine in a project and in a region. Console view: IAM & Admin, Quotas & System Limits.

gcloud compute project-info describe --project=PROJECT_ID --format="yaml(quotas)"
gcloud compute regions describe REGION --project=PROJECT_ID --format="yaml(quotas)"
gcloud services list --enabled --project=PROJECT_ID
quotas:
- limit: 24.0
  metric: CPUS
  usage: 0.0
- limit: 8.0
  metric: IN_USE_ADDRESSES
  usage: 0.0

Flags. --format="yaml(quotas)" narrows output to the quota block. For quota increases use the console or the Cloud Quotas API; the CLI group for quotas has changed between releases, so check gcloud --help for "quotas" in your SDK version. Cost: free. Common errors. Compute Engine API has not been used in project ... before means the API is not enabled yet.

Production use. Turn quota usage into a dashboard and an alert at 80 percent, and file increase requests before a scale-up, not during it.

Lab 3: link billing, create a budget, read quotas (about 20 minutes)

Goal. Link a lab project to a billing account, create a small budget with three alerts, check quotas, and clean up.

Prerequisites. A lab project (for example from Lab 2), a billing account where you hold roles/billing.user and roles/billing.costsManager (or billing.admin), and roles/owner or billing.projectManager on the project. If you have no billing account, read the steps and run only the read commands. IDs in the expected output are illustrative.

Cost. Free. Linking billing and creating a budget are metadata changes. Do not create compute resources in this lab. A budget is not a cap.

  1. List accounts and pick one.
    gcloud billing accounts list --filter="open=true"
  2. Link the project and verify.
    gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
    gcloud billing projects describe PROJECT_ID --format="value(billingEnabled,billingAccountName)"
    True	billingAccounts/0X0X0X-0X0X0X-0X0X0X
  3. Enable the Budget API on the lab project.
    gcloud services enable billingbudgets.googleapis.com --project=PROJECT_ID
  4. Create the budget with the command from the previous tab, using an amount that is appropriate for a lab in your billing currency. Add an email recipient in the console if you want to test notifications.
  5. Verify the budget.
    gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID --filter="displayName=lz-lab-budget"
    Open the budget in the console (Billing, Budgets & alerts) and confirm the three thresholds and the project filter.
  6. Read quotas.
    gcloud services enable compute.googleapis.com --project=PROJECT_ID
    gcloud compute project-info describe --project=PROJECT_ID --format="yaml(quotas)"
    Note the CPUS and IN_USE_ADDRESSES values. Enabling the Compute Engine API is free; no instance exists yet.
  7. Think about the failure. Write down what would happen if a VM request exceeded CPUS (error, nothing created) and what would happen if spend exceeded the budget (alert, resources keep running).

Expected result. Billing shows billingEnabled: True for the project, one budget with three thresholds, and a quota list.

Cleanup. Remove the budget, unlink billing, and leave the project for Lab 7 or delete it.

gcloud billing budgets delete BUDGET_ID --billing-account=BILLING_ACCOUNT_ID
gcloud billing projects unlink PROJECT_ID
gcloud projects delete PROJECT_ID --quiet
Safety. Never unlink a project you do not own. Use --filter on displayName so you delete only your lab budget.

Real cases

  • The Friday autoscaler. A test cluster with no node limit scaled during a load test and was left over a weekend. A project budget with a 90 percent alert emailed a mailing list nobody read. The platform team moved alerts to a Pub/Sub topic that creates a ticket and pages the on-call, and added node-pool maximums and quota limits on the project.
  • Everything on one card. A growing company paid every project from a single billing account owned by one person. When the card expired, billing stopped for dozens of projects. The remedy was an invoiced billing account with a finance group as admin, a second group as billing contact, and a break-glass billing admin.
  • A sandbox with a hard stop. A training programme gave learners projects under a sandbox folder with a separate billing account. A small function subscribed to the budget topic, and at 100 percent it disabled billing on the project. Because only sandbox projects used it, the loss of services was acceptable and the invoice stayed bounded.

Practices

  • Create a budget in the same Terraform that creates the project. Three thresholds (50, 90, 100 percent) plus a forecast rule are a good start; send them to Pub/Sub and a team channel, not only to an inbox.
  • Give roles/billing.user to the factory service account and to a small group. Keep billing.admin to two or three people through a group.
  • Use separate billing accounts only for a reason (legal entity, currency, sandbox control). More accounts mean more admin work.
  • Enable billing export to BigQuery (Hour 6) and apply labels (Module 5) so the invoice maps to owners.
  • Request quota increases ahead of launches, and lower quotas in sandboxes. Track CPU, GPU and IP address quotas for production regions.
  • Review billing IAM and budgets quarterly. Remove users who left, and check that every active project is linked to the right account.
Security note. Anyone who can unlink or relink billing on a production project can take it down. Restrict billing.projectManager and owner on production, and alert on UpdateProjectBillingInfo events in the admin activity audit logs.
Disabling billing as a control. It stops services and can lead to data loss for some resources. It is acceptable only on sandboxes. For production, alert and investigate.

Symptoms and first checks

SymptomLikely causeFirst check
BILLING_DISABLED when enabling an APIThe project has no billing linkgcloud billing projects describe PROJECT_ID, then link
PERMISSION_DENIED on billing projects linkMissing billing.user on the account, or no billing assignment permission on the projectgcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID and projects get-iam-policy PROJECT_ID
No billing accounts listedNo billing role, wrong identity, or accounts closedgcloud auth list; ask a billing admin to add you
Budget alert never arrivesRecipients not set, the threshold not reached, data delay, email filteredOpen the budget in the console; check notification settings and Pub/Sub topic
API [billingbudgets.googleapis.com] not enabledBudget API disabled in the quota projectgcloud services enable billingbudgets.googleapis.com
Quota 'CPUS' exceededRegion or project allocation quota reachedgcloud compute regions describe REGION; request an increase or change region
Quota is fine but VM creation still failsZone resource exhaustion (capacity), or an Organization PolicyRead the full error message; try another zone
Services stopped after a billing changeBilling disabled or the account closedgcloud billing projects describe PROJECT_ID; relink to an open account
Costs not attributed to the teamMissing labels, shared project, no exportCheck labels on the project and enable billing export (Hour 6)

Triage order

  1. Is billing enabled on the project (billingEnabled)? Which account is it?
  2. Is that account open, and does your identity (or the service account) hold billing.user?
  3. Is the needed API enabled in the project, and in the quota project used by the client?
  4. Compare quota usage and limit for the metric and region named in the error.
  5. Check the audit log for billing changes and for the denied call.
or score ≥ 70% on the quiz

Module 4 · Identity foundation

20–28 · Cloud Identity and Google Workspace, domain verification, groups, super admins and break-glass accounts
Cloud IdentityGroupsSuper admin2-step verification8 min
Learning objectives
  • Explain how a verified domain in Cloud Identity or Google Workspace creates the organization and the identities that IAM uses.
  • Design group-based access and a small set of administrator groups instead of granting roles to individuals.
  • Protect super admin and break-glass accounts with 2-step verification and monitoring, and explain why they are not for daily work.

The short answer

Google Cloud does not store people. It trusts an identity account: Cloud Identity (云身份) or Google Workspace (谷歌工作空间). Verifying your domain in either one creates the organization and provides the users, groups and security settings that IAM grants roles to. The landing zone's first design job is therefore to decide who administers that identity account, how people are grouped, and how the most privileged accounts are protected.

What: the pieces

PieceWhat it isWhy it matters
Cloud IdentityFree and Premium editions of the identity platform: users, groups, devices, SSO, 2-step verificationUse when you do not need Workspace apps. Verifying the domain creates the organization.
Google WorkspaceCloud Identity plus Gmail, Drive and collaborationIf the company already has it, reuse its users and groups.
Verified domainPrimary domain (and optional secondary domains) that you proved you ownTies users and the organization to your company.
UsersHuman accounts such as anna@example.comPrincipals that sign in to the console or gcloud.
GroupsCollections of users (and other groups) with an email addressThe unit for granting roles.
Super adminUnrestricted administrator of the identity accountOwns recovery, security settings and delegated admin roles.
Admin rolesRoles in the Admin console (user management, groups admin, help desk)Separate from IAM roles; they control identity data, not cloud resources.
SSO and provisioningFederation to an external identity provider (SAML or OIDC), automatic user provisioning (SCIM)Lets employees use the company login while Google keeps the accounts in sync.

Why: IAM needs real principals

  • People change roles. Group membership is where joiners, movers and leavers are handled. IAM then stays stable.
  • Policy is audited. An IAM policy listing twenty groups is readable. One listing four hundred users is not.
  • Security settings are central. 2-step verification, session length, password rules, and device rules are set in the identity account for all users.
  • Federation. Large companies already have an identity provider (for example Microsoft Entra ID or Okta). Federating avoids a second set of passwords while keeping Google groups for IAM.

How it works internally

  1. You sign up for Cloud Identity with a business email domain, or use an existing Google Workspace account. The first user becomes a super admin.
  2. You verify the domain by adding a TXT record (or a CNAME or MX record) at your DNS host. Google checks it and marks the domain verified.
  3. When the domain is verified and the first user signs in to the Google Cloud console, the organization resource is created for that account. Its numeric ID is stable and independent of the domain name.
  4. Users and groups are created in the Admin console (admin.google.com), through the Cloud Identity API, gcloud identity groups, bulk upload, or provisioning from an external identity provider.
  5. When a request arrives, IAM asks which groups the principal belongs to (including nested groups) and evaluates the union of the roles of the user and those groups.

The first super admin can grant themselves the organization administrator role; check the organization IAM policy after setup and grant the role to an admin group, then reduce individual grants.

Group design: the starting set

The security foundations guidance uses groups named after duties. Names below are examples; keep one convention.

Group (example)DutyTypical role scope
gcp-organization-adminsAdminister the organization, policies and IAMOrganization (very few members)
gcp-billing-adminsManage billing accountsBilling account
gcp-network-adminsManage networks and hybrid connectivityNetwork folder and projects
gcp-security-adminsManage security policy and keysOrganization and security project
gcp-logging-admins / gcp-monitoring-adminsManage logs and monitoringLogging and monitoring projects
gcp-developersBuild and deploy applicationsNon-production folders
gcp-auditorsRead-only audit accessOrganization, read roles

Super admin and break-glass design

  • Two or more super admins that are named people, so there is no single point of failure; fewer than five in total.
  • Separate accounts for admin work. A super admin uses a dedicated admin account (for example admin.anna@example.com), not the mailbox used for daily email and browsing.
  • Break-glass accounts: two or three dedicated accounts, not tied to a person, with long random passwords stored in a vault with dual control, and hardware security keys kept in separate safe locations.
  • Alert on use. Any sign-in of a break-glass account creates a high-severity alert, reviewed by security.
  • Test on a schedule. Sign in at least twice a year under change control, then rotate the password.

2-step verification

Enforce 2-step verification for everyone, and require phishing-resistant methods (security keys or passkeys) for administrators. Set the enforcement date and a grace period for new users in the Admin console under security authentication settings. Avoid SMS codes for admins. Use Context-Aware Access or device policies where the edition supports them.

When to use which identity product

SituationChoice
Company already uses Google WorkspaceUse it. The organization exists; build groups there.
Company uses Microsoft 365 or another provider, no Google appsCloud Identity (Free or Premium) with SSO and provisioning from the existing provider
Proof of concept, no domainA personal Google account and a project with no organization. No folders or policy; use only for learning.
Need device management or advanced securityCloud Identity Premium or Workspace editions with those features

What it is confused with

Often confusedWhy it differs
Admin console admin roles and IAM rolesAdmin roles manage users, groups and identity settings. IAM roles manage cloud resources. A super admin is not automatically an organization administrator in IAM.
Google group and Google Cloud service accountA group contains people. A service account is a non-human identity used by workloads (Hour 2).
Cloud Identity and Cloud IAMCloud Identity says who someone is and which groups they are in. IAM says what that principal may do on resources.
Super admin and break-glassSuper admins are named, accountable administrators. Break-glass accounts are emergency-only and exist for the identity system itself failing.

Common misunderstandings

"We can add everyone as Owner while we learn." Owner and Editor on the organization or a folder apply to every project below, and are hard to remove later. Start with groups and predefined roles on the smallest scope.
"A shared admin mailbox is break-glass." A shared mailbox is a single point of compromise with no accountability. Break-glass needs unique credentials, vault custody and monitoring.
"SSO makes MFA unnecessary." SSO moves the sign-in to your identity provider; that provider must enforce MFA. Emergency admins still need their own strong authentication.
Identity provider Entra ID, Okta, HR (optional) SAML / OIDC · SCIM Cloud Identity / Workspace example.com (verified domain) users · groups · 2-step verification Organization organizations/123456789012 created at domain verification gcp-organization-admins 3 named admins gcp-network-admins network team gcp-developers application teams organization · org admin role network folder · network roles non-prod folder · editor roles People join the groups; roles are bound to the groups. IAM resolves membership at request time. Break-glass and super admins sit outside this flow, with their own controls (see the next diagram).

Figure 1. From identity account to IAM binding. The groups are the link between people and roles.

Follow the arrows from the identity account to the groups and then to the scopes. Roles are attached at the folder or organization level to groups, and individuals only appear as members of those groups.

Daily account anna@example.com email, browsing, group roles no super admin rights Named super admin admin.anna@example.com security key required used only for admin tasks Break-glass emergency-1@example.com vault custody · tested twice a year any sign-in raises an alert Controls for all three: 2-step verification, audit logs for sign-in and admin actions, recovery information reviewed quarterly, no shared mailboxes, no personal devices for admins. Least privilege applies inside the Admin console too: use delegated admin roles for help desk. Break-glass is for lockouts and identity-provider failure only.

Figure 2. Three tiers of identity. The more power an account holds, the fewer people use it and the more it is monitored.

The animation starts from a DNS record and ends with an IAM binding to a group. It shows where trust comes from: domain ownership creates the organization, groups carry membership, and IAM expands membership at request time. The last step is the security setting that protects administrators.

Identity itself is mostly managed in the Admin console (admin.google.com), the Cloud Identity API or an external identity provider. The gcloud commands below read and bind identities on the cloud side. Creating a group or a binding is free. Group commands need the Cloud Identity API enabled and the right Admin console role; check gcloud identity groups --help in your SDK version.

Verify the domain (DNS) and read the organization

Purpose. Confirms the TXT record is published, then shows that the organization exists.

dig TXT example.com +short
gcloud organizations list
"google-site-verification=abcdEFGH1234example"
DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Flags. On Windows use nslookup -type=TXT example.com. Common errors. DNS changes can take time to propagate; wait and retry. A missing organization after verification means no user from the domain has signed in to the Cloud console yet. Cost. Free.

gcloud auth list and gcloud config list account

Purpose. Shows which identity gcloud is using. Always check this before changing IAM.

gcloud auth list
gcloud config list account
      Credentialed Accounts
ACTIVE  ACCOUNT
*       admin.anna@example.com

To set the active account, run:
    $ gcloud config set account `ACCOUNT`

Common errors. Running admin commands with a daily account leads to PERMISSION_DENIED. Production use. Admins use a dedicated account; automation uses impersonation or Workload Identity Federation, never a downloaded key.

gcloud identity groups create (write, free)

Purpose. Creates a group in the identity account. The flags for the group type and labels differ between SDK versions, so use the help text.

gcloud identity groups create GROUP_EMAIL \
  --organization=ORG_ID \
  --display-name="GCP Developers" \
  --description="Application developers, non-production"

Flags. GROUP_EMAIL must be on a verified domain. --organization identifies the customer by organization ID. Check gcloud identity groups create --help for the flags in your SDK version, including group labels. Common errors. PERMISSION_DENIED means the caller lacks the groups admin role in the Admin console, or the Cloud Identity API is disabled. Production use. Groups are created by the identity team or by provisioning from the identity provider, not by hand.

gcloud identity groups memberships list, add (write, free)

Purpose. Reads and changes who is in a group.

gcloud identity groups memberships list --group-email=GROUP_EMAIL
gcloud identity groups memberships add \
  --group-email=GROUP_EMAIL \
  --member-email=USER_EMAIL
ID                      ROLES
1234567890123456789     MEMBER
9876543210987654321     OWNER

Common errors. A member from outside the domain can be blocked by group sharing settings. Production use. Keep group ownership with the accountable manager, and review membership quarterly.

gcloud organizations get-iam-policy (read)

Purpose. Reads who holds roles on the organization. Run this after setup to remove personal grants.

gcloud organizations get-iam-policy ORG_ID \
  --flatten="bindings[].members" \
  --format="table(bindings.role,bindings.members)"
ROLE                                       MEMBERS
roles/resourcemanager.organizationAdmin    group:gcp-organization-admins@example.com
roles/billing.creator                      group:gcp-billing-admins@example.com
roles/resourcemanager.projectCreator       domain:example.com

Common errors. domain:example.com next to projectCreator means every user in the domain can create projects (a common default). Remove it after the project factory exists. IDs in the expected output are illustrative.

gcloud resource-manager folders add-iam-policy-binding (write, free)

Purpose. Grants a role to a group on a folder, which is the normal way to give a team access.

gcloud resource-manager folders add-iam-policy-binding FOLDER_ID \
  --member="group:GROUP_EMAIL" \
  --role="roles/browser"
Updated IAM policy for folder [555555555555].
bindings:
- members:
  - group:gcp-developers@example.com
  role: roles/browser
etag: BwYabc123=
version: 1

Flags. --member uses the group: prefix. roles/browser only lets the group list and read the hierarchy. To remove the binding, use remove-iam-policy-binding with the same flags. Common errors. INVALID_ARGUMENT: Group ... does not exist means the group email is wrong or has not propagated yet.

Sign-in audit (Admin console)

Purpose. Break-glass monitoring. In the Admin console open Reporting, Audit and investigation, Login log and filter by the break-glass user. Create an alert rule from the same page, and send it to security. Check the console menu names in your edition.

Production use. Keep a document with the identity account owner, the list of super admins, the list of break-glass accounts and where the credentials are stored. Review it every quarter.

Lab 4: review the identity foundation and bind a group on a folder (about 25 minutes)

Goal. Check that the domain and the organization exist, review who holds powerful roles, and give a lab group read access on a lab folder.

Prerequisites. A sandbox organization with a verified domain, a lab folder (from Lab 2), a lab group and a test user. You need the groups admin role (or a human who creates the group for you) and roles/resourcemanager.folderAdmin on the lab folder. Without an organization, read the steps and do only steps 1 and 2. IDs in the expected output are illustrative.

Cost. Free. No billable resource is created. Do not add real colleagues to lab groups and do not change the organization IAM policy in a shared organization.

  1. Check your identity.
    gcloud auth list
    gcloud config list account
  2. Find the organization and domain.
    gcloud organizations list
    dig TXT example.com +short
    Record the organization ID and whether the verification TXT is present.
  3. Review privileged roles on the organization.
    gcloud organizations get-iam-policy ORG_ID --flatten="bindings[].members" --format="table(bindings.role,bindings.members)" --filter="bindings.role:(organizationAdmin OR projectCreator OR billing.creator OR owner)"
    Write down every member of these roles. Mark each as group or individual, and note any domain: entry.
  4. Create a lab group (or ask your identity admin to create it): lz-lab-readers@example.com.
    gcloud identity groups create lz-lab-readers@example.com --organization=ORG_ID --display-name="LZ lab readers"
    Check gcloud identity groups create --help if your SDK version asks for other flags.
  5. Add a test member and verify.
    gcloud identity groups memberships add --group-email=lz-lab-readers@example.com --member-email=TEST_USER_EMAIL
    gcloud identity groups memberships list --group-email=lz-lab-readers@example.com
  6. Bind the group on the lab folder and verify.
    gcloud resource-manager folders add-iam-policy-binding FOLDER_ID --member="group:lz-lab-readers@example.com" --role="roles/browser"
    gcloud resource-manager folders get-iam-policy FOLDER_ID --flatten="bindings[].members" --format="table(bindings.role,bindings.members)"
    ROLE           MEMBERS
    roles/browser  group:lz-lab-readers@example.com
  7. Test the access. Sign in as the test user (separate browser profile) and run gcloud resource-manager folders describe FOLDER_ID. It should succeed. Try gcloud resource-manager folders create --folder=FOLDER_ID --display-name=denied; it must fail with PERMISSION_DENIED.
  8. Write the admin inventory. List the super admins, the break-glass accounts, where their credentials live, and whether 2-step verification is enforced (Admin console, Security, Authentication, 2-step verification). Record gaps.

Expected result. A group with one member, a binding on the folder, one successful read and one denied write, and an inventory of privileged identities.

Cleanup.

gcloud resource-manager folders remove-iam-policy-binding FOLDER_ID --member="group:lz-lab-readers@example.com" --role="roles/browser"
gcloud identity groups memberships delete --group-email=lz-lab-readers@example.com --member-email=TEST_USER_EMAIL
gcloud identity groups delete lz-lab-readers@example.com
Safety. Never change 2-step verification enforcement or super admin membership during a lab. Treat those as change-controlled actions in the real identity account.

Real cases

  • The departed administrator. A company granted roles/owner to individuals. When an administrator left, nobody knew which projects only he could manage. After moving to group-based grants and a quarterly membership review, offboarding became one change in the identity provider.
  • The IdP outage. A company federated sign-in to an external provider, which had an outage on a Monday morning. Engineers could not sign in. Two emergency super admins with security keys, stored in separate safes, restored access and let the team change the SSO profile. Afterwards the team added a runbook and a scheduled test of those accounts.
  • Consultants with personal Gmail. External partners were added as individual personal accounts. The security team enabled constraints/iam.allowedPolicyMemberDomains (Hour 3) and moved partners into a managed external-collaborator group in a separate folder with expiry reviews.

Practices

  • Create groups per duty and per environment, grant roles to groups only, and keep group owners accountable.
  • Keep the super admin count small (two to four named, plus break-glass) and use delegated Admin roles for help desk tasks.
  • Enforce 2-step verification for everyone and security keys or passkeys for admins. Disable SMS as a method for admins where possible.
  • Federate to your identity provider when one exists, provision groups automatically, and keep emergency accounts outside the federation.
  • Alert on sign-ins to break-glass accounts, on new super admin assignments, and on changes to 2-step verification enforcement.
  • Separate the identity-account administration (Admin console) from cloud administration (IAM) with different groups and different people where the team size allows.
Security note. Super admin compromise equals total compromise of the identity account, and so of the organization. Never use a super admin for email, never sign in from unmanaged devices, and never store credentials in chat, tickets or repositories.
Domain takeover risk. Whoever controls the DNS of your verified domain can prove ownership again. Protect DNS with the same care as identity: registrar lock, restricted access and change alerts.

Symptoms and first checks

SymptomLikely causeFirst check
Domain verification failsTXT record not published, wrong host, DNS not propagated, or record set in the wrong zonedig TXT example.com +short from a public resolver; compare to the console value
gcloud organizations list is empty after verificationNo domain user has signed in to the Cloud console yet, or your identity is outside the domainSign in to console.cloud.google.com as a user of the domain; check gcloud auth list
PERMISSION_DENIED on identity groups createMissing Admin console role, Cloud Identity API disabled, or wrong customerCheck the Admin console role and the --organization value
User added to group but still has no accessPropagation delay, nested group not allowed, or the binding is on a different scopeWait a few minutes; run memberships list and the IAM policy on the folder
Cannot add an external memberGroup sharing settings block members outside the domainAdmin console group settings; use a managed external-collaboration group instead
Everyone can create projectsA default domain: binding for projectCreator on the organizationgcloud organizations get-iam-policy ORG_ID; remove the broad grant once the factory exists
Users locked out after enforcing 2-step verificationNo enrolled second factor, no grace periodAdmin console: user security, backup codes; announce the enforcement date in advance
Nobody can sign in (SSO failure)Identity provider outage or certificate expiryUse an emergency super admin to change the SSO profile; check the certificate dates
Break-glass sign-in alert firedTest, or unauthorized useCheck the login log, confirm with the on-call owner, rotate the password after any use

Triage order

  1. Who is the caller? gcloud auth list and the identity shown in the audit log.
  2. Does the principal exist and is it active (not suspended) in the identity account?
  3. Is the principal in the expected groups (memberships list), directly or through nested groups?
  4. Does an IAM binding for those groups exist at the right scope and role?
  5. Check Organization Policy that restricts members (domain restriction) and any deny policy (Hour 2 and Hour 3).
or score ≥ 70% on the quiz

Module 5 · Naming, labels and tags

28–35 · Project ID rules, naming conventions, labels for cost, and Resource Manager tags for policy and IAM conditions
Project IDLabelsTags7 min
Learning objectives
  • State the project ID rules (6 to 30 characters, globally unique, immutable) and design a naming convention that survives growth.
  • Apply labels to projects and resources so that cost can be allocated in billing reports.
  • Distinguish labels (metadata for reporting) from Resource Manager tags (governance objects used by IAM conditions and Organization Policy).

The short answer

Every Google Cloud project has three names: a project name (a display name you can change), a project ID (chosen by you, unique worldwide, permanent) and a project number (assigned by Google, permanent). On top of names, there are two kinds of metadata: labels (标签), which you use for reporting and cost allocation, and Resource Manager tags (资源管理器标签), which you use for governance. A landing zone defines all of this once, so that every project looks the same and reports the same way.

What: the three project identifiers

IdentifierWho chooses itRulesCan it change?Where you see it
Project nameYou4 to 30 characters; letters, numbers, quotes, hyphens, spaces, exclamation marksYesConsole, gcloud projects list
Project IDYou (or generated if you leave it out in the console)6 to 30 characters; lowercase letters, digits and hyphens; starts with a letter; cannot end with a hyphen; globally uniqueNoEvery gcloud command, API path, resource names, billing export
Project numberGoogleNumericNoDefault service account names, IAM members of Google-managed agents, tag binding paths
Common misunderstanding. Renaming a project changes only its display name. The ID stays. If you need a different ID, you must create a new project and migrate, so choose the convention first and put it into the project factory.

Why: naming conventions

A name is the first thing an on-call engineer sees in an alert, a log line or a bill. A good convention lets a person tell what a project is, who owns it and how serious it is, without opening the console. Because the ID is global and permanent, three constraints shape the convention:

  • Global uniqueness. Someone else may already hold my-app-prod. A short generated suffix (four digits or random characters) makes collisions rare and is the common pattern for project factories.
  • Permanence. A project ID can hold the application and environment, but not a team name that will be reorganised, a person, or a customer secret. Put changeable facts in labels, where they can be updated.
  • Deleted IDs are not reused for a while. A deleted project keeps its ID reserved during the recovery period, and a project ID cannot be reused by a new project.

A pattern that works

prj-<app>-<env>-<nnnn>        prj-billing-prod-4821
fld-<purpose>                  fld-production, fld-nonprod, fld-platform
sa-<purpose>@PROJECT_ID...      sa-deployer@prj-billing-prod-4821.iam.gserviceaccount.com
net-<env>-<region>-<purpose>   net-prod-europe-west1-app

The enterprise foundations blueprint (Module 6) uses the same idea: a short prefix for the type, a business code, an environment, and a unique suffix. Pick one, write it down, and let automation create the names.

What: labels

A label is a key-value pair attached to one resource, such as env=prod or cost-center=cc1234. Labels are supported on projects and on most resources (VMs, buckets, BigQuery datasets, Cloud Run services and others). Facts to remember:

  • Up to 64 labels per resource. Keys are 1 to 63 characters, start with a lowercase letter, and may contain lowercase letters, digits, underscores and hyphens. Values are up to 63 characters with the same character set, and may be empty.
  • Labels are not inherited from folders to projects, or from projects to resources. Each resource carries its own.
  • Labels flow into billing reports and billing export to BigQuery, which is why they are the tool for cost allocation (Hour 6 covers the export in depth).
  • Labels are visible to anyone who can read the resource. Do not put secrets or personal data in them.
  • Labels are not access control. Changing a label never changes who can do what.

What: Resource Manager tags

A tag is different. It is a key and one of its allowed values, created as its own resource under an organization or a project, and then bound to a resource such as a project or folder. The key has a short name (env), a namespaced name (ORG_ID/env) and a numeric ID (tagKeys/281234567890). The values (dev, prod) have IDs too (tagValues/…).

  • Tags are inherited down the hierarchy: a tag bound to a folder applies to every project below it, unless a lower binding overrides the same key.
  • Tags are controlled with IAM: roles/resourcemanager.tagAdmin manages tag keys and values, roles/resourcemanager.tagUser allows binding existing tags. Only the right people can change what "prod" means.
  • Tags can be used in IAM Conditions (resource.matchTag("ORG_ID/env", "prod")), in conditional Organization Policy and in firewall policies, so that one rule can follow the label of a whole branch of the hierarchy.

Labels, tags and network tags compared

FeatureLabelsResource Manager tagsNetwork tags
PurposeReporting, filtering, cost allocationGovernance (IAM conditions, policy, firewall)Select VMs for legacy VPC firewall rules and routes
ScopeOne resourceDefined at organization or project, bound anywhere belowOne VM
Inherited?NoYesNo
Who may changeAnyone with update permission on the resourceControlled by tag IAM rolesAnyone who can edit the VM
In billing dataYesNo (use labels for billing)No
Typical usecost-center, owner, env, appenv=prod to apply a stricter rulehttp-server

When to use which

  • Need the bill by team or app: labels.
  • Need a rule to apply to one environment or data class, and need people not to change that classification freely: tags.
  • Need to define the structure that holds both: use folders and projects, not metadata. Metadata describes the hierarchy; it does not replace it.

Common misunderstandings

  • "Labels on the project will label everything inside it." They will not. Labels do not inherit. Set them in the project factory on the project and in your templates on each resource.
  • "A tag is a stronger label." A tag is a different object with its own lifecycle and permissions. It is not shown in billing exports, so keep both.
  • "Naming can be fixed later." Project IDs cannot. You can rename display names, labels and tags, but not the ID.
Project: prj-billing-prod-4821 ID is permanent and globally unique · number 123456789012 · name "Billing production" can change Labels (reporting) env=prod · app=billing cost-center=cc1234 · owner=team-pay set on each resource, not inherited Tags (governance) ORG_ID/env = prod bound to a folder or project, inherited changed only with tag IAM roles Billing export and reports cost by label IAM Conditions, Org Policy, firewall rules that follow the tag

Figure 1. One project, two kinds of metadata with two different destinations. Labels feed cost reporting; tags feed governance.

Look at the arrows: they show where the data goes. If your question is "who spends", the answer is on the left. If the question is "what is allowed", the answer is on the right.

Organization Folder: production tag env = prod (bound here) Folder: nonprod tag env = nonprod (bound here) prj-app-aeffective: prod prj-app-beffective: prod prj-test-aeffective: nonprod prj-exp-1own binding: dev A binding on the project itself overrides the inherited value for the same tag key.

Figure 2. Tag inheritance. Bind a value once on the folder and every project below it has that effective tag. A project may carry its own binding for the same key, which takes precedence.

The animation follows one project through labelling and tagging. The label path ends in billing data, the tag path ends in a policy decision. Notice that the two paths use different services.

Replace uppercase placeholders with your values. The label commands work on any project you can update. The tag commands need an organization and roles/resourcemanager.tagAdmin (to create keys and values) and roles/resourcemanager.tagUser (to bind them). All commands here are metadata changes and are free.

gcloud projects update --update-labels (write, free)

Purpose. Adds or changes labels on a project without touching the labels that already exist.

gcloud projects update PROJECT_ID --update-labels=env=dev,cost-center=cc1234,owner=team-platform
Updated project [https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID].
createTime: '2026-11-25T09:14:02.123Z'
labels:
  cost-center: cc1234
  env: dev
  owner: team-platform
lifecycleState: ACTIVE
name: Sandbox lab
parent:
  id: '555555555555'
  type: folder
projectId: PROJECT_ID
projectNumber: '123456789012'

Flags. --update-labels=KEY=VALUE,… adds or overwrites the keys you list. --remove-labels=KEY,… removes named keys. --clear-labels removes all labels. Do not use --clear-labels in scripts that share a project, because it also removes labels other teams rely on.

Common errors. Invalid value for field 'labels' means a key starts with a capital letter or digit, has a space, or a value is longer than 63 characters. PERMISSION_DENIED … resourcemanager.projects.update means you need roles/resourcemanager.projectUpdater or Owner on the project.

Production use. Labels are written by the project factory at creation, then changed through the same code, never by hand. Hour 7 builds this.

gcloud projects describe and projects list --filter (read, free)

Purpose. Read back labels and find projects by label. This is how you check that the convention is applied everywhere.

gcloud projects describe PROJECT_ID --format="yaml(projectId,projectNumber,labels,parent)"
gcloud projects list --filter="labels.env=dev" --format="table(projectId,labels.cost-center,parent.id)"
PROJECT_ID           COST_CENTER  ID
prj-sandbox-dev-0042  cc1234      555555555555

Flags. --filter="labels.env=dev" matches a label value. Use NOT labels.cost-center:* to find projects that have no cost-centre label (the :* form means "key exists"). --format="table(…)" selects columns; label keys with a hyphen work in table projections, but quote the whole format string.

Common errors. An empty result with no error means that no project matched, not that the command failed. Check the spelling and case of the key; label keys are lowercase.

Production use. A scheduled job that lists projects lacking the mandatory labels and opens a ticket is a cheap and effective audit.

gcloud resource-manager tags keys create (write, free)

Purpose. Creates a tag key at the organization (or project). The short name becomes part of the namespaced name ORG_ID/env.

gcloud resource-manager tags keys create env --parent=organizations/ORG_ID --description="Environment classification"
Waiting for TagKey [tagKeys/281234567890] to be created...done.
createTime: '2026-11-25T09:20:11.447Z'
description: Environment classification
name: tagKeys/281234567890
namespacedName: ORG_ID/env
parent: organizations/ORG_ID
shortName: env
updateTime: '2026-11-25T09:20:11.447Z'

Flags. --parent is organizations/ORG_ID or projects/PROJECT_ID. --description documents the key. Check gcloud resource-manager tags keys create --help for optional flags (such as --purpose for firewall tags) in your SDK version.

Common errors. PERMISSION_DENIED … resourcemanager.tagKeys.create means you lack roles/resourcemanager.tagAdmin. A duplicate short name under the same parent returns ALREADY_EXISTS.

gcloud resource-manager tags values create (write, free)

Purpose. Adds an allowed value to a key. The parent is the key's namespaced name.

gcloud resource-manager tags values create dev --parent=ORG_ID/env
gcloud resource-manager tags values create prod --parent=ORG_ID/env
gcloud resource-manager tags values list --parent=ORG_ID/env
NAME                      SHORT_NAME  DESCRIPTION
tagValues/281234500001    dev
tagValues/281234500002    prod

gcloud resource-manager tags bindings create (write, free)

Purpose. Attaches a tag value to a resource. For a project, the parent is written with the full resource name and the project number.

gcloud resource-manager tags bindings create \
  --tag-value=ORG_ID/env/dev \
  --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
gcloud resource-manager tags bindings list \
  --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
NAME                                                                               TAG_VALUE
tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123456789012/tagValues/281234500001  tagValues/281234500001

Flags. --tag-value accepts the namespaced name or the numeric tagValues/… ID. --parent uses the full resource name. Check gcloud resource-manager tags bindings create --help for location flags, which are needed for regional resources. IDs in the expected output are illustrative.

Common errors. Using the project ID instead of the project number in --parent fails with a not-found error. Missing roles/resourcemanager.tagUser on both the tag value and the resource fails with PERMISSION_DENIED.

Production use. Bind env on folders, not on every project. Then a conditional policy or IAM condition that checks env=prod covers new projects automatically.

Check your SDK. Tag commands are stable but the surrounding flags evolve. Run gcloud resource-manager tags --help and the --help of each subcommand before you script them.

Using a tag in an IAM Condition (read, concept)

The condition expression below grants a role only on resources that carry the env=dev tag. Conditions are covered in Hour 2; here it shows why tags exist.

resource.matchTag("ORG_ID/env", "dev")

Lab 5: naming, labels and a tag (about 10 minutes, free)

Goal. Validate a project ID against the rules, apply mandatory labels to a sandbox project, query by label, and, if you have an organization, create and bind one tag.

Prerequisites. A sandbox project you own (PROJECT_ID), with roles/resourcemanager.projectUpdater or Owner. For the tag steps: an organization and roles/resourcemanager.tagAdmin plus roles/resourcemanager.tagUser. No billing resources are created. IDs in the expected output are illustrative.

  1. Check the ID against the rules. Run a local check on your convention (not a Google command). The pattern below accepts 6 to 30 characters, lowercase letters, digits and hyphens, starting with a letter and not ending with a hyphen.
    echo "prj-sandbox-dev-0042" | grep -E '^[a-z][a-z0-9-]{4,28}[a-z0-9]$' && echo "valid"
    prj-sandbox-dev-0042
    valid
  2. Show the three identifiers.
    gcloud projects describe PROJECT_ID --format="table(name,projectId,projectNumber)"
    NAME          PROJECT_ID            PROJECT_NUMBER
    Sandbox lab   prj-sandbox-dev-0042  123456789012
  3. Apply mandatory labels.
    gcloud projects update PROJECT_ID --update-labels=env=dev,cost-center=cc1234,owner=team-platform
  4. Verify.
    gcloud projects describe PROJECT_ID --format="value(labels)"
    {'cost-center': 'cc1234', 'env': 'dev', 'owner': 'team-platform'}
  5. Find by label.
    gcloud projects list --filter="labels.cost-center=cc1234" --format="value(projectId)"
    The project ID must appear. Then run gcloud projects list --filter="NOT labels.cost-center:*" --format="value(projectId)" to see projects missing the label: that is your audit query.
  6. Observe that labels stay on the resource they were set on. The project label does not appear on resources inside the project unless you set it there too.
    gcloud projects describe PROJECT_ID --format="value(labels.env)"
    dev
    Anything you create later in the project (a bucket, for example) starts with no labels. Use Resource Manager tags (steps 7 to 9) for something that follows the hierarchy.
  7. Create a tag key and values (organization required).
    gcloud resource-manager tags keys create env --parent=organizations/ORG_ID
    gcloud resource-manager tags values create dev --parent=ORG_ID/env
    gcloud resource-manager tags values create prod --parent=ORG_ID/env
  8. Bind dev to the sandbox project.
    gcloud resource-manager tags bindings create --tag-value=ORG_ID/env/dev --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
  9. Verify the binding and the effective tags.
    gcloud resource-manager tags bindings list --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
    gcloud resource-manager tags bindings list --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER --effective
    The second command (check --help for --effective in your SDK) should list inherited tags as well.

Expected result. Labels present on the project, the filter finds it, and (with an organization) one tag binding to env=dev.

Cost. Free. These are metadata changes. Budgets send alerts and do not cap spend, which is why the hour 1 lab sets one first.

Cleanup.

gcloud resource-manager tags bindings delete --tag-value=ORG_ID/env/dev --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
gcloud resource-manager tags values delete ORG_ID/env/dev
gcloud resource-manager tags values delete ORG_ID/env/prod
gcloud resource-manager tags keys delete ORG_ID/env
gcloud projects update PROJECT_ID --remove-labels=env,cost-center,owner

Delete order matters: bindings first, then values, then the key. A key with values cannot be deleted.

Exercise (no commands): write your convention

On one page, write the pattern for folders, project IDs, service accounts and networks, the mandatory label keys (suggested: env, app, owner, cost-center), and the tag keys you will govern (suggested: env). Review it with the finance owner and the security owner. This page becomes the input for the Terraform project factory in Hour 7.

Real cases

  • The invoice that nobody could split. A company shared three billing accounts across forty projects and no labels. Finance asked for cost by team and the platform team spent two weeks guessing from project names. They introduced four mandatory labels (env, app, owner, cost-center), enforced them in the project factory and ran a weekly report of projects with missing labels. Allocation went from weeks to a query.
  • Names that contained a team. Projects were named after teams (prj-payments-team). After a reorganisation, the names were wrong and the IDs could not be changed. The new convention kept stable facts (application and environment) in the ID, and moved the team to an owner label that the factory updates on request.
  • Policy by tag instead of by list. A security team maintained a list of project IDs that were allowed to have external IP addresses. Moving to a tag on the folder (env=sandbox), plus a conditional Organization Policy, meant that new sandbox projects were covered at creation, and the list disappeared.

Practices

  • Define mandatory labels in one place (Terraform variables or a policy-as-code check), and fail the pipeline when one is missing.
  • Keep the label set small. Four to six keys that people maintain are better than twenty that nobody uses.
  • Use lowercase for every key and value. Mixed case is rejected for keys, and inconsistent values (Prod, prod, production) break reports. Allow only fixed value lists (dev, test, prod).
  • Give tagAdmin to the platform team only. Give tagUser to the project factory service account, so that automation, not people, decides classifications.
  • Apply tags at folder level wherever you can. Fewer bindings are easier to audit.
  • Never put secrets, personal data or customer names into labels, tags or project names. They appear in logs, billing exports and the console.
Security note. If a team can edit its own governance tags, it can move itself out of a stricter rule. Separate tagAdmin (define) from tagUser (bind), and monitor tag binding changes in the Admin Activity audit log.
Cost note. Labels allocate cost but do not reduce it. Cost-allocation labels only help if someone reads the report. Schedule the review (Hour 6).

Symptoms and first checks

SymptomLikely causeFirst check
The project ID … is already in use or "unavailable" when creating a projectID is taken globally or reserved by a deleted projectAdd a generated suffix; check gcloud projects list --filter="lifecycleState:DELETE_REQUESTED"
Invalid value for field 'labels'Key starts with a capital or a digit, has spaces, or a value is longer than 63 charactersLowercase everything; replace spaces with hyphens or underscores
Label on the project is missing on its buckets or VMsLabels do not inheritSet the label on each resource, or use a tag for inherited governance
Costs do not appear by label in the reportLabel added after the spend, or resource type does not propagate itLabels apply to costs from the time they are set; check the billing export schema (Hour 6)
PERMISSION_DENIED creating a tag keyMissing roles/resourcemanager.tagAdmin on the parentgcloud organizations get-iam-policy ORG_ID filtered to your identity
Tag binding command says the parent is not foundProject ID used instead of project numberRun gcloud projects describe PROJECT_ID --format="value(projectNumber)"
Tag key cannot be deletedKey still has values or bindingsDelete bindings, then values, then the key

Triage order

  1. Identify the identifier type you are working with (name, ID or number). Many errors come from using the wrong one.
  2. Check that the value follows the character and length rules.
  3. Check which IAM role the call needs (tagAdmin, tagUser, projectUpdater).
  4. Check inheritance: effective tags are inherited, labels are not.
  5. Read the Admin Activity audit log for the call to see the exact reason it failed.
or score ≥ 70% on the quiz

Module 6 · Landing-zone layers and the enterprise foundations blueprint

35–43 · Bootstrap, organization, environments, networks, projects and applications, with separation of duties
LayersFoundations blueprintSeparation of duties8 min
Learning objectives
  • Describe the layers of a landing zone (bootstrap, organization, environments, networks, projects, applications) and what each layer owns.
  • Explain the roles of the seed project, the CI/CD project and the shared projects, and why one identity must not own everything.
  • Map the Google Cloud enterprise foundations blueprint and the terraform-example-foundation repository to your own design decisions.

The short answer

A landing zone is not one Terraform file. It is a set of layers (层), each answering one question, each applied by its own pipeline identity and keeping its own state. The Google Cloud enterprise foundations blueprint (and its open-source implementation, the terraform-example-foundation repository) is the reference design that most teams adapt. You do not have to use it as is, but you should understand what it separates and why.

What: the layers

Layer (stage)What it createsWho applies itWhy separate
0 BootstrapSeed project, CI/CD project, Terraform state bucket, stage service accounts, initial groups wiringA human administrator, once. Later by the pipelineSolves the "who builds the builder" problem. The most privileged identities live here
1 OrganizationTop-level folders (common, network, bootstrap), organization policies, organization-level IAM, central logging and security projects, log sinks, billing exportOrg pipeline, with org-level rolesOnly a few people may change organization policy
2 EnvironmentsEnvironment folders (production, non-production, development), their policies, per-environment key and secret projectsEnvironments pipelineEnvironment rules differ; one stage per set of rules
3 NetworksHub or Shared VPC host projects, subnets, firewall policies, DNS, NAT, hybrid connectivityNetwork pipeline, network adminsNetwork changes are high risk and need network review
4 ProjectsBusiness-unit projects created by a project factory: labels, billing link, APIs, Shared VPC attachmentProjects pipelineHigh-volume, repeatable work; app teams request through pull requests
5 Application infrastructureWorkloads in the projects (compute, data, pipelines)The application team's own pipelineTeams own their workloads, within the guardrails above

Stage names and numbers differ between releases of the repository. Treat the table as the idea; read the repository README for the layout of the version you use.

What: the shapes inside the layers

  • Bootstrap folder and projects. A folder (often bootstrap) holds the seed project and the CI/CD project. Access is restricted to the platform administrators.
  • Common folder. Shared services owned by the platform and security teams: a logging project (organization log sink destination), a billing export project (BigQuery dataset for billing data), a security project (Security Command Center notifications), shared KMS and secrets projects, and a project for the scanner or policy tooling. The blueprint uses prefixes such as prj-b- (bootstrap) and prj-c- (common) so the type of a project is visible in its ID.
  • Network folder or projects. Host projects for Shared VPC (Hour 4), often one per environment, plus a hub if you use a hub-and-spoke design.
  • Environment folders. production, non-production and development (or an environment set you choose). Each holds business-unit subfolders and projects.

How it works: state, identities and reviews

  1. One state per stage, stored in a Cloud Storage bucket in the seed project (versioned, with uniform bucket-level access). A broken network change cannot corrupt organization state.
  2. One service account per stage. The pipeline does not hold standing keys. It authenticates (Workload Identity Federation or the CI/CD project's identity) and impersonates the stage service account with roles/iam.serviceAccountTokenCreator. The organization-stage account holds organization roles; the network-stage account holds network roles; the projects-stage account may create projects and link billing; none holds everything.
  3. Pull request, plan, approval, apply. Changes are proposed in Git, a plan is produced and reviewed by a human who did not write the change, and apply happens in the pipeline. The same person cannot write, approve and apply.
  4. Remote state references. Later stages read outputs of earlier stages (folder IDs, project IDs) rather than hard-coding them. Names and IDs stay consistent.

Why separation of duties matters

In the first week of a platform, one administrator does everything and that is acceptable. In production it becomes the most common root cause of serious incidents: one identity can delete a folder, change a policy and read all logs. Separation of duties (职责分离) reduces the blast radius (影响范围) of a mistake and of a stolen credential, and it is what auditors ask to see.

DutyTypical holderExample roles
Define organization policy and hierarchyOrganization admin group (very small)roles/resourcemanager.organizationAdmin, roles/orgpolicy.policyAdmin
Own billing accountsBilling admin grouproles/billing.admin
Own security tooling and logsSecurity admin grouproles/logging.admin, roles/securitycenter.admin
Own networkNetwork admin grouproles/compute.networkAdmin, roles/compute.xpnAdmin
Apply Terraform per stageStage service account (no human login)Only the roles that stage needs
Build and operate applicationsApplication team groupsPredefined roles on their projects only

When to follow the blueprint, and when to simplify

  • Follow it closely when you have many teams, regulated data, multiple environments, a hybrid network, or an audit requirement.
  • Simplify for a small organization: two environment folders, one network project, a single pipeline with separated roles, and the same principles (state bucket, service accounts, reviews). Keep the layout compatible so you can grow into the full design.
  • Use a different tool if you must (Cloud Foundation Toolkit modules, a commercial platform, or your own modules). The layers and the separation of duties matter more than the specific repository.

What it is confused with

TermMeaningNot the same as
Enterprise foundations blueprintGoogle's reference design with documentation and Terraform codeA managed service you subscribe to. You own the code you deploy
Cloud Foundation ToolkitA set of reusable Terraform modules (project factory, network and others)A full landing zone by itself
Seed projectHome of Terraform state and the privileged service accountsA "scratch" project for experiments
Shared services projectCentral logging, KMS, secrets, security toolingThe Shared VPC host project (that one is for networking)

Common misunderstandings

  • "Bootstrap can be done manually and forgotten." The bootstrap resources (state bucket, stage service accounts) are the most sensitive. They need protection, documentation and a recovery plan.
  • "One pipeline for everything is simpler, so it is better." It is simpler until it is compromised. One identity with all roles turns a pipeline bug into an organization incident.
  • "The blueprint gives me compliance." It gives you strong defaults. You still need to assess them against your own rules.
Organization stage 1: org policy · org IAM · log sink bootstrapstage 0 commonshared services networkstage 3 production · non-prod · devstage 2 folders seed projectstate · stage SAs CI/CD projectpipelines loggingorg sink target billing exportBigQuery dataset kms · secrets · sccsecurity tooling net host (prod)Shared VPC net host (non-prod)Shared VPC business unit folderstage 4 projects service projectsstage 5 workloads Every stage has its own Terraform state in the seed project bucket and its own service account. Names and the exact folder set differ between blueprint releases; the separation of layers is the point.

Figure 1. A typical blueprint layout. Red items hold the most privileged identities and state; amber items are shared services; green is networking; blue is the hierarchy and workloads.

Git repositorypull request Plan + reviewsecond person approves CI/CD pipelineno stored keys sa-tf-orgorganization roles sa-tf-envfolders, env policy sa-tf-netnetwork roles sa-tf-projproject creation The pipeline identity can only impersonate (create tokens for) these service accounts. Each account can change only its own layer. Compromise of one stage does not reach the others.

Figure 2. Impersonation. The pipeline has no powerful roles itself. It gets short-lived tokens for the service account of the stage it is applying.

The animation follows one apply of the organization, environments and projects stages. Watch which identity acts at each step: the pipeline never changes anything directly, it always acts as a stage service account.

These commands inspect the foundation you built or inherited. They are read-only and free unless marked otherwise. Replace uppercase placeholders. IDs in the expected output are illustrative.

git clone the blueprint repository (read, free)

Purpose. Read the reference code and README of the stage layout before you design your own. Cloning does not change anything in Google Cloud.

git clone https://github.com/terraform-google-modules/terraform-example-foundation.git
cd terraform-example-foundation
ls
0-bootstrap  1-org  2-environments  3-networks-dual-svpc  3-networks-hub-and-spoke  4-projects  5-app-infra  docs  policy-library  README.md

Flags. None. Use git tag --list and check out a release tag rather than the default branch if you adopt the code, so that your copy is reproducible. The directory names above change between releases; read the README.

Common errors. Repository not found means a typo or a proxy issue. Cloning anonymously needs no credentials. Never paste access tokens into the clone URL.

Production use. Fork into your own organization's repository host and treat the fork as product code: reviews, tags and a changelog.

gcloud resource-manager folders list (read, free)

Purpose. See the top-level folders and compare them with the blueprint's layout.

gcloud resource-manager folders list --organization=ORG_ID --format="table(displayName,name)"
DISPLAY_NAME      NAME
fldr-bootstrap    folders/111111111111
fldr-common       folders/222222222222
fldr-network      folders/333333333333
fldr-production   folders/444444444444
fldr-development  folders/555555555555

Flags. --organization lists the first level under the organization. Use --folder=FOLDER_ID to list children of a folder. --format="table(displayName,name)" chooses columns.

Common errors. An empty list on an organization where you expect folders usually means missing resourcemanager.folders.list, for example if you only hold roles/browser on a project.

gcloud projects list --filter by parent (read, free)

Purpose. List the shared projects in the common folder and confirm that they exist where the design says they should.

gcloud projects list --filter="parent.id=FOLDER_ID AND parent.type=folder" --format="table(projectId,name,labels.env)"
PROJECT_ID           NAME           ENV
prj-c-logging-a1b2   prj-c-logging  common
prj-c-kms-c3d4       prj-c-kms      common
prj-c-secrets-e5f6   prj-c-secrets  common

Common errors. Projects in a nested folder do not appear when you filter on the parent folder. List each level, or use Cloud Asset Inventory (Hour 6) for a recursive view.

gcloud organizations get-iam-policy (read, free)

Purpose. Review who holds organization-level roles. This is the first separation-of-duties audit: expect groups, a short list of roles, and no individual users or personal accounts.

gcloud organizations get-iam-policy ORG_ID \
  --flatten="bindings[].members" \
  --format="table(bindings.role,bindings.members)" \
  --filter="bindings.role:organizationAdmin OR bindings.role:billing.admin"
ROLE                                          MEMBERS
roles/resourcemanager.organizationAdmin       group:gcp-organization-admins@example.com
roles/billing.admin                           group:gcp-billing-admins@example.com

Flags. --flatten="bindings[].members" turns each member into its own row. --filter narrows to the roles you care about; note that billing roles are often granted on the billing account, not the organization, so an empty result is not a failure.

Common errors. PERMISSION_DENIED … resourcemanager.organizations.getIamPolicy means you lack roles/resourcemanager.organizationAdmin or roles/iam.securityReviewer on the organization. Ask for the narrower reviewer role, not admin.

gcloud iam service-accounts list in the seed project (read, free)

Purpose. Confirm that there is one service account per stage and that no unexpected ones exist.

gcloud iam service-accounts list --project=SEED_PROJECT_ID --format="table(email,displayName,disabled)"
EMAIL                                                 DISPLAY_NAME  DISABLED
sa-terraform-org@SEED_PROJECT_ID.iam.gserviceaccount.com   Org stage    False
sa-terraform-env@SEED_PROJECT_ID.iam.gserviceaccount.com   Env stage    False
sa-terraform-net@SEED_PROJECT_ID.iam.gserviceaccount.com   Net stage    False
sa-terraform-proj@SEED_PROJECT_ID.iam.gserviceaccount.com  Proj stage   False

Common errors. If the list contains default service accounts or accounts with user-managed keys, plan their removal. Keys on these accounts defeat the purpose of impersonation.

gcloud storage buckets describe for the state bucket (read, free)

Purpose. Verify that the state bucket has versioning and uniform bucket-level access.

gcloud storage buckets describe gs://STATE_BUCKET --format="yaml(name,location,uniform_bucket_level_access,versioning_enabled)"
location: EUROPE-WEST1
name: STATE_BUCKET
uniform_bucket_level_access: true
versioning_enabled: true

Flags. Output field names can differ between SDK versions. Check gcloud storage buckets describe --help and use --format=json to see all fields in your version.

Production use. Run these commands as a scheduled "foundation health" job and compare the output with a stored baseline. A new organization-level binding or a new key on a stage account should open a ticket.

Lab 6: map your foundation to the blueprint (about 12 minutes, free)

Goal. Produce a one-page gap analysis: which layers exist in your environment, which identities hold power, and which parts of the blueprint you would adopt first.

Prerequisites. Read access to an organization (roles/browser plus roles/iam.securityReviewer is enough) or the sandbox from Hour 1 setup. Git installed. No resources are created. If you have no organization, do steps 1 and 6 only. IDs in the expected output are illustrative.

  1. Clone and read. Clone the blueprint repository (see Commands), and open the README of the stages. Note the stage names of your release.
  2. List top-level folders.
    gcloud resource-manager folders list --organization=ORG_ID --format="table(displayName,name)"
    Mark in your notes which of these exist: bootstrap, common, network, production, non-production, development.
  3. Find the shared projects. For the common folder run the project list filter. Tick: logging, billing export, KMS, secrets, security.
  4. Review organization roles.
    gcloud organizations get-iam-policy ORG_ID --flatten="bindings[].members" --format="table(bindings.role,bindings.members)"
    Count the principals that are individual users. The target for production is zero for administrative roles.
  5. Review stage service accounts and keys. If you have a seed project, list its service accounts, then check each for user-managed keys:
    gcloud iam service-accounts keys list --iam-account=SA_EMAIL --managed-by=user
    Listed 0 items.
    The expected result is no user-managed keys.
  6. Write the gap table. Use the table below as a template and fill the right column.
    Layer            Exists?  Applied by (identity)   Reviewed by      Gap / next action
    Bootstrap        ...
    Organization     ...
    Environments     ...
    Networks         ...
    Projects         ...
    Applications     ...

Expected result. A filled table, a list of individual users with powerful roles (if any), and a list of user-managed keys (if any). Together they form the first backlog for the platform team.

Verification. Re-run steps 4 and 5 and confirm that your counts match the table. If you have a sandbox only, state which layers are missing by design.

Cost. None. Everything is read-only.

Cleanup. Delete the cloned repository directory if you do not need it. Nothing in Google Cloud changed.

Optional: sketch a minimal foundation

Draw the smallest version of the layout that fits a team of ten: one common folder with a logging project, two environment folders, one network host project and a single pipeline that impersonates two service accounts (one for organization, one for projects). Keep the folder names compatible with the blueprint, so that you can adopt more stages later.

Real cases

  • One service account for everything. A platform team ran all Terraform with one service account that held Owner on the organization. A pipeline misconfiguration deleted a shared host project. After the incident they split into four stage accounts with narrow roles, and added a manual approval before the network stage. The same mistake would now fail with PERMISSION_DENIED in a stage that does not own the resource.
  • Seed project used as a sandbox. Engineers were given Editor in the seed project "to debug the pipeline". A developer created a service account key there, which was later leaked. The fix: remove human access, keep state in a protected bucket, use break-glass access with logging, and never create keys.
  • Adopting the blueprint late. An organization with 120 existing projects could not rebuild. It adopted the layers in order: first bootstrap and organization policies in audit-only mode, then moved projects into environment folders in batches, then introduced the project factory for new projects only. Existing projects were imported or left until their next major change.

Practices

  • Run bootstrap once with a named human administrator, record every step, then remove or tightly control that human access.
  • Give each stage its own service account, state prefix and approval rule. Restrict who can create tokens for each account (roles/iam.serviceAccountTokenCreator only to the pipeline identity).
  • Require a pull request, a plan in the review, and at least one approver who did not write the change.
  • Protect the state bucket: uniform bucket-level access, object versioning, a retention or soft-delete policy, and no public access. Consider restricting the bucket to the stage identities with IAM Conditions.
  • Keep a break-glass procedure for when the pipeline is down: named accounts, strong authentication, an approval, a logged session, and a review afterwards.
  • Version the foundation code with tags. Upgrade deliberately, reading release notes for breaking changes.
Security note. Service accounts in the seed project can reach the entire organization. Do not create user-managed keys for them, do not give humans Service Account User or Token Creator on them outside break-glass, and alert on any change to their IAM policy.
Cost note. The shared projects (logging, billing export, security) can generate real cost from log ingestion and BigQuery storage. Set budgets for them as well as for application projects.

Symptoms and first checks

SymptomLikely causeFirst check
Pipeline fails with iam.serviceAccounts.getAccessToken deniedPipeline identity lacks roles/iam.serviceAccountTokenCreator on the stage accountgcloud iam service-accounts get-iam-policy SA_EMAIL
Stage apply says a folder or project already existsTwo stages own the same resource, or it was created by handSearch state for the address; import or delete one owner
Error acquiring the state lockA previous run is still active or crashedCheck the pipeline run; unlock only after confirming no apply is running (Hour 7)
Stage cannot read outputs of an earlier stageWrong bucket or prefix in the remote state referenceCompare the backend and terraform_remote_state settings
New project has no billing link after the projects stageStage account lacks roles/billing.user on the billing accountgcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID
Plan wants to destroy shared projectsWrong variables (folder ID or naming) or a changed releaseStop. Read the plan line by line; compare variables with the last applied values
Network stage cannot create a Shared VPC hostMissing roles/compute.xpnAdmin at the organization or folderCheck the stage account's roles at the parent

Triage order

  1. Find out which stage and which service account failed. The pipeline log names both.
  2. Check whether the failing call is an IAM problem (denied), a policy problem (Organization Policy) or a state problem (lock, drift).
  3. Read the audit log entry for the denied call to see the exact permission.
  4. Fix by changing the stage's role in code, not in the console. A console fix will drift (Hour 7).
  5. Never widen a stage account to Owner to make a pipeline green.
or score ≥ 70% on the quiz

Module 7 · Lab: build and verify the hierarchy

43–53 · A sandbox folder and project with labels, a billing link and a budget, verified step by step and cleaned up
Hands-onHierarchyBillingVerification10 min
Learning objectives
  • Build a sandbox folder and project with mandatory labels, link it to billing and set a budget before anything else is created.
  • Verify every step with a read command and compare the result with the expected output.
  • Remove everything in the right order and confirm that nothing that costs money remains.

The short answer

This module is a guided build. You create the smallest useful landing-zone hierarchy: one sandbox folder (文件夹), one project (项目) with mandatory labels, a billing link (结算关联) and a budget (预算). After every write you run a read command (the verification) and compare the output. At the end you delete everything in dependency order. The point is the habit: set the safety net first, change one thing at a time, prove it worked, and clean up.

What you build

StepObjectWrite commandVerificationCost
1Preflight(read only)gcloud organizations list, gcloud billing accounts listFree
2Folder lz-lab-sandboxgcloud resource-manager folders createfolders describeFree
3Project with labelsgcloud projects create --folder --labelsprojects describeFree (no resources)
4Billing linkgcloud billing projects linkbilling projects describeFree (no services used)
5Budgetgcloud billing budgets createbilling budgets listFree
6Audit trail check(read only)gcloud logging readFree
7Cleanupdelete budget, unlink, delete project, delete folderlist commands return nothingFree

No compute, storage or network resources are created, so the lab itself has no metered cost. The budget exists because the habit matters, and because it is the first guard if somebody extends the lab.

Why this order

  • Folder before project. A project can be created with --folder only if the folder exists. Creating the project at the organization root and moving it later is possible but leaves a window in which inherited policies are not yet applied.
  • Labels at creation. Setting labels in the creation command means there is never a moment when the project is unlabelled. Cost reports are correct from the start.
  • Billing link before APIs. Many service APIs cannot be enabled until billing is linked. The lab does not enable any, but the order mirrors what a project factory does.
  • Budget before resources. A budget sends alerts but does not cap spend (see Module 3). Having the alert in place before anything is built means a mistake is visible within the day.
  • Verify after every write. A write command can return success while the effect is not what you intended (a wrong parent, a wrong billing account). A read command is the proof.

How the commands relate to the earlier modules

Lab stepConceptModule
Find the organization and the billing accountHierarchy, billing accounts2, 3
Create folder and project with a conventionNaming and IDs2, 5
LabelsCost allocation5
Link and budgetBilling structure and alerts3
Who may do each stepIdentity and roles4, 6

Roles you need

ActionRole (predefined)Where
Create a folderroles/resourcemanager.folderCreatorOrganization or parent folder
Create a project in the folderroles/resourcemanager.projectCreatorOrganization or folder
Link a project to billingroles/billing.user on the billing account, plus resourcemanager.projects.createBillingAssignment on the project (in the project Owner role)Billing account and project
Create a budgetroles/billing.costsManager (or roles/billing.admin)Billing account
Delete a projectroles/resourcemanager.projectDeleter or OwnerProject
Sandbox rule. If you cannot get these roles, do not ask for Organization Administrator. Ask for the narrow roles on a sandbox folder and a sandbox billing account, or use a personal Google Cloud account with a billing account that you own. In that case you have no organization: skip the folder and use gcloud projects create PROJECT_ID without --folder.

Common misunderstandings

  • "Free tier means there is nothing to clean up." Even a free project keeps its ID and quota. Clean up so the lab account is not full of forgotten projects.
  • "The budget protects me." It does not stop spend. It only tells you.
  • "Deleting the project deletes the folder." It does not. Folder cleanup is a separate command.
  • "A successful create means the settings are right." The verification commands exist because create returns success even if the parent or labels are not what you meant.
1 Preflightorg · billing 2 Folderlz-lab-sandbox 3 Projectlabels at creation 4 Billing linkbillingEnabled 5 Budget50 · 90 · 100% Verification after each write: describe or list, compare with expected output 6 Audit check, then 7 Cleanup in dependency order delete budget → unlink billing → delete project (recoverable) → delete folder when empty

Figure 1. The lab in one line. Green steps change the hierarchy, amber steps attach money, and the red bar is the habit that makes it safe.

Organization ORG_IDexisting, not changed Folder lz-lab-sandboxFOLDER_ID Project PROJECT_IDenv=sandbox · owner=you · cost-center=cc0000billingEnabled: true Billing accountbudget: 3 thresholdsemail alerts Nothing else exists:no APIs enabled, no network,no VMs, no buckets

Figure 2. The end state. If a later command shows anything more than this, something other than the lab created it.

The animation follows the write commands and their effects in one run, including the audit entry that proves who did what. The last step shows project deletion as a recoverable state, not an instant removal.

This tab lists every command used in the lab with its purpose, flags, expected output and common errors. IDs in the expected output are illustrative. Replace the uppercase placeholders. A write command changes your environment. All commands here are free because no metered resource is created.

gcloud organizations list and gcloud billing accounts list (read, free)

Purpose. Find the organization ID and an open billing account ID.

gcloud organizations list
gcloud billing accounts list --filter="open=true" --format="table(name,displayName,open)"
DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

NAME                          DISPLAY_NAME      OPEN
billingAccounts/0X0X0X-0X0X0X-0X0X0X  Sandbox billing  True

Flags. --filter="open=true" hides closed accounts. --format="table(…)" chooses columns. The account ID is the part after billingAccounts/.

Common errors. An empty billing list means you do not have roles/billing.user (or higher) on any account. Ask the billing owner for the role on the sandbox account only.

gcloud resource-manager folders create (write, free)

Purpose. Creates the sandbox folder under the organization.

gcloud resource-manager folders create --display-name="lz-lab-sandbox" --organization=ORG_ID
Create in progress for folder [folders/555555555555].

Flags. --display-name must be unique among siblings. --organization or --folder sets the parent. Display names are 3 to 30 characters in length.

Common errors. PERMISSION_DENIED means a missing roles/resourcemanager.folderCreator. ALREADY_EXISTS means a sibling already has this display name; choose another or reuse the folder.

Verify.

gcloud resource-manager folders list --organization=ORG_ID --filter="displayName=lz-lab-sandbox" --format="value(name)"
folders/555555555555

gcloud projects create (write, free)

Purpose. Creates the project inside the folder with the mandatory labels.

gcloud projects create PROJECT_ID \
  --name="LZ lab sandbox" \
  --folder=FOLDER_ID \
  --labels=env=sandbox,owner=your-name,cost-center=cc0000
Create in progress for [https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID].
Waiting for [operations/cp.1234567890123456789] to finish...done.
Enabling service [cloudapis.googleapis.com] on project [PROJECT_ID]...
Operation "operations/acat.p2-123456789012-aaaa" finished successfully.

Flags. PROJECT_ID must follow the ID rules (6 to 30 characters, lowercase letters, digits, hyphens). --folder and --organization are alternatives for the parent. --labels sets labels at creation. --name is the display name. --set-as-default would change your default project; avoid it in a shared shell.

Common errors. The project ID you specified is already in use by another project means the ID is taken; add a suffix. Operation denied by org policy … constraints/gcp.restrictProjectCreation (or a similar message) indicates an organization restriction on who may create projects. PERMISSION_DENIED … resourcemanager.projects.create means a missing roles/resourcemanager.projectCreator on the folder.

Verify.

gcloud projects describe PROJECT_ID --format="yaml(projectId,projectNumber,lifecycleState,parent,labels)"
labels:
  cost-center: cc0000
  env: sandbox
  owner: your-name
lifecycleState: ACTIVE
parent:
  id: '555555555555'
  type: folder
projectId: PROJECT_ID
projectNumber: '123456789012'

gcloud billing projects link (write, free until services are used)

Purpose. Links the project to a billing account.

gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
billingAccountName: billingAccounts/BILLING_ACCOUNT_ID
billingEnabled: true
name: projects/PROJECT_ID/billingInfo
projectId: PROJECT_ID

Flags. --billing-account takes the account ID without the prefix.

Common errors. The caller does not have permission means a missing roles/billing.user on the account or Owner on the project. Cloud Billing account … is closed means the account is not open. Link limits (a quota on projects per billing account) show as a quota error; request more through the billing owner.

Verify.

gcloud billing projects describe PROJECT_ID

gcloud billing budgets create (write, free)

Purpose. Creates an alerting budget restricted to the lab project.

gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="lz-lab-sandbox budget" \
  --budget-amount=20USD \
  --filter-projects=projects/PROJECT_NUMBER \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0
Created budget [billingAccounts/BILLING_ACCOUNT_ID/budgets/BUDGET_ID].

Flags. --budget-amount is an amount with a currency code that matches the billing account currency. --filter-projects restricts the budget to listed projects. --threshold-rule=percent=… adds an alert threshold (fractions of the budget). Check gcloud billing budgets create --help for the flags in your SDK version, including notification options. A budget does not stop spend.

Common errors. Cloud Billing Budget API has not been used in project … before means the API must be enabled in the quota project you are using (gcloud services enable billingbudgets.googleapis.com --project=ADMIN_PROJECT_ID, then retry with --billing-project=ADMIN_PROJECT_ID if your SDK asks for it). PERMISSION_DENIED means missing roles/billing.costsManager or roles/billing.admin. A wrong currency code gives an INVALID_ARGUMENT error.

Verify.

gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID --format="table(displayName,amount.specifiedAmount.units,amount.specifiedAmount.currencyCode)"
DISPLAY_NAME            UNITS  CURRENCY_CODE
lz-lab-sandbox budget   20     USD

gcloud logging read for the audit trail (read, free)

Purpose. Proves who created the project, using the Admin Activity audit log. The log is always on and free to read for the default retention.

gcloud logging read 'protoPayload.methodName="CreateProject" AND protoPayload.resourceName:"PROJECT_ID"' --project=PROJECT_ID --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName)"
2026-11-25T09:14:02.451Z  you@example.com  CreateProject

Flags. The filter is a Logging query. --limit caps results. Project creation audit entries may be recorded at the organization or folder level and not in the new project; if the command returns nothing, repeat with --folder=FOLDER_ID or --organization=ORG_ID in place of --project. IDs and times are illustrative.

Common errors. No output may mean the entry is stored at another level, or you lack roles/logging.viewer (and roles/logging.privateLogViewer for Data Access logs).

Cleanup commands (write, free)

gcloud billing budgets delete BUDGET_ID --billing-account=BILLING_ACCOUNT_ID
gcloud billing projects unlink PROJECT_ID
gcloud projects delete PROJECT_ID
gcloud resource-manager folders delete FOLDER_ID

Flags. gcloud projects delete asks for confirmation; add --quiet only in automation. A deleted project can be restored with gcloud projects undelete PROJECT_ID during the recovery period. Find BUDGET_ID from gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID --format="value(name)" (the last path element).

Common errors. Deleting a folder that still contains active projects or folders fails with a precondition error. A project in the DELETE_REQUESTED state may still count as a child; if the folder cannot be deleted yet, leave the empty folder (it is free) and retry later, or check gcloud resource-manager folders delete --help.

Lab 7: build and verify the hierarchy (10 minutes in the session, free)

Goal. Create a sandbox folder and project with labels, link billing, set a budget, verify each step, read the audit entry, and clean up.

Prerequisites. The roles from the Concepts tab, gcloud authenticated (Cloud Shell is the easiest), an organization ID (ORG_ID) and an open billing account (BILLING_ACCOUNT_ID) from the preflight step. A unique PROJECT_ID following the pattern prj-lzlab-sbx-NNNN (replace NNNN with four random digits). No real secrets are used. IDs in the expected output are illustrative.

Cost. Free. The lab creates no compute, storage or network resources. Budgets send alerts and do not cap spend.

Set the variables once

export ORG_ID=123456789012
export BILLING_ACCOUNT_ID=0X0X0X-0X0X0X-0X0X0X
export PROJECT_ID=prj-lzlab-sbx-$(printf '%04d' $((RANDOM % 10000)))
echo "$PROJECT_ID"
prj-lzlab-sbx-4821
  1. Preflight. Confirm identity, organization and billing.
    gcloud config list account --format="value(core.account)"
    gcloud organizations list --format="value(ID)" | grep "$ORG_ID"
    gcloud billing accounts list --filter="name=billingAccounts/$BILLING_ACCOUNT_ID AND open=true" --format="value(name)"
    Expected: your account, the organization ID, and the billing account. If any line is empty, stop and fix access first.
  2. Create the folder.
    gcloud resource-manager folders create --display-name="lz-lab-sandbox" --organization="$ORG_ID"
    export FOLDER_ID=$(gcloud resource-manager folders list --organization="$ORG_ID" --filter="displayName=lz-lab-sandbox" --format="value(name)" | cut -d/ -f2)
    echo "$FOLDER_ID"
    Verify: echo "$FOLDER_ID" prints a 12-digit number. If it prints nothing, wait a few seconds and run the second command again.
  3. Create the project in the folder, with labels.
    gcloud projects create "$PROJECT_ID" --name="LZ lab sandbox" --folder="$FOLDER_ID" --labels=env=sandbox,owner=your-name,cost-center=cc0000
    Verify:
    gcloud projects describe "$PROJECT_ID" --format="value(lifecycleState,parent.id,labels.env)"
    ACTIVE	555555555555	sandbox
    The middle value must equal your folder ID.
  4. Link billing.
    gcloud billing projects link "$PROJECT_ID" --billing-account="$BILLING_ACCOUNT_ID"
    gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled,billingAccountName)"
    True	billingAccounts/0X0X0X-0X0X0X-0X0X0X
  5. Create the budget.
    export PROJECT_NUMBER=$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)")
    gcloud billing budgets create --billing-account="$BILLING_ACCOUNT_ID" --display-name="lz-lab-sandbox budget" --budget-amount=20USD --filter-projects="projects/$PROJECT_NUMBER" --threshold-rule=percent=0.5 --threshold-rule=percent=0.9 --threshold-rule=percent=1.0
    Verify:
    gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:'lz-lab-sandbox budget'" --format="value(name,displayName)"
    The budget name must appear. Check the currency of your billing account; if it is not USD, use its currency code. Check gcloud billing budgets create --help if a flag is rejected in your SDK version.
  6. Confirm nothing else exists. No services are enabled that cost money, and there is no network.
    gcloud services list --enabled --project="$PROJECT_ID" --format="value(config.name)" | head -20
    You see only default APIs (for example the Cloud APIs bundle) or an empty list. Do not enable Compute Engine in this lab: the default network creation would be an unwanted side effect if your organization does not set compute.skipDefaultNetworkCreation (Hour 3).
  7. Read the audit entry. Run the gcloud logging read command from the Commands tab (project, folder or organization scope). You should see your principal and CreateProject.
  8. Run the verification script. It checks all of the above and prints PASS or FAIL per line.
    pass() { echo "PASS  $1"; }; fail() { echo "FAIL  $1"; }
    [ "$(gcloud projects describe "$PROJECT_ID" --format='value(lifecycleState)')" = "ACTIVE" ] && pass "project active" || fail "project active"
    [ "$(gcloud projects describe "$PROJECT_ID" --format='value(parent.id)')" = "$FOLDER_ID" ] && pass "parent is lab folder" || fail "parent is lab folder"
    [ "$(gcloud projects describe "$PROJECT_ID" --format='value(labels.env)')" = "sandbox" ] && pass "label env=sandbox" || fail "label env=sandbox"
    [ "$(gcloud billing projects describe "$PROJECT_ID" --format='value(billingEnabled)')" = "True" ] && pass "billing enabled" || fail "billing enabled"
    [ -n "$(gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:'lz-lab-sandbox budget'" --format='value(name)')" ] && pass "budget exists" || fail "budget exists"
    PASS  project active
    PASS  parent is lab folder
    PASS  label env=sandbox
    PASS  billing enabled
    PASS  budget exists

Expected result. Five PASS lines, a folder with one project, one budget, and an audit entry showing who created the project.

Cleanup (do not skip)

  1. Delete the budget:
    export BUDGET_ID=$(gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:'lz-lab-sandbox budget'" --format="value(name)" | awk -F/ '{print $NF}')
    gcloud billing budgets delete "$BUDGET_ID" --billing-account="$BILLING_ACCOUNT_ID"
  2. Unlink billing: gcloud billing projects unlink "$PROJECT_ID". Verify: gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled)" prints False.
  3. Delete the project: gcloud projects delete "$PROJECT_ID". Verify: gcloud projects describe "$PROJECT_ID" --format="value(lifecycleState)" prints DELETE_REQUESTED.
  4. Delete the folder: gcloud resource-manager folders delete "$FOLDER_ID". If it fails because of the project pending deletion, leave the empty folder (free) and delete it later.
  5. Final check: gcloud projects list --filter="labels.env=sandbox AND labels.owner=your-name" shows nothing active.

Restore (optional exercise). Before the recovery period ends, gcloud projects undelete "$PROJECT_ID" restores the project. Link it to billing again if you want it to work. Practising this once makes the production case in Module 8 routine.

Real cases

  • Sandbox sprawl. A company gave every engineer a project in a sandbox folder with a monthly budget but no clean-up. A year later there were hundreds of idle projects, each holding a few forgotten resources. The fix combined a mandatory expiry label, a weekly job that listed expired projects and notified owners, and automatic deletion after two reminders. Deletion stays recoverable for the recovery period.
  • Lab that billed the wrong account. A training team linked student projects to the shared corporate billing account. A student ran a large job and the alert went to nobody. The training platform was changed to create a dedicated billing account per course with a budget alert to the instructor, and a strict list of allowed services in a sandbox folder.
  • Verification as code. A platform team turned their post-creation checks (parent, labels, billing enabled, budget exists) into a pipeline step. Every new project is checked before the requester is told it is ready. Failures are rare, but they caught two wrong-parent errors in the first month.

Practices

  • Run every lab in a dedicated sandbox folder with its own budget and a named owner. Never test in production folders.
  • Prefer Cloud Shell for labs: no local credentials to leak, and the session is isolated.
  • Write the set of commands you ran next to the verification output. In production this becomes the change record.
  • Delete in dependency order and confirm with a list command. A clean-up that is not verified is not finished.
  • Use --impersonate-service-account or short-lived credentials for automation. Do not export a service account key to run the lab.
Cost note. This lab creates no metered resources. If you extend it (enable Compute Engine, create a VM, a disk or a static IP), delete those first and read the billing report the next day. A budget sends alerts and does not stop anything.
Security note. Never run the lab with a shared Owner account, and never paste an access token or key file into a command. If you must use a service account, use impersonation with the Token Creator role granted for the session and removed afterwards.

Symptoms and first checks

SymptomLikely causeFirst check
folders create returns PERMISSION_DENIEDNo roles/resourcemanager.folderCreator on the organization or parentgcloud organizations get-iam-policy ORG_ID (find your member)
projects create fails with an ID in useID is taken or reserved by a deleted projectChoose a new suffix; the ID pattern needs 6 to 30 characters
projects create is denied by an organization policyProject creation is restricted (for example by a constraint or by a missing role)Read the error text; gcloud org-policies list --organization=ORG_ID
billing projects link failsMissing roles/billing.user, closed billing account, or a project quota on the accountgcloud billing accounts list shows OPEN; check roles on the account
budgets create says the API is not enabledBilling Budget API is not enabled in the quota projectEnable billingbudgets.googleapis.com in an admin project and pass --billing-project
budgets create returns INVALID_ARGUMENTCurrency code does not match the billing account, or an unsupported flaggcloud billing budgets create --help; check the account currency
Folder delete failsFolder still has active children (or a child pending deletion)gcloud projects list --filter="parent.id=FOLDER_ID"
Audit log search returns nothingEntry stored at organization or folder, or filter typoRepeat the query with --folder or --organization; check the filter string

Triage order

  1. Print your identity (gcloud config list account) and the project you are targeting (gcloud config list project). Many failures are the wrong account or the wrong default project.
  2. Read the whole error. The message normally names the permission, the constraint or the API.
  3. Check IAM at the right level (organization, folder, billing account, project).
  4. Check Organization Policy (gcloud org-policies list) if the error mentions a constraint.
  5. Check the audit log for the denied call, then decide on the smallest role change that fixes it.
or score ≥ 70% on the quiz

Module 8 · Production cases and troubleshooting

53–60 · Project creation denied, billing not linked, default network created, quotas, and project deletion and recovery
TroubleshootingProduction casesRecovery7 min
Learning objectives
  • Diagnose the five most common Hour 1 failures (creation denied, billing not linked, default network, quota, deleted project) with a fixed triage order.
  • Choose the smallest safe fix for each case and prevent it from coming back through policy and automation.
  • Recover a deleted project during the recovery period and know what cannot be recovered.

The short answer

Almost every foundation problem is one of five things: an identity that lacks a role, a policy that blocks the request, a billing link that is missing or closed, a quota that is reached, or a lifecycle event such as a deleted project. Use the same triage order every time, read the error message in full, and fix the cause in code so that it does not come back.

What: the five cases

CaseTypical error textReal causePermanent fix
1 Project creation deniedPERMISSION_DENIED, caller does not have permission, Operation denied by org policyMissing projectCreator on the parent, restricted creation by policy, or the wrong parentCreate projects only through the project factory; grant the factory's service account, not people
2 Billing not linkedThis API method requires billing to be enabled, billingEnabled: falseNo link, closed account, missing billing.user, or project quota on the billing accountProject factory links billing; billing access through groups
3 Default network createdA default VPC with default-allow-ssh, default-allow-rdp, default-allow-icmpCompute API enabled without skipDefaultNetworkCreationEnforce constraints/compute.skipDefaultNetworkCreation at the organization
4 Quota exceededQuota 'CPUS' exceeded. Limit: 24.0 in region …, RATE_LIMIT_EXCEEDEDProject or region limit reached (also API request rate)Request increases in the project factory for known needs; monitor usage
5 Project deletedProject … was requested for deletion, lifecycleState: DELETE_REQUESTEDManual delete, a Terraform destroy, or an automation bugLien on critical projects, deletion protection in Terraform, restricted delete roles

How to think about each case

Case 1: project creation denied

Project creation has three gates: IAM (does the caller have resourcemanager.projects.create on the parent?), Organization Policy (does any constraint block it?) and billing (if you link at the same time, does the caller have billing.user?). In many organizations, the roles/resourcemanager.projectCreator role is deliberately not granted to people at the organization level, because the default organization grant lets everyone in the domain create projects and billing links. When creation is denied for a person, the correct answer is usually "use the project factory", not "grant yourself the role".

Case 2: billing not linked

A project needs an open billing account for most services. Four things break the link: no link was made, the account is closed or suspended, the caller lacks roles/billing.user on the account, or the billing account has reached its limit on linked projects. A link also disappears when an administrator unlinks the project, which immediately stops paid resources. This is why billing changes are audited and why the billing admin group is small.

Case 3: the default network

When the Compute Engine API is first enabled in a project, Google creates an auto mode network called default with firewall rules that allow SSH, RDP and ICMP from anywhere, and all traffic within the network. That is a convenient lab default and a poor production default. The landing zone enforces constraints/compute.skipDefaultNetworkCreation so that projects start with no network, and the network layer creates a custom Shared VPC attachment (Hour 4). The constraint does not delete a network that already exists. You delete the firewall rules first, then the network.

Case 4: quotas

Quotas are limits per project (and per region for most compute resources). They are different from budgets (which warn about spend) and from Organization Policy (which restricts what can be done). Increasing a quota may need a request and an approval from Google. Plan for the time, because it is not instant, and set up monitoring on usage.

Case 5: deletion and recovery

Deleting a project (gcloud projects delete) shuts down the project: resources stop, billing stops, and the state becomes DELETE_REQUESTED. After a recovery period (typically 30 days; check the documentation for your case) the project and its resources are permanently removed. During the period you can run gcloud projects undelete. Not every resource comes back unchanged, and some deletions (a Cloud Storage bucket that was already deleted, a Cloud SQL instance that was deleted separately) follow their own rules. A lien on a project blocks deletion until it is removed.

Why a triage order

  1. Identity. Who made the call? (The wrong account or the wrong impersonated service account is common.)
  2. Scope. Which project, folder or organization was the target?
  3. IAM. Does the identity hold a role with the permission on that scope?
  4. Organization Policy and deny policies. Is a rule blocking the operation even though the role is present?
  5. Billing and APIs. Is billing linked? Is the API enabled?
  6. Quota. Is a limit reached?
  7. Audit log. What exactly did the platform record?
Rule of thumb. A message that names a permission (resourcemanager.projects.create) is an IAM problem. A message that names a constraint (constraints/…) is a policy problem. A message that names a quota or a limit is a quota problem. Read for the noun.

When to escalate

  • When the fix needs organization-level change: raise a pull request on the foundation code, do not change it in the console.
  • When billing is closed or suspended: contact the billing owner, not the platform team.
  • When a quota increase is declined: ask for a different region, or split the workload, and talk to Google Cloud support.

Common misunderstandings

  • "Owner on the project lets me create projects." No. Creation is checked on the parent (folder or organization).
  • "If the project is deleted, billing is still active." Billing stops with the shutdown, but a linked billing account still shows past charges.
  • "Undelete brings back everything." It restores the project. Check resources, IAM, billing link and keys afterwards.
A call failsread the whole error text Which noun is in the message?permission · constraint · billing · quota · state PermissionIAM role at theright scope? ConstraintOrg Policy or denypolicy in effect? Billinglinked, open,billing.user? Quotalimit reachedin project or region? Statedeleted, locked,liens, lifecycle? Always finish with the audit log Confirm the principal, method, scope and status code before and after the fix. Fix in code, not by hand.

Figure 1. Read the noun in the error message to pick the branch. Every branch ends in the audit log and a fix in the foundation code.

ACTIVEnormal operation delete DELETE_REQUESTEDshut down · billing stops recovery period ends Purgednot recoverable undelete during the recovery period ID stays reserved the whole time and after purge. A lien blocks deletion at the first arrow. After undelete: re-link billing, re-check IAM, keys and the state of each resource.

Figure 2. The life of a deleted project. The recovery window is the only time that restore is possible.

The animation shows one denied project creation, the audit record that explains it, and the retry after the cause was fixed. Watch the second and third steps: the denial is a policy decision recorded by the platform, which is why the audit log is the best first source of truth.

Commands for the five cases. Read commands are free. Write commands are marked and are free as well (metadata changes), unless a step says otherwise. IDs in the expected output are illustrative.

Case 1: gcloud logging read for denied project creation (read, free)

Purpose. Finds the failed call, the principal and the status in the audit log.

gcloud logging read 'protoPayload.methodName="CreateProject" AND protoPayload.status.code=7' --organization=ORG_ID --limit=3 --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.status.message)"
TIMESTAMP                 PRINCIPAL_EMAIL   MESSAGE
2026-11-25T09:14:02.451Z  dev@example.com   The caller does not have permission

Flags. --organization reads organization-level logs (needs roles/logging.viewer on the organization). Status code 7 is PERMISSION_DENIED. --limit caps results. --format="table(…)" selects fields.

Common errors. No output may mean the denial is stored at another level or you lack the viewer role. Try --folder=FOLDER_ID.

Case 1: who holds project creation? (read, free)

gcloud organizations get-iam-policy ORG_ID --flatten="bindings[].members" --filter="bindings.role=roles/resourcemanager.projectCreator" --format="table(bindings.role,bindings.members)"
gcloud resource-manager folders get-iam-policy FOLDER_ID --flatten="bindings[].members" --filter="bindings.role=roles/resourcemanager.projectCreator" --format="table(bindings.role,bindings.members)"
ROLE                                   MEMBERS
roles/resourcemanager.projectCreator   serviceAccount:sa-terraform-proj@SEED_PROJECT_ID.iam.gserviceaccount.com

Production use. Expect a service account and no individual users. Seeing domain:example.com means anyone in the domain can create projects.

Case 1: restrictive checks for policy (read, free)

gcloud org-policies list --organization=ORG_ID --format="table(constraint)"
gcloud org-policies describe constraints/gcp.resourceLocations --folder=FOLDER_ID --effective

Flags. --effective shows the policy after inheritance and merging. Hour 3 covers the commands in full. Check gcloud org-policies --help for flags in your SDK version.

Case 2: gcloud billing projects describe and re-link (read, then write, free)

gcloud billing projects describe PROJECT_ID
gcloud billing accounts list --filter="open=true" --format="table(name,displayName,open)"
gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
billingAccountName: ''
billingEnabled: false
name: projects/PROJECT_ID/billingInfo
projectId: PROJECT_ID

Common errors. Cloud billing quota exceeded (or a similar message) when linking means the billing account reached its limit of linked projects: ask the billing owner to request more, or use another account. The caller does not have permission means roles/billing.user is missing.

Case 3: gcloud compute networks list and removal of the default network (read, then write, free)

gcloud compute networks list --project=PROJECT_ID --format="table(name,subnet_mode,autoCreateSubnetworks)"
gcloud compute firewall-rules list --project=PROJECT_ID --filter="network:default" --format="table(name,direction,sourceRanges.list():label=SRC,allowed[].map().firewall_rule().list():label=ALLOW)"
NAME     SUBNET_MODE  AUTO_CREATE_SUBNETWORKS
default  AUTO         True

NAME                 DIRECTION  SRC            ALLOW
default-allow-icmp   INGRESS    0.0.0.0/0      icmp
default-allow-internal INGRESS  10.128.0.0/9   tcp:0-65535,udp:0-65535,icmp
default-allow-rdp    INGRESS    0.0.0.0/0      tcp:3389
default-allow-ssh    INGRESS    0.0.0.0/0      tcp:22

Remove it (only if nothing uses it):

gcloud compute firewall-rules delete default-allow-icmp default-allow-internal default-allow-rdp default-allow-ssh --project=PROJECT_ID
gcloud compute networks delete default --project=PROJECT_ID

Flags. The --filter and --format projections are long; if one fails in your SDK, use --format=json and read the fields. Rules must be deleted before the network. Deleting a network that has VMs fails.

Prevent it:

gcloud org-policies set-policy policy-skip-default-network.yaml
name: organizations/ORG_ID/policies/compute.skipDefaultNetworkCreation
spec:
  rules:
  - enforce: true

Common errors. The command needs roles/orgpolicy.policyAdmin. Setting it on the organization applies to new projects only. Existing default networks stay until deleted. Hour 3 covers this constraint.

Case 4: quota checks (read, free)

gcloud compute project-info describe --project=PROJECT_ID --format="yaml(quotas)"
gcloud compute regions describe REGION --project=PROJECT_ID --format="yaml(quotas)"
quotas:
- limit: 24.0
  metric: CPUS
  usage: 24.0
- limit: 500.0
  metric: SNAPSHOTS
  usage: 3.0

Flags. project-info shows global compute quotas; regions describe shows regional quotas such as CPUs. Other services have their own quotas; use the Quotas page in the console (IAM and Admin, Quotas and system limits) or the Service Usage API. Check gcloud --help for quota-related command groups in your SDK version; they are changing.

Common errors. RATE_LIMIT_EXCEEDED is an API request rate, not a resource quota; retry with back-off. New projects start with low default quotas. Request increases in advance.

Case 5: find, inspect and restore a deleted project (read, then write, free)

gcloud projects list --filter="lifecycleState:DELETE_REQUESTED" --format="table(projectId,name,lifecycleState)"
gcloud projects undelete PROJECT_ID
gcloud projects describe PROJECT_ID --format="value(lifecycleState)"
PROJECT_ID           NAME           LIFECYCLE_STATE
prj-lzlab-sbx-4821   LZ lab sandbox DELETE_REQUESTED

Undeleted project [PROJECT_ID].
ACTIVE

Common errors. Project … is not in a deleted state or a not-found error means the recovery period has ended or the project was never deleted. After undelete, billing is typically unlinked: re-link it and check resources and IAM.

Case 5: protect a project with a lien (write, free)

gcloud alpha resource-manager liens create --restrictions=resourcemanager.projects.delete --reason="Production landing zone project" --origin="platform-team" --project=PROJECT_ID
gcloud alpha resource-manager liens list --project=PROJECT_ID

Flags. A lien blocks projects delete until it is removed. The alpha track can change: check gcloud resource-manager liens --help and gcloud alpha resource-manager liens --help for the flags and the release track in your SDK version. Terraform's deletion protection on project resources is the preferred control in code.

Lab 8: break it, read it, fix it (about 10 minutes, free)

Goal. Reproduce two safe failures in the sandbox from Module 7 (billing not linked, and project deletion and recovery), diagnose each with the triage order, and fix them.

Prerequisites. The sandbox folder and project from Lab 7 (or recreate them with the commands of Module 7). roles/billing.user on the billing account. IDs in the expected output are illustrative.

Cost. Free. No metered resources are created. A budget sends alerts and does not cap spend.

  1. Break billing. Unlink the project and observe the symptom.
    gcloud billing projects unlink PROJECT_ID
    gcloud billing projects describe PROJECT_ID --format="value(billingEnabled)"
    False
  2. Diagnose. Try an operation that needs billing, for example enabling a paid service API. The error must mention billing.
    gcloud services enable compute.googleapis.com --project=PROJECT_ID
    Expected: an error stating that billing must be enabled for the project. If it succeeds, your project had billing or the API does not require it; use gcloud services enable bigquery.googleapis.com and read the response.
  3. Fix. Re-link billing and verify.
    gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
    gcloud billing projects describe PROJECT_ID --format="value(billingEnabled)"
    True
    Do not enable Compute Engine in this lab. If you did, delete the default network (Commands tab) and disable the API: gcloud services disable compute.googleapis.com --project=PROJECT_ID.
  4. Break the lifecycle. Delete the project and observe it.
    gcloud projects delete PROJECT_ID
    gcloud projects describe PROJECT_ID --format="value(lifecycleState)"
    DELETE_REQUESTED
  5. Diagnose. Find it in the list of deleted projects and read the audit log for the delete call.
    gcloud projects list --filter="lifecycleState:DELETE_REQUESTED AND projectId=PROJECT_ID"
    gcloud logging read 'protoPayload.methodName="DeleteProject" AND protoPayload.resourceName:"PROJECT_ID"' --folder=FOLDER_ID --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail)"
  6. Recover.
    gcloud projects undelete PROJECT_ID
    gcloud projects describe PROJECT_ID --format="value(lifecycleState,labels.env)"
    gcloud billing projects describe PROJECT_ID --format="value(billingEnabled)"
    ACTIVE	sandbox
    False
    Billing is False after the project came back: this is the lesson. Link it again if you plan to keep the project.
  7. Write the incident note. For each failure write: symptom, cause, command that proved it, fix, and the control that prevents it (project factory link step, lien, deletion protection, skipDefaultNetworkCreation).

Expected result. Both failures reproduced and fixed, and a short incident note.

Cleanup. Delete the budget, unlink billing, delete the project and the folder exactly as in Module 7. Confirm with gcloud projects list --filter="labels.env=sandbox".

Optional drill: policy-denied creation

If you have a lab folder where project creation is restricted, run gcloud projects create there with an account that lacks the role. Read the error text, then find the same event with gcloud logging read. Compare the error to the audit entry and explain which of the three gates (IAM, policy, billing) blocked the request.

Real cases

  • Everyone can create projects. An organization created in the first days of a company still had the default grant that let every domain user create projects and billing links. Two years later there were hundreds of unmanaged projects. The platform team removed the default grants, introduced a project factory with a pull request flow and a service account holding projectCreator, and migrated the unmanaged projects into folders in batches. The first message to users was a short guide on how to request a project.
  • Default networks in every project. A security review found open SSH from the internet in 300 projects because of default networks. The team first set compute.skipDefaultNetworkCreation, then scripted the deletion of default firewall rules and networks in projects with no instances, and reviewed the rest manually. Detection moved to a scheduled asset inventory query (Hour 6).
  • A destroy that removed a project. A Terraform change renamed a module. The plan showed a destroy and re-create of a production project, and it was applied without reading the plan closely. The project was restored with undelete within the recovery period, but the billing link, a service account key and an organization-level IAM grant had to be rebuilt. Afterwards the team added deletion_policy protection on project resources, a lien, and a rule that plans showing project destruction need a second approval.
  • Quota surprise at launch. A launch needed 200 CPUs in one region. The default quota was a fraction of that. The increase request took days. Capacity planning became a checklist item in the project factory request, with quota requests made at project creation.

Practices

  • Remove people from projectCreator and billing roles. Give the roles to a project factory service account and to groups for the few who need them.
  • Set constraints/compute.skipDefaultNetworkCreation before the first project is created, not after.
  • Put a lien (or Terraform deletion protection) on every production project and on the shared services projects.
  • Monitor quota usage and set an alert at about 80% of limits that matter (CPUs, IP addresses, API rates).
  • Practise recovery: run undelete in a sandbox once a quarter so the procedure is known before it is needed.
  • Keep an incident template with the five triage questions and the audit-log queries from this module.
Security note. A restored project may carry old IAM bindings, service account keys and permissive firewall rules. After any restore, review IAM, rotate or delete keys, and check network exposure before reconnecting workloads.
Cost note. A deleted project stops charges for its resources, but a mistaken delete followed by a restore can leave resources running with no billing owner. Re-link billing deliberately and check the billing report the next day.

Symptoms and first checks

SymptomLikely causeFirst check
PERMISSION_DENIED on projects createNo projectCreator on the parent, or wrong accountgcloud config list account; gcloud resource-manager folders get-iam-policy FOLDER_ID
Operation denied by org policy on creationA constraint blocks the call (location, creation restriction)Read the constraint name in the error; gcloud org-policies describe CONSTRAINT --folder=FOLDER_ID --effective
API error "billing must be enabled"Project not linked to an open billing accountgcloud billing projects describe PROJECT_ID
Linking billing failsMissing billing.user, closed account, project limit on the accountgcloud billing accounts list and the roles on the account
Open SSH and RDP rules in a new projectDefault network createdgcloud compute networks list; enforce skipDefaultNetworkCreation
Quota 'X' exceededProject or regional limit reachedgcloud compute regions describe REGION --format="yaml(quotas)"
Project "not found" for a project that existedDeleted, or you are using the wrong ID or accountgcloud projects list --filter="lifecycleState:DELETE_REQUESTED"
Cannot delete a projectA lien is presentgcloud alpha resource-manager liens list --project=PROJECT_ID
Restore works but workloads failBilling unlinked, APIs disabled, keys revokedRe-link billing, gcloud services list --enabled, review IAM

Triage order

  1. Identity: who made the call (gcloud auth list, impersonation flags, CI identity).
  2. Scope: project, folder or organization, and the parent chain.
  3. IAM: the role and the permission at that scope (gcloud policy-troubleshoot iam is covered in Hour 2).
  4. Organization Policy and deny policies: effective policy at the scope.
  5. Billing and APIs: link, open account, enabled services.
  6. Quota and rate limits.
  7. Lifecycle: deleted, liens, pending operations.
  8. Audit log: confirm, then fix in code and record the change.
or score ≥ 70% on the quiz

Command cheat sheet

Foundations: resource hierarchy, billing and identity
Hour 1

Hour 1 command cheat sheet

Commands for the resource hierarchy, billing, labels, tags, quotas and project lifecycle. Uppercase words are placeholders (ORG_ID, FOLDER_ID, PROJECT_ID, BILLING_ACCOUNT_ID). Every command here is a metadata operation. "Read" means it changes nothing. "Write" means it changes configuration; none of them creates a metered resource. Check gcloud … --help for the flags in your SDK version (gcloud CLI, current release channel).

Organization and hierarchy

CommandPurposeKey flagsGotcha
gcloud organizations listShow the organizations you can see (read)--format, --filter"Listed 0 items" means no organization or a missing permission, not an error
gcloud organizations describe ORG_IDShow one organization and its directory customer ID (read)--format="value(displayName)"Needs resourcemanager.organizations.get
gcloud resource-manager folders listList child folders of an organization or folder (read)--organization=ORG_ID or --folder=FOLDER_IDLists one level only, not the whole tree
gcloud resource-manager folders createCreate a folder (write)--display-name, --organization or --folderDisplay name must be unique among siblings; output shows an operation, the ID appears a moment later
gcloud resource-manager folders describe FOLDER_IDShow a folder and its parent (read)--format="value(parent)"IDs are numbers; do not include the folders/ prefix unless the command asks for it
gcloud resource-manager folders move FOLDER_IDMove a folder to another parent (write)--organization or --folderInherited policies and IAM change at once; review the effective policy before and after
gcloud resource-manager folders delete FOLDER_IDDelete an empty folder (write)none neededFails while active projects or folders remain inside

Projects

CommandPurposeKey flagsGotcha
gcloud projects create PROJECT_IDCreate a project (write)--folder or --organization, --name, --labelsThe ID is permanent, 6 to 30 characters, globally unique. Without a parent flag the project may land at the organization root or outside any organization
gcloud projects describe PROJECT_IDShow ID, number, parent, state and labels (read)--format="yaml(projectId,projectNumber,parent,labels)"Project number is different from the ID and is needed for tag bindings and budgets
gcloud projects listList and filter projects (read)--filter="parent.id=FOLDER_ID AND parent.type=folder", --filter="labels.env=dev"An empty result with no error means no match; keys are lowercase
gcloud projects update PROJECT_IDChange name or labels (write)--update-labels, --remove-labels, --clear-labels--clear-labels removes labels other teams rely on
gcloud projects move PROJECT_IDMove a project to a folder or organization (write)--folder or --organizationNeeds resourcemanager.projects.move on the project and create rights on the target. Check --help in your SDK
gcloud projects delete PROJECT_IDShut down a project (write)--quiet skips the promptRecoverable during the recovery period; the ID stays reserved
gcloud projects undelete PROJECT_IDRestore a deleted project (write)noneBilling is usually unlinked after a restore; check resources, IAM and keys
gcloud config set project PROJECT_IDSet the default project for later commands--installation not neededThe wrong default project is a classic cause of "wrong resource" errors; prefer --project in scripts

Billing and budgets

CommandPurposeKey flagsGotcha
gcloud billing accounts listList billing accounts you may use (read)--filter="open=true"Empty list means you lack roles/billing.user or higher on any account
gcloud billing projects describe PROJECT_IDShow the billing link of a project (read)--format="value(billingEnabled,billingAccountName)"billingEnabled: false means paid services will not work
gcloud billing projects link PROJECT_IDLink a project to a billing account (write)--billing-account=BILLING_ACCOUNT_IDNeeds billing.user on the account plus Owner-level billing permission on the project; accounts have a limit on linked projects
gcloud billing projects unlink PROJECT_IDRemove the link (write)noneStops paid resources in the project. Audit this action
gcloud billing budgets createCreate an alerting budget (write)--billing-account, --display-name, --budget-amount=20USD, --filter-projects, --threshold-rule=percent=0.5A budget alerts and does not cap spend. May need the Billing Budget API enabled in a quota project
gcloud billing budgets listList budgets of an account (read)--billing-accountCurrency must match the account currency when you create one
gcloud billing budgets delete BUDGET_IDDelete a budget (write)--billing-accountUse the last element of the budget name as the ID

Labels and tags

CommandPurposeKey flagsGotcha
gcloud projects update PROJECT_ID --update-labels=env=devAdd or change project labels (write)--update-labels=K=V,K2=V2Lowercase keys, up to 63 characters, no inheritance
gcloud resource-manager tags keys create envCreate a tag key (write)--parent=organizations/ORG_ID, --descriptionNeeds roles/resourcemanager.tagAdmin
gcloud resource-manager tags values create devAdd a value to a key (write)--parent=ORG_ID/envParent is the key's namespaced name
gcloud resource-manager tags bindings createAttach a tag value to a resource (write)--tag-value=ORG_ID/env/dev, --parent=//cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBERUse the project number, not the ID. Needs tagUser
gcloud resource-manager tags bindings listShow tags bound to a resource (read)--parent=…, --effective--effective includes inherited tags; check --help in your SDK
gcloud resource-manager tags keys deleteDelete a key (write)namespaced nameDelete bindings, then values, then the key

IAM and policy checks used in Hour 1

CommandPurposeKey flagsGotcha
gcloud organizations get-iam-policy ORG_IDSee who holds organization roles (read)--flatten="bindings[].members", --filter, --format="table(bindings.role,bindings.members)"Expect groups, not individuals; billing roles may be on the billing account instead
gcloud resource-manager folders get-iam-policy FOLDER_IDSee roles granted on a folder (read)same as aboveShows only that level, not inherited roles
gcloud org-policies list --organization=ORG_IDList constraints that have a policy (read)--folder, --projectCovered in Hour 3. A constraint not listed is not set at that level
gcloud org-policies describe CONSTRAINT --project=PROJECT_ID --effectiveShow the policy that actually applies (read)--effectiveWithout --effective you see only the policy set on that node

Quotas, services, logs

CommandPurposeKey flagsGotcha
gcloud services list --enabled --project=PROJECT_IDList enabled APIs (read)--format="value(config.name)"A new project has few APIs enabled; many need billing
gcloud services enable SERVICE.googleapis.comEnable an API (write)--projectSome APIs can start metered resources or create the default network (Compute Engine)
gcloud compute project-info describe --format="yaml(quotas)"Show global Compute quotas (read)--projectRequires the Compute Engine API; other services use the Quotas page
gcloud compute regions describe REGION --format="yaml(quotas)"Show regional quotas such as CPUs (read)--projectQuotas are per project and per region
gcloud logging read '…'Query audit log entries (read)--project, --folder, --organization, --limit, --formatAdmin Activity logs are on by default; creation events may be stored at the organization or folder level

Handy one-liners

# Where does this project live?
gcloud projects describe PROJECT_ID --format="value(parent.type,parent.id)"

# Projects missing the cost-center label
gcloud projects list --filter="NOT labels.cost-center:*" --format="value(projectId)"

# Deleted projects that can still be restored
gcloud projects list --filter="lifecycleState:DELETE_REQUESTED" --format="table(projectId,name)"

# Project number from ID
gcloud projects describe PROJECT_ID --format="value(projectNumber)"

# Who may create projects at the organization
gcloud organizations get-iam-policy ORG_ID --flatten="bindings[].members" \
  --filter="bindings.role=roles/resourcemanager.projectCreator" \
  --format="table(bindings.role,bindings.members)"

Rules worth remembering

  • Project ID: 6 to 30 characters, lowercase letters, digits, hyphens, starts with a letter, globally unique, never changes.
  • Labels: key and value up to 63 characters, lowercase, 64 labels per resource, not inherited, used in billing data.
  • Tags: Resource Manager objects, inherited, used by IAM conditions and policy, managed with tagAdmin and tagUser.
  • Budgets alert but never cap spend. Quotas are per project and region. Billing is linked per project.
  • Deleted projects are recoverable during the recovery period with gcloud projects undelete.
Before production. Flags and output fields change between gcloud CLI releases. Run gcloud components update in a test environment and re-check each command with --help before it goes into a pipeline. Pin the SDK version in your CI image.

Capstone lab and final quiz

Foundations: resource hierarchy, billing and identity
Hour 1

Capstone lab: a governed sandbox foundation, end to end

Goal. Build a small but complete Hour 1 foundation and prove it: a sandbox folder, two labelled projects (one "shared", one "application"), a Resource Manager tag, billing links, a budget with alert thresholds, a verification script, an audit check, and a full cleanup. The result is the minimum shape of a landing zone hierarchy, built by commands you can later move into Terraform (Hour 7).

Time. About 25 to 30 minutes. Cost. Free: no compute, storage or network resources are created. Budgets send alerts and do not cap spend. IDs in the expected output are illustrative.

Prerequisites

  • A sandbox organization (or a delegated sandbox folder) and a sandbox billing account that is open. Roles from Module 7: roles/resourcemanager.folderCreator, roles/resourcemanager.projectCreator, roles/billing.user on the account, and roles/billing.costsManager (or admin) for budgets. For the tag steps: roles/resourcemanager.tagAdmin and roles/resourcemanager.tagUser.
  • Cloud Shell, or a terminal with the gcloud CLI (current release channel) authenticated: gcloud auth list.
  • No organization? Skip the folder and tag steps (marked org only) and create the projects without --folder. The rest works.
  • No real secrets, keys or customer data are used. Do not create service account keys.

Step 0. Variables and preflight

export ORG_ID=123456789012
export BILLING_ACCOUNT_ID=0X0X0X-0X0X0X-0X0X0X
export SUFFIX=$(printf '%04d' $((RANDOM % 10000)))
export SHARED_ID=prj-cap-shared-$SUFFIX
export APP_ID=prj-cap-app-$SUFFIX
gcloud config list account --format="value(core.account)"
gcloud organizations list --format="value(ID)"
gcloud billing accounts list --filter="open=true" --format="value(name)"

Verify. Your account, your organization ID and the billing account appear. Expected output:

you@example.com
123456789012
billingAccounts/0X0X0X-0X0X0X-0X0X0X

Step 1. Budget first (safety net)

Create the budget before the projects. Projects do not exist yet, so scope it to the whole billing account if it is your sandbox account; otherwise create it in Step 5 with --filter-projects. If the sandbox account is shared with others, skip this step and do Step 5 only.

gcloud billing budgets create \
  --billing-account="$BILLING_ACCOUNT_ID" \
  --display-name="capstone-h1-budget-$SUFFIX" \
  --budget-amount=20USD \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --threshold-rule=percent=1.0

Verify.

gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:capstone-h1-budget-$SUFFIX" --format="value(displayName,amount.specifiedAmount.units,amount.specifiedAmount.currencyCode)"
capstone-h1-budget-4821	20	USD

Use your billing account's currency code if it is not USD. If a flag is rejected, check gcloud billing budgets create --help for your SDK version. If the API is not enabled, enable billingbudgets.googleapis.com in an admin project and pass --billing-project.

Step 2. Folder (org only)

gcloud resource-manager folders create --display-name="lz-capstone-$SUFFIX" --organization="$ORG_ID"
export FOLDER_ID=$(gcloud resource-manager folders list --organization="$ORG_ID" --filter="displayName=lz-capstone-$SUFFIX" --format="value(name)" | cut -d/ -f2)
echo "$FOLDER_ID"

Verify. A 12-digit number is printed. If it is empty, wait a few seconds and rerun the export line. Expected output:

555555555555

Step 3. Two labelled projects

gcloud projects create "$SHARED_ID" --name="Capstone shared" --folder="$FOLDER_ID" --labels=env=sandbox,app=shared,owner=your-name,cost-center=cc0000
gcloud projects create "$APP_ID"    --name="Capstone app"    --folder="$FOLDER_ID" --labels=env=sandbox,app=demo,owner=your-name,cost-center=cc0000

Verify. Both projects are active, under the folder, and carry four labels each.

gcloud projects list --filter="parent.id=$FOLDER_ID AND parent.type=folder" --format="table(projectId,lifecycleState,labels.env,labels.app,labels.cost-center)"
PROJECT_ID             LIFECYCLE_STATE  ENV      APP     COST_CENTER
prj-cap-shared-4821    ACTIVE           sandbox  shared  cc0000
prj-cap-app-4821       ACTIVE           sandbox  demo    cc0000

Without an organization, drop --folder and verify with gcloud projects list --filter="labels.owner=your-name".

Step 4. Link billing

gcloud billing projects link "$SHARED_ID" --billing-account="$BILLING_ACCOUNT_ID"
gcloud billing projects link "$APP_ID"    --billing-account="$BILLING_ACCOUNT_ID"

Verify.

for p in "$SHARED_ID" "$APP_ID"; do gcloud billing projects describe "$p" --format="value(projectId,billingEnabled)"; done
prj-cap-shared-4821	True
prj-cap-app-4821	True

Step 5. Scope a budget to the projects

If you skipped Step 1, or you want a per-project budget, create it now with the project numbers.

export SHARED_NUM=$(gcloud projects describe "$SHARED_ID" --format="value(projectNumber)")
export APP_NUM=$(gcloud projects describe "$APP_ID" --format="value(projectNumber)")
gcloud billing budgets create --billing-account="$BILLING_ACCOUNT_ID" --display-name="capstone-h1-projects-$SUFFIX" --budget-amount=10USD --filter-projects="projects/$SHARED_NUM" --filter-projects="projects/$APP_NUM" --threshold-rule=percent=0.5 --threshold-rule=percent=1.0

Verify. gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="table(displayName)" shows both capstone budgets (or one if you skipped Step 1). Check --help if repeating --filter-projects is rejected in your SDK version; some versions take a comma-separated list.

Step 6. A governance tag (org only)

gcloud resource-manager tags keys create env --parent=organizations/"$ORG_ID" --description="Environment classification"
gcloud resource-manager tags values create sandbox --parent="$ORG_ID/env"
gcloud resource-manager tags bindings create --tag-value="$ORG_ID/env/sandbox" --parent=//cloudresourcemanager.googleapis.com/projects/"$APP_NUM"

Verify.

gcloud resource-manager tags bindings list --parent=//cloudresourcemanager.googleapis.com/projects/"$APP_NUM"

Expected: one binding for tagValues/… (the sandbox value). If a tag key env already exists in your organization, reuse it instead of creating it and add only the value you need.

Step 7. Review who can do what (read only)

gcloud resource-manager folders get-iam-policy "$FOLDER_ID" --flatten="bindings[].members" --format="table(bindings.role,bindings.members)"
gcloud organizations get-iam-policy "$ORG_ID" --flatten="bindings[].members" --filter="bindings.role=roles/resourcemanager.projectCreator" --format="table(bindings.role,bindings.members)"

Check. Note whether individual users hold powerful roles. In the sandbox it is acceptable; write down what you would change in production (groups only, project creation through a factory).

Step 8. Verification script

pass() { echo "PASS  $1"; }; fail() { echo "FAIL  $1"; }
for p in "$SHARED_ID" "$APP_ID"; do
  [ "$(gcloud projects describe "$p" --format='value(lifecycleState)')" = "ACTIVE" ] && pass "$p active" || fail "$p active"
  [ "$(gcloud projects describe "$p" --format='value(parent.id)')" = "$FOLDER_ID" ] && pass "$p in lab folder" || fail "$p in lab folder"
  [ -n "$(gcloud projects describe "$p" --format='value(labels.cost-center)')" ] && pass "$p has cost-center" || fail "$p has cost-center"
  [ "$(gcloud billing projects describe "$p" --format='value(billingEnabled)')" = "True" ] && pass "$p billing enabled" || fail "$p billing enabled"
done
[ -n "$(gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:capstone-h1" --format='value(name)')" ] && pass "budget exists" || fail "budget exists"
PASS  prj-cap-shared-4821 active
PASS  prj-cap-shared-4821 in lab folder
PASS  prj-cap-shared-4821 has cost-center
PASS  prj-cap-shared-4821 billing enabled
PASS  prj-cap-app-4821 active
PASS  prj-cap-app-4821 in lab folder
PASS  prj-cap-app-4821 has cost-center
PASS  prj-cap-app-4821 billing enabled
PASS  budget exists

Without an organization the "in lab folder" lines print FAIL by design: skip them.

Step 9. Audit trail

gcloud logging read 'protoPayload.methodName="CreateProject"' --folder="$FOLDER_ID" --limit=2 --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"

Expected. Two rows with your principal. If nothing appears, retry with --organization="$ORG_ID" (the entry may be recorded at that level), or wait a minute. You need roles/logging.viewer on the scope you query.

Step 10. Break one thing and fix it (optional, 3 minutes)

gcloud billing projects unlink "$APP_ID"
gcloud billing projects describe "$APP_ID" --format="value(billingEnabled)"
gcloud billing projects link "$APP_ID" --billing-account="$BILLING_ACCOUNT_ID"
gcloud billing projects describe "$APP_ID" --format="value(billingEnabled)"
False
True

Expected final state

  • One folder with two active projects, each with env, app, owner and cost-center labels and billing enabled.
  • One or two budgets with thresholds at 50%, 90% and 100% (or 50% and 100%).
  • One tag key env with a sandbox value bound to the app project (organization only).
  • Nine PASS lines in the verification script and the creation entries in the audit log.

Cost

Free. The lab creates only metadata objects. Budgets send alerts and do not cap spend. If you enabled any API that creates resources (Compute Engine, for example), delete those resources first and check the billing report the next day.

Cleanup (in this order)

# 1. Tag objects (org only): bindings, values, key
gcloud resource-manager tags bindings delete --tag-value="$ORG_ID/env/sandbox" --parent=//cloudresourcemanager.googleapis.com/projects/"$APP_NUM"
gcloud resource-manager tags values delete "$ORG_ID/env/sandbox"
gcloud resource-manager tags keys delete "$ORG_ID/env"    # skip if the key existed before the lab

# 2. Budgets created by this lab
for b in $(gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:capstone-h1" --format="value(name)" | awk -F/ '{print $NF}'); do
  gcloud billing budgets delete "$b" --billing-account="$BILLING_ACCOUNT_ID"
done

# 3. Unlink billing and delete the projects
for p in "$SHARED_ID" "$APP_ID"; do
  gcloud billing projects unlink "$p"
  gcloud projects delete "$p" --quiet
done

# 4. Folder (when empty). If it fails because projects are pending deletion, leave it and retry later
gcloud resource-manager folders delete "$FOLDER_ID"

Verify the cleanup.

gcloud projects list --filter="labels.owner=your-name AND lifecycleState=ACTIVE" --format="value(projectId)"
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --filter="displayName:capstone-h1" --format="value(displayName)"

Both commands should print nothing. Projects in the DELETE_REQUESTED state can be restored with gcloud projects undelete during the recovery period.

Common problems in this lab

SymptomCauseFix
PERMISSION_DENIED creating a folder or projectMissing folderCreator or projectCreator on the parentAsk for the narrow role on the sandbox folder (not Organization Administrator)
Project ID already in useRandom suffix collided or ID is reservedChange SUFFIX and retry
Link failsNo billing.user, closed account, project limitCheck gcloud billing accounts list and the account's IAM
Budget command rejectedFlag name or currency--help for your SDK; match the billing currency
Folder delete failsChild projects still active or pending deletionWait or leave the empty folder; it is free

Next

Take the final quiz below. In Hour 2 you add least-privilege IAM to this hierarchy, and in Hour 7 you rebuild the same objects with Terraform and a project factory.

Knowledge check

Sources and versions

Foundations: resource hierarchy, billing and identity
Hour 1

Reference documentation for Hour 1

Primary sources for the resource hierarchy, billing, labels and tags, the foundations blueprint and project lifecycle. Read the page for the topic before you copy a command into a pipeline. Documentation changes, so the date of the page matters.

Resource hierarchy and projects

Labels and tags

Billing, budgets and quotas

Organization Policy

Landing zone and foundations blueprint

Identity (background for this hour)

Tool versions used in this hour

ToolVersion usedNotes
gcloud CLI (Google Cloud CLI)Current release channelCommands used are in the GA track except where marked alpha (liens). Run gcloud version and gcloud components update in a test environment
Terraform1.x with the Google provider (pin the major version in required_providers)Used for reading the blueprint in this hour and building in Hour 7
Cloud ShellManaged by GoogleComes with an authenticated gcloud CLI and Terraform; check the version it provides
terraform-example-foundationA release tag you chooseStage names and folder layout differ between releases

Before production

Check versions and flags. This course shows commands as they work in the gcloud CLI (current release channel) when it was written. Flags, output fields and API behaviour change. Before any command goes into a pipeline or a runbook: run it with --help in your SDK version, test it in a sandbox organization or folder, pin the SDK version in your CI image, and confirm the current behaviour in the documentation above. Illustrative IDs and outputs in this course are not real measurements.

Videos in this course are search links and official documentation only. No specific video is endorsed or guaranteed to be current.