Hour 6: Logging, monitoring, audit and cost governance
Hour 6: Logging, monitoring, audit and cost governance
A landing zone is only trustworthy if you can answer three questions at any time: what happened, are we being told, and what does it cost. This hour builds the evidence, alerting and spend controls that the earlier hours made necessary. Hour 1 gave you a hierarchy and a billing structure, Hour 2 gave you IAM, Hour 3 gave you guardrails, and Hours 4 and 5 gave you a network. Now you will record what happens in all of it and learn to read that record.
You start with Cloud Audit Logs, the platform's own record of who did what, and learn which of the four types are on by default and how long each is kept. You then follow a log entry through the Log Router, where sinks, buckets and exclusions decide where it is stored. Next you design the centralized pattern: an organization-level aggregated sink writing into a protected logging project, with a writer identity that is granted exactly one role. After that, Cloud Monitoring turns the signals into alerts that people receive.
The second half of the hour covers cost governance (budgets that alert but do not cap, billing export to BigQuery, labels for allocation), Cloud Asset Inventory for change history and drift reporting, a hands-on lab that ties the pieces together, and a module of production cases and troubleshooting for missing logs, silent sinks, alerts that never arrive and ingestion cost spikes.
Every module follows the same ten tabs: concepts, diagrams, a step-by-step animation, commands, a lab, production practice, troubleshooting and videos, and each module ends with a five-question quiz. Use the audio buttons to hear the key terms in English.
What you will be able to do
- Name the four Cloud Audit Log types, say which are on by default and for how long they are kept, and enable Data Access logs for one service on purpose.
- Read an audit entry with
gcloud logging readand find the principal, the method, the resource, the caller IP and the result. - Create a log bucket with its own retention, a sink with an inclusion filter and an exclusion, and verify that entries arrived.
- Design a central logging architecture with an organization sink using
--include-children, and grant the sink's writer identity the narrowest role on the destination. - Build a notification channel and a log-based alert for an audit event such as an IAM policy change.
- Create a budget with alert thresholds, explain why a budget does not stop spend, and find cost by label in a billing export.
- Search the resource inventory and export an asset snapshot to detect drift.
- Triage the four classic failures: missing logs, a sink without permission, an alert that is not received, and an ingestion cost spike.
Schedule (60 minutes)
What you need
- A Google Cloud sandbox: ideally an organization with a lab folder, but a single sandbox project works for every lab (see the setup page for the project-level alternatives).
- Access to the Billing account that pays for the sandbox, with
roles/billing.costsManagerorroles/billing.adminto create budgets. - The gcloud CLI (current release channel) or Cloud Shell, and an email address you can read for alert notifications.
- The IDs from Hour 1:
ORG_ID(if you have one),FOLDER_ID,PROJECT_IDandBILLING_ACCOUNT_ID.
What the labs create and what they cost
| Resource | Created in | Cost |
|---|---|---|
| Service accounts (to generate audit events) | Modules 1 to 4 | Free |
| Custom log buckets (30-day retention) | Modules 2, 3 and 7 | Low: only the few audit entries routed into them are billed |
| Log sinks (project-level, optionally organization-level) | Modules 2, 3 and 7 | Free to create |
| Notification channel and log-based alert policy | Modules 4 and 7 | Free |
| Budget with email alerts | Modules 5 and 7 | Free |
| Asset export to a Cloud Storage bucket (optional) | Module 6 | Low: a small bucket and a small file |
_Required log buckets, Data Access logs and long retention are billed by volume. The labs keep filters narrow and retention short, so the total is usually well under a few USD per day. Budgets send alerts and do not cap spend: set one before you start, and run every cleanup step at the end. Do not enable Data Access logs for all services, and do not create an organization sink in a shared organization without approval.Setup
Setup for Hour 6
This hour needs only a sandbox project for most labs. Organization-level steps are optional. Complete the checks below before you start Module 1, so the labs do not stall on access or billing.
1. Tools
- Google Cloud CLI (current release channel). Use Cloud Shell (no installation) or install the CLI locally and run
gcloud init. Update withgcloud components updateif a command in this hour is missing. A few monitoring commands are in thealphaorbetatracks, and the CLI may ask to install those components. - An email address you can read, for the alert channel and the budget notifications. Prefer a group address in a real environment.
- Optional: Terraform 1.x with the Google provider (pin the major version in
required_providers) if you want to translate the console steps into code later in Hour 7.
gcloud --version gcloud auth list gcloud config list --format="value(core.account,core.project)"
Google Cloud SDK 5xx.x.x
alpha 2026.xx.xx
beta 2026.xx.xx
core 2026.xx.xx
Credentialed Accounts
ACTIVE ACCOUNT
* ana@example.com
ana@example.com lz-lab-0001
Versions and IDs in the expected output are illustrative.
2. The sandbox project and the destination
Use a sandbox project that you are allowed to break. For the central logging labs, a second project is better: one acts as the producer and the other as the logging destination. If you only have one project, the labs still work with the sink and the bucket in the same project.
gcloud config set project PROJECT_ID gcloud projects describe PROJECT_ID --format="value(projectId,projectNumber,parent.id,lifecycleState)" gcloud services enable logging.googleapis.com monitoring.googleapis.com iam.googleapis.com cloudasset.googleapis.com cloudbilling.googleapis.com --project=PROJECT_ID
lz-lab-0001 123456789012 987654321098 ACTIVE Operation "operations/acf.p2-123456789012-…" finished successfully.
Enabling these APIs is free. Cloud Logging and Cloud Monitoring are enabled by default on most projects. Cloud Asset API is used in Module 6, and the Cloud Billing API is needed for budget commands.
3. Roles you need
| Task | Role | Scope |
|---|---|---|
| Read audit logs (Admin Activity, System Event) | roles/logging.viewer | Project (organization for organization-wide reads) |
| Read Data Access logs | roles/logging.privateLogViewer | Project |
| Create buckets, sinks and exclusions | roles/logging.configWriter | Project (organization for organization sinks) |
| Grant a sink's writer identity access | roles/resourcemanager.projectIamAdmin (or an equivalent) | Destination project |
| Create alerting policies and channels | roles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor (or roles/monitoring.editor) | Scoping project |
| Create and read budgets | roles/billing.costsManager or roles/billing.admin | Billing account |
| Search and export assets | roles/cloudasset.viewer (search) and roles/cloudasset.owner or equivalent for exports | Project, folder or organization |
In a sandbox the Owner role on the project covers all project-level rows. Billing roles are separate and are granted on the billing account, so confirm them first.
4. Billing and the budget (do this first)
gcloud billing accounts list gcloud billing projects describe PROJECT_ID
ACCOUNT_ID NAME OPEN MASTER_BILLING_ACCOUNT 0X0X0X-0X0X0X-0X0X0X Platform billing True billingAccountName: billingAccounts/0X0X0X-0X0X0X-0X0X0X billingEnabled: true name: projects/lz-lab-0001/billingInfo projectId: lz-lab-0001
If billingEnabled is false, link the project with gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID (Hour 1). Create a small budget on the sandbox before you run any lab; Module 5 shows the command. A budget sends alerts and does not cap spend. If you cannot see a billing account, ask the billing administrator for roles/billing.viewer on it and for a budget created on your behalf.
5. If you do not have an organization
- Audit logs and routing. Everything in Modules 1 and 2 works in a single project. In Module 3 use a project-level sink from the producer project to a log bucket in the logging project instead of an organization sink. The writer identity grant is identical.
- Organization sinks, folder sinks and
--include-children. These need an organization. Read the commands and answer the design questions on paper. - Monitoring. A metrics scope works with ordinary projects. Alerting, channels and log-based alerts do not need an organization.
- Budgets. They need a billing account, not an organization. If the billing account belongs to someone else, ask them to create the budget or to grant the role.
- Asset inventory. Use
--scope=projects/PROJECT_IDinstead of--scope=organizations/ORG_ID.
gcloud organizations list
Listed 0 items.
Listed 0 items. means that you work without an organization. This is a normal result for a personal account and does not block the labs.
6. Quick access checks
gcloud logging logs list --project=PROJECT_ID --limit=3 gcloud logging buckets list --project=PROJECT_ID gcloud logging sinks list --project=PROJECT_ID gcloud alpha monitoring channels list --project=PROJECT_ID
All four should return without a permission error (an empty list is fine). A PERMISSION_DENIED error names the missing permission: request the matching role from the table above. If gcloud alpha asks to install components, answer yes, or use the console for the monitoring steps.
7. Cleanup habit
Each module lab ends with a cleanup block. Keep a note of what you create, using a label or a name prefix such as lab- (for example lab-audit, lab-audit-sink), so you can find leftovers with gcloud logging buckets list, gcloud logging sinks list and gcloud logging metrics list at the end of the day.
_Default or _Required configuration of a shared project, or enable Data Access logs for all services without approval from the platform owner.Module 1 · Cloud Audit Logs
- Name the four audit log types, say which are on by default, and say how long each is kept.
- Read an audit log entry and find the principal, the method, the resource and the result.
- Query audit logs with
gcloud logging readand a filter, and enable Data Access logs for a service on purpose.
The short answer
Cloud Audit Logs are structured log entries that Google Cloud services write automatically for administrative actions and, if you enable them, for data access. They answer the audit question: who (principal) did what (method) on which resource, when, from where (caller IP) and with what result (status). They are part of Cloud Logging, so every tool you will meet in this hour (sinks, buckets, log-based metrics, alerts) works on them.
What: the four audit log types
| Type | Log ID (after cloudaudit.googleapis.com%2F) | What it records | On by default? | Stored in |
|---|---|---|---|---|
| Admin Activity | activity | API calls and actions that modify configuration or metadata (create a VM, set an IAM policy, change a firewall rule) | Yes, always. Cannot be disabled or excluded. | _Required bucket, 400 days, free |
| System Event | system_event | Google system actions that change resources, not a user call (for example a live migration) | Yes, always. Cannot be disabled or excluded. | _Required bucket, 400 days, free |
| Data Access | data_access | ADMIN_READ (read configuration), DATA_READ and DATA_WRITE (read or write user data) | No, except BigQuery. Must be enabled per service. | _Default bucket, 30 days by default, billed as ingestion |
| Policy Denied | policy | Requests denied because of a security policy (VPC Service Controls, IAM deny policies) | Yes. Cannot be disabled, but can be excluded from storage. | _Default bucket, 30 days by default, billed as ingestion |
The full log name has the form projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity. The same entries exist at folder and organization level for organization-level resources, for example organizations/ORG_ID/logs/cloudaudit.googleapis.com%2Factivity for a change to an organization policy.
How it works internally
- A caller sends a request to a Google Cloud API (console click,
gcloud, Terraform and client libraries all end up here). - The service authenticates and authorises the call with IAM, then runs it.
- The service writes an audit
LogEntrywith aprotoPayloadof typegoogle.cloud.audit.AuditLog. The payload includes the principal, the method, the resource, the request metadata and the status. - The entry reaches the Log Router. Sinks decide where copies go. The built-in
_Requiredsink stores Admin Activity and System Event logs; the_Defaultsink stores most other logs, including Data Access and Policy Denied.
Important fields in an entry:
| Field | Meaning |
|---|---|
protoPayload.authenticationInfo.principalEmail | Who made the call (user or service account) |
protoPayload.authenticationInfo.serviceAccountDelegationInfo | Impersonation chain when one identity acts as another |
protoPayload.serviceName | The API, for example iam.googleapis.com |
protoPayload.methodName | The operation, for example google.iam.admin.v1.CreateServiceAccount or SetIamPolicy |
protoPayload.resourceName | The target, for example projects/PROJECT_ID/serviceAccounts/… |
protoPayload.requestMetadata.callerIp | Source address of the call |
protoPayload.authorizationInfo[] | Each permission checked, with granted true or false |
protoPayload.status | Result; an empty status means success, code: 7 is PERMISSION_DENIED |
Why it is needed
- Security investigation. After an incident you need to reconstruct the sequence of calls.
- Compliance. Many standards require a retained record of administrative changes and of access to sensitive data.
- Operations. "Who deleted the firewall rule?" is answered in one query instead of a meeting.
- Detection. Log-based metrics and alerts (Module 4) are built on audit entries, for example an alert whenever an IAM policy changes.
When to enable Data Access logs
Data Access logs can be very large, because every read of every object may produce an entry. Enable them where the data or the permission is sensitive: Cloud KMS, Secret Manager, projects holding regulated data, IAM and Resource Manager reads (ADMIN_READ). For high-volume, low-risk services, keep them off or enable only DATA_WRITE. Use exempted members to skip known noisy service accounts. Set the choice in code, at organization or folder level when you want consistency, and budget for the ingestion.
What it is confused with
| Often confused with | Difference |
|---|---|
| Application logs | Written by your code or by agents on a VM. Audit logs are written by the platform about API calls, not about what your code did internally. |
| VPC Flow Logs, firewall logs | Network telemetry about packets and connections. Audit logs record API calls such as creating or changing a firewall rule, not the traffic itself. |
| Access Transparency logs | Record actions by Google personnel on your content. Audit logs record your own principals' actions. |
| Cloud Asset Inventory history | Shows what a resource looked like at a time (Module 6). Audit logs show who changed it and how. |
| Google Workspace or Cloud Identity audit logs | Sign-in, admin console and directory events. They live in the Admin console and Reports API; they can be shared to Cloud Logging, but they are not Cloud Audit Logs. |
Common misunderstandings
storage.objects.get by an attacker is invisible until Data Access logs are enabled for Cloud Storage, and nothing is back-filled.userAgent field shows the console or the tool._Required retention is fixed. If your regulation needs longer, or needs Data Access entries kept longer than the _Default 30 days, route a copy to a custom bucket or to Cloud Storage (Modules 2 and 3).Figure 1. From an API call to a stored audit entry. The Log Router decides which bucket or destination receives a copy.
Figure 2. Choose the log by the question. Most investigations begin with the activity log; the other three answer narrower questions.
Look at the first diagram from left to right: the same entry is created for every caller, and the only thing that changes is where the Log Router sends copies. Look at the second diagram when you write a filter: the log name is the cheapest way to narrow a query.
The animation follows a single administrative call from the engineer's terminal to the moment the entry is stored and read back. Watch step 2: the audit entry is produced by the platform, not by anything you installed, and step 5 shows why the base trail cannot be removed by a project owner.
All commands read logs unless marked as a write. Run them in Cloud Shell or any shell with the gcloud CLI (current release channel). Reading logs needs roles/logging.viewer (Admin Activity and System Event) or roles/logging.privateLogViewer (Data Access). Reading costs nothing beyond API quota. IDs in the expected output are illustrative.
gcloud logging read (Admin Activity for the last day)
Purpose. Shows the most recent administrative changes in a project.
gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"' \ --project=PROJECT_ID \ --freshness=1d \ --limit=5 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL METHOD_NAME RESOURCE_NAME 2026-11-25T09:14:03.118Z ana@example.com google.iam.admin.v1.CreateServiceAccount projects/lz-lab-0001/serviceAccounts/audit-demo@lz-lab-0001.iam.gserviceaccount.com 2026-11-25T08:51:40.502Z tf-platform@lz-boot.iam.gserviceaccount.com v1.compute.firewalls.patch projects/lz-lab-0001/global/firewalls/allow-iap
Flags. The first argument is the filter in the Logging query language. --freshness limits the age of entries (default is 1 day when you give no time filter in some versions, so state it). --limit caps the number of entries. --format picks fields; use json or yaml to see everything. Cost: free to read.
Common errors. An empty result with no error means the filter matched nothing (check the log name encoding %2F, the project and --freshness). PERMISSION_DENIED means you lack roles/logging.viewer. Invalid filter usually means a missing quote or a lowercase and; operators AND, OR, NOT must be uppercase.
gcloud logging read (who changed IAM policies, with the caller IP)
Purpose. Finds every SetIamPolicy call and shows the person, the caller IP and the target. This is the single most useful audit query in a landing zone.
gcloud logging read 'protoPayload.methodName:"SetIamPolicy" AND logName:"cloudaudit.googleapis.com%2Factivity"' \ --project=PROJECT_ID --freshness=7d --limit=20 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.requestMetadata.callerIp,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL CALLER_IP RESOURCE_NAME 2026-11-24T16:02:11.870Z ana@example.com 203.0.113.10 projects/lz-lab-0001 2026-11-22T10:31:45.004Z tf-iam@lz-boot.iam.gserviceaccount.com 198.51.100.7 folders/987654321098
Flags. The colon operator (:) means "contains", which matches names with a version prefix such as v1.compute.firewalls.patch. Production use. Run the same filter at organization level with --organization=ORG_ID (requires roles/logging.viewer on the organization) to see changes across all projects, and turn it into an alert in Module 4. Cost: free.
gcloud logging read (denied requests)
Purpose. Shows calls that failed with PERMISSION_DENIED or were blocked by a policy. Use it when a pipeline fails and the error text is unclear.
gcloud logging read 'protoPayload.status.code=7 OR logName:"cloudaudit.googleapis.com%2Fpolicy"' \ --project=PROJECT_ID --freshness=1d --limit=10 \ --format="table(timestamp,logName.basename(),protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.status.message)"
TIMESTAMP LOG_NAME PRINCIPAL_EMAIL METHOD_NAME MESSAGE 2026-11-25T09:30:12.001Z cloudaudit.googleapis.com%2Factivity dev@example.com v1.compute.instances.insert Required 'compute.instances.create' permission for 'projects/lz-lab-0001/zones/europe-west1-b/instances/vm1' 2026-11-25T09:05:44.700Z cloudaudit.googleapis.com%2Fpolicy build@lz-ci.iam.gserviceaccount.com google.storage.objects.get Request is prohibited by organization's policy. vpcServiceControlsUniqueIdentifier: …
Common errors. Code 7 is PERMISSION_DENIED; code 16 is UNAUTHENTICATED. The vpcServiceControlsUniqueIdentifier value is what you quote when you look up a VPC Service Controls violation (Hour 3).
gcloud logging logs list
Purpose. Lists which log IDs exist in a project, which tells you at a glance whether Data Access or Policy Denied entries have ever been written.
gcloud logging logs list --project=PROJECT_ID
NAME projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Factivity projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Fdata_access projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Fsystem_event
Cost: free. A log that never appears here has never received an entry in the retained window.
Enable Data Access logs (write, changes IAM policy)
Purpose. Adds an auditConfigs block to the project IAM policy so Cloud Storage records reads and writes. Cost: the command is free; the resulting log entries are billed as ingestion into the _Default bucket, so start with one service and watch the volume.
gcloud projects get-iam-policy PROJECT_ID --format=yaml > policy.yaml # Edit policy.yaml: add the block below at the top level, keep bindings and etag as exported. gcloud projects set-iam-policy PROJECT_ID policy.yaml
auditConfigs:
- service: storage.googleapis.com
auditLogConfigs:
- logType: ADMIN_READ
- logType: DATA_READ
- logType: DATA_WRITE
exemptedMembers:
- serviceAccount:backup-job@PROJECT_ID.iam.gserviceaccount.com
Updated IAM policy for project [lz-lab-0001].
auditConfigs:
- auditLogConfigs:
- logType: ADMIN_READ
- logType: DATA_READ
- logType: DATA_WRITE
exemptedMembers:
- serviceAccount:backup-job@lz-lab-0001.iam.gserviceaccount.com
service: storage.googleapis.com
bindings: …
etag: BwY…
Flags and risk. set-iam-policy replaces the whole policy. If the file has an old etag, the call fails with a conflict (good). If you remove bindings by mistake, access is removed (bad), so review the diff. Use allServices in service only when you accept the volume. The same auditConfigs form exists for gcloud organizations and gcloud resource-manager folders. In production, set it in Terraform with google_project_iam_audit_config (or the organization and folder versions), not by hand. Check gcloud projects set-iam-policy --help for the flags in your SDK version.
Lab: generate an audit event and read it back (about 10 minutes, free)
Goal. Create a harmless administrative event, find it in the Admin Activity log, and read the principal, method and resource fields.
Prerequisites. A sandbox project (PROJECT_ID) where you hold roles/iam.serviceAccountAdmin (or Owner) and roles/logging.viewer. The IAM API enabled (gcloud services enable iam.googleapis.com, free). A budget set first (Module 5 shows how; at minimum make sure you know which billing account pays for the project). No organization is needed.
- Confirm the identity and the project:
gcloud config list --format="value(core.account,core.project)". Set the project if needed withgcloud config set project PROJECT_ID. - Create a service account. This is an Admin Activity event. A service account without keys or role bindings has no permissions and no cost.
gcloud iam service-accounts create audit-demo --display-name="Audit lab demo" --project=PROJECT_ID
- Wait about a minute, then read the event:
gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount" AND protoPayload.resourceName:"audit-demo"' \ --project=PROJECT_ID --freshness=1h --limit=1 --format=json
- In the JSON, find and write down:
protoPayload.authenticationInfo.principalEmail,protoPayload.requestMetadata.callerIp,protoPayload.requestMetadata.callerSuppliedUserAgent,protoPayload.status(empty means success) andlogName. - Generate a denied event on purpose:
gcloud iam service-accounts delete nonexistent@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet. It fails because the account does not exist (NOT_FOUND, code 5), and the failed call is still recorded. Then run the query from the command tab withprotoPayload.status.code>0and find it. - Open Logs Explorer in the console, switch to the Query editor, paste the filter from step 3 and press Run query. Compare the console view with the JSON.
- Check whether Data Access logs exist:
gcloud logging logs list --project=PROJECT_ID. Note which ofactivity,data_access,system_event,policyare present, and explain why.
Expected result. One entry whose principalEmail is your account, methodName is google.iam.admin.v1.CreateServiceAccount, and resourceName ends with serviceAccounts/audit-demo@PROJECT_ID.iam.gserviceaccount.com. Another entry for the failed delete with a non-zero status code.
[
{
"logName": "projects/lz-lab-0001/logs/cloudaudit.googleapis.com%2Factivity",
"protoPayload": {
"authenticationInfo": { "principalEmail": "ana@example.com" },
"methodName": "google.iam.admin.v1.CreateServiceAccount",
"resourceName": "projects/lz-lab-0001/serviceAccounts/…",
"serviceName": "iam.googleapis.com"
},
"severity": "NOTICE"
}
]
Verification. If step 3 returns [], wait another minute (entries can take up to a few minutes), confirm the project with --project, and re-run with --freshness=1d.
Cost. Free. Admin Activity logs are not billed, a service account is free, and reading logs is free.
Cleanup.
gcloud iam service-accounts delete audit-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet
The deletion creates a further Admin Activity entry; that is expected and proves the trail records cleanup too.
Stretch (optional): Data Access on a test bucket
Enable DATA_READ and DATA_WRITE for storage.googleapis.com as in the command tab, create a bucket with gcloud storage buckets create gs://UNIQUE_BUCKET_NAME --location=REGION --uniform-bucket-level-access, upload a tiny file with gcloud storage cp, and read the data_access entries. The volume is tiny, so the cost is low (usually well under a few USD per day for this lab). Remove the audit config and delete the bucket afterwards. Budgets send alerts and do not cap spend.
Real cases (typical patterns)
- The deleted firewall rule. An ingress rule disappeared on a Friday and an application became reachable from the internet. The platform team ran a saved query on
v1.compute.firewalls.delete, found a service account used by a deployment pipeline, and traced it to a Terraform plan that nobody had reviewed. The fix was a pull-request gate, not a new log; the log made the diagnosis take minutes. - Data Access enabled everywhere. A team turned on
allServicesData Access logs for the whole organization to satisfy an auditor. Logging ingestion became the largest line of the monthly bill, driven by one batch job reading millions of objects. The corrected design enabled Data Access for KMS, Secret Manager, IAM and the regulated projects only, added exempted members for known batch identities, and kept a short retention in_Defaultwith a copy of the sensitive entries in a longer-lived bucket. - Investigation without a baseline. After a credential leak, a company could prove which administrative calls the stolen key had made, but not which objects it had read, because Data Access was off for Cloud Storage. The lesson recorded in their runbook: decide what you want to be able to answer before the incident, and enable the logs that answer it.
Practices
- Enable the Data Access types you need through code at organization or folder level, so new projects inherit them, and review the list every quarter.
- Route audit logs to a protected, central location (Modules 2 and 3), because a project owner can delete a project and its
_Defaultdata with it. - Use groups and service accounts with clear names, so
principalEmailtells a reviewer who or what acted. Shared accounts defeat the audit trail. - Tag impersonation: when a pipeline impersonates a service account, the entry shows the chain in
serviceAccountDelegationInfo. Teach reviewers to read it. - Keep a small set of tested queries in the incident runbook: IAM changes, organization policy changes, service account key creation, firewall and route changes, sink and exclusion changes, denied calls.
Security notes
roles/logging.admin, roles/owner) can change what is kept in the editable buckets. Give that role to a small group, alert on UpdateSink, DeleteSink and bucket updates, and keep a copy in a project that application teams cannot administer.roles/logging.privateLogViewer (needed for Data Access logs) sparingly, and use log views (Module 3) to scope access.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
gcloud logging read returns nothing for an action you know happened | Wrong log name encoding, wrong project, entry older than --freshness, or the entry is at folder or organization level | Run with only logName:"cloudaudit" and --freshness=1d; then try --organization=ORG_ID |
No data_access log exists | Data Access is not enabled for that service, or it was enabled recently | gcloud projects get-iam-policy PROJECT_ID --format="yaml(auditConfigs)" |
| Entry is found but the principal is a Google-owned account | A Google service agent or system performed the action on your behalf | Read serviceAccountDelegationInfo and the methodName; check System Event logs |
PERMISSION_DENIED reading Data Access logs | Missing roles/logging.privateLogViewer | gcloud projects get-iam-policy PROJECT_ID, filtered to your identity |
| Policy Denied entries are missing | An exclusion on _Default removes them, or no policy denied anything | gcloud logging sinks describe _Default and look at exclusions |
| Cannot find old entries after 30 days | Data Access and Policy Denied are kept 30 days in _Default | gcloud logging buckets describe _Default --location=global and check retentionDays |
set-iam-policy fails with a conflict | Stale etag because someone changed the policy after your export | Export again, merge the auditConfigs block, re-apply |
Triage order
- Confirm the scope: project, folder or organization, and the correct
--projector--organizationflag. - Confirm the log type and the exact log name (
%2Factivity,%2Fdata_access,%2Fpolicy,%2Fsystem_event). - Widen the time window, then narrow by
methodNameandresourceName. - If the entry should exist but does not, check whether the log was ever enabled and whether an exclusion or a short retention removed it.
- Read the
statusandauthorizationInfoof the entry to see which permission was checked and whether it was granted.
Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.
- YouTube search: Google Cloud audit logs, Admin Activity and Data Access
- YouTube search: Logs Explorer and the Logging query language
Official reading: Cloud Audit Logs overview · Configure Data Access audit logs · Logging query language.
Module 2 · Log routing
- Explain how the Log Router uses inclusion filters, exclusion filters and sinks to decide where each log entry is stored.
- Create a log bucket with a chosen retention and a sink that routes a filtered set of logs into it.
- State what
_Requiredand_Defaultare, what you can and cannot change, and where the cost comes from.
The short answer
Log routing decides where each log entry ends up. All entries go to the Log Router (日志路由器). The router tests every entry against every sink (日志接收器) in the resource that produced it. A sink has a destination, an inclusion filter (what to keep) and zero or more exclusion filters (what to drop from this sink). If the entry passes, a copy is written to the destination. One entry can therefore be stored in several places, each with its own retention and cost.
What: the building blocks
| Piece | What it is | You can change it? |
|---|---|---|
_Required bucket and sink | Holds Admin Activity, System Event and Access Transparency logs, 400 days, no ingestion charge | No. Not editable, no exclusions, retention fixed |
_Default bucket and sink | Holds every other log (application, Data Access, Policy Denied, platform logs); 30 days by default | Yes: retention, exclusions, or disable the sink |
| Custom log bucket | Your bucket with a location, retention, optional CMEK, optional Log Analytics, optional lock | Yes (location cannot change) |
| Sink | Routing rule: destination, filter, exclusions, writer identity | Yes |
| Log view | A saved filter over a bucket used to grant access to a subset of its entries | Yes |
Destinations
| Destination | Format of the destination argument | Writer role needed | Typical use |
|---|---|---|---|
| Log bucket | logging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_ID | roles/logging.bucketWriter | Central retention, Logs Explorer, Log Analytics |
| Cloud Storage | storage.googleapis.com/BUCKET_NAME | roles/storage.objectCreator | Cheap long-term archive, retention policy or lock |
| BigQuery dataset | bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID | roles/bigquery.dataEditor | SQL analysis, reports |
| Pub/Sub topic | pubsub.googleapis.com/projects/PROJECT_ID/topics/TOPIC_ID | roles/pubsub.publisher | Stream to a SIEM or another cloud |
| Another project's log bucket | same as log bucket | roles/logging.bucketWriter on the destination project | Central logging project (Module 3) |
How it works internally
- An entry is written to a resource, for example a project. It reaches the Log Router of that resource.
- For each sink on that resource the router evaluates the inclusion filter. If it does not match, the sink ignores the entry. If the filter is empty, the sink matches every entry (this is the
_Defaultsink shape). - If the entry matches, the sink's exclusion filters are evaluated. If any exclusion matches, the entry is dropped for this sink only (optionally sampled with
sample(insertId, 0.9)). - If the entry passes, the router writes it to the destination with the sink's writer identity.
- The destination applies its own storage rules: log bucket retention, Cloud Storage lifecycle or retention policy, BigQuery table expiration.
Every sink works independently. This is why you can keep audit logs in a locked bucket for years and, at the same time, drop DEBUG noise from _Default to control cost.
Retention and cost
- Ingestion. Entries stored in a log bucket other than
_Requiredare billed by volume ingested. Routing a copy to a second bucket means a second ingestion for that copy. Exclusions are the control that reduces the bill. - Storage and retention. Retention beyond the default period is billed by the volume kept. Choose the shortest retention that your rules and investigations require.
- Cloud Storage and BigQuery. Billed as normal storage and, for BigQuery, queries. A sink to Cloud Storage or BigQuery does not incur Logging ingestion for that copy; the destination service bills its own storage.
- Do not memorise prices. Use the pricing page and the Billing reports (Module 5) to measure.
When to use each approach
| Need | Approach |
|---|---|
| Keep audit logs longer than 30 days with search in the console | Custom log bucket (for example 365 days) plus a sink for cloudaudit logs |
| Prove logs were not tampered with for years | Cloud Storage with a retention policy, locked, or a locked log bucket |
| Analyse with SQL | Log bucket with Log Analytics enabled, or a BigQuery sink |
| Send to a SIEM | Pub/Sub sink and a subscriber |
| Cut noise cost | Exclusion on _Default (for example health checks, DEBUG) |
What it is confused with
| Often confused with | Difference |
|---|---|
| Exclusion filter vs inclusion filter | Inclusion says what the sink keeps; exclusion says what to remove from that selection. Both belong to the sink. |
| Log bucket vs Cloud Storage bucket | A log bucket is Cloud Logging storage that Logs Explorer and Log Analytics can query. A Cloud Storage bucket receives files exported by a sink. |
| Log views vs IAM on the bucket | A view narrows what a reader can see inside a bucket; IAM on the project decides who can read at all. |
| Retention vs lock | Retention sets how long entries are kept; locking a bucket makes the retention setting permanent. |
Common misunderstandings
Figure 1. One entry, several independent sinks. An audit entry can be stored in _Required, in a long-lived custom bucket and in a SIEM at the same time.
Figure 2. The two questions each sink asks. Read the first diagram for the big picture and this one when you write a filter.
Look at the fan-out on the first diagram: nothing in one sink depends on another. In the second diagram, note that a successful filter is not yet a successful write; the writer identity decides that.
The animation follows one ERROR entry through the Log Router. Each sink decides on its own, and each destination keeps its own copy with its own retention. Watch step 4, where the sink uses its writer identity, because that is the permission that most often breaks a new sink.
Most commands in this tab write configuration. Creating buckets and sinks is free; ingestion into non-_Required buckets is billed by volume, so keep filters narrow in labs. IDs in the expected output are illustrative. Roles: roles/logging.configWriter to create sinks and buckets, roles/logging.viewer to list.
gcloud logging buckets list and describe
Purpose. Shows the buckets of a project and their retention.
gcloud logging buckets list --project=PROJECT_ID gcloud logging buckets describe _Default --location=global --project=PROJECT_ID
LOCATION BUCKET_ID RETENTION_DAYS LIFECYCLE_STATE LOCKED global _Default 30 ACTIVE False global _Required 400 ACTIVE True createTime: '2026-11-01T08:00:00.123456789Z' lifecycleState: ACTIVE name: projects/lz-lab-0001/locations/global/buckets/_Default retentionDays: 30
Flags. --location is required for describe (use global unless you created a regional bucket). Column names can differ in your SDK version. Cost: free.
gcloud logging buckets create (write)
Purpose. Creates a custom log bucket with its own retention. Cost: creating it is free; entries ingested into it are billed.
gcloud logging buckets create audit-365 \ --location=global \ --retention-days=365 \ --description="Audit logs kept 365 days" \ --project=PROJECT_ID
Created bucket [audit-365]. createTime: '2026-11-25T09:40:02.000Z' description: Audit logs kept 365 days lifecycleState: ACTIVE name: projects/lz-lab-0001/locations/global/buckets/audit-365 retentionDays: 365
Flags. --location is where the data is stored and cannot be changed later; pick it with your data-residency rule (global or a region such as europe-west1). --retention-days sets how long entries are kept. Optional flags exist for CMEK, Log Analytics and locking; check gcloud logging buckets create --help for the flags in your SDK version.
Common errors. ALREADY_EXISTS when a bucket ID was used before and is in the 7-day deleted state (deleted buckets stay recoverable for a short period, and the ID is reserved). PERMISSION_DENIED needs logging.buckets.create.
gcloud logging buckets update (write)
Purpose. Changes retention of an existing bucket, including _Default.
gcloud logging buckets update _Default --location=global --retention-days=60 --project=PROJECT_ID
Updated bucket [_Default]. retentionDays: 60
Production use. Shortening retention does not instantly delete data in all cases, but entries older than the new period become eligible for deletion; plan a change window and confirm with legal. Lengthening is safe and billed from then on.
gcloud logging sinks create (write)
Purpose. Creates a sink that routes matching entries to the bucket.
gcloud logging sinks create audit-to-365 \ logging.googleapis.com/projects/PROJECT_ID/locations/global/buckets/audit-365 \ --log-filter='logName:"logs/cloudaudit.googleapis.com"' \ --description="Copy audit logs to the 365-day bucket" \ --project=PROJECT_ID
Created [https://logging.googleapis.com/v2/projects/lz-lab-0001/sinks/audit-to-365]. Please remember to grant `serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com` the Logs Bucket Writer role on the destination if it is in a different project.
Flags. The first argument is the sink name and the second is the destination. --log-filter is the inclusion filter. The printed writer identity is the principal to authorise on the destination. The message wording varies by SDK version. Cost: the sink is free; the bucket ingestion is billed.
Common errors. Invalid destination means the destination string does not match the expected format. Invalid filter means a syntax error such as an unbalanced quote.
gcloud logging sinks describe and list
Purpose. Shows the filter, destination, exclusions and writer identity.
gcloud logging sinks list --project=PROJECT_ID gcloud logging sinks describe audit-to-365 --project=PROJECT_ID
NAME DESTINATION FILTER
_Default logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/_Default NOT LOG_ID("cloudaudit.googleapis.com/activity") AND NOT LOG_ID("externalaudit.googleapis.com/activity") AND NOT LOG_ID("cloudaudit.googleapis.com/system_event") AND NOT LOG_ID("externalaudit.googleapis.com/system_event") AND NOT LOG_ID("cloudaudit.googleapis.com/access_transparency") AND NOT LOG_ID("externalaudit.googleapis.com/access_transparency")
_Required logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/_Required LOG_ID("cloudaudit.googleapis.com/activity") OR …
audit-to-365 logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/audit-365 logName:"logs/cloudaudit.googleapis.com"
createTime: '2026-11-25T09:41:10.000Z'
description: Copy audit logs to the 365-day bucket
destination: logging.googleapis.com/projects/lz-lab-0001/locations/global/buckets/audit-365
filter: logName:"logs/cloudaudit.googleapis.com"
name: audit-to-365
writerIdentity: serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com
The built-in sinks show that _Default is "everything except the logs that _Required keeps". Cost: free.
gcloud logging sinks update (write): add an exclusion on _Default
Purpose. Drops noisy low-severity entries from _Default to reduce ingestion.
gcloud logging sinks update _Default \ --add-exclusion=name=drop-debug,filter='severity<=DEBUG',description="Drop DEBUG entries" \ --project=PROJECT_ID
Flags. The exclusion has a name and a filter, and may carry a description or be disabled. Update flags differ between SDK versions; check gcloud logging sinks update --help. Warning. Never exclude cloudaudit.googleapis.com%2Fdata_access or %2Fpolicy entries you rely on for investigations without confirming a copy exists elsewhere.
gcloud logging read from a bucket
Purpose. Verifies that routed entries arrived.
gcloud logging read 'logName:"cloudaudit.googleapis.com"' \ --bucket=audit-365 --location=global --view=_AllLogs \ --project=PROJECT_ID --limit=3 --freshness=1d \ --format="table(timestamp,protoPayload.methodName)"
Flags. --bucket, --location and --view read from a specific bucket instead of the default view; _AllLogs is the view that shows every entry in the bucket. Cost: free.
google_logging_project_bucket_config, google_logging_project_sink, google_logging_organization_sink), review changes by pull request and alert on any manual change (Module 4).Lab: a custom bucket and a sink, verified end to end (about 15 minutes, low cost)
Goal. Create a log bucket with 30-day retention, route audit logs to it with a sink, generate an event and read it back from the bucket. IDs in the expected output are illustrative.
Prerequisites. A sandbox project (PROJECT_ID), roles/logging.configWriter and roles/logging.viewer, a budget in place (budgets send alerts and do not cap spend), and the gcloud CLI. No organization is required for a project-level sink.
- List the current buckets and sinks to see the baseline.
gcloud logging buckets list --project=PROJECT_ID gcloud logging sinks list --project=PROJECT_ID
- Create the bucket with a short retention. Short retention keeps the cost low.
gcloud logging buckets create lab-audit --location=global --retention-days=30 --project=PROJECT_ID
Verify:gcloud logging buckets describe lab-audit --location=global --project=PROJECT_ID --format="value(retentionDays)"must print30. - Create the sink for audit logs of this project.
gcloud logging sinks create lab-audit-sink \ logging.googleapis.com/projects/PROJECT_ID/locations/global/buckets/lab-audit \ --log-filter='logName:"logs/cloudaudit.googleapis.com%2Factivity"' --project=PROJECT_ID
Verify:gcloud logging sinks describe lab-audit-sink --project=PROJECT_ID --format="value(writerIdentity,destination)"prints aserviceAccount:service-…@gcp-sa-logging.iam.gserviceaccount.comidentity and the bucket path. - Generate an event and wait one to two minutes.
gcloud iam service-accounts create route-demo --project=PROJECT_ID
- Read the entry from the bucket, not from
_Defaultor_Required.gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \ --bucket=lab-audit --location=global --view=_AllLogs --project=PROJECT_ID --freshness=1h --limit=1 \ --format="value(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
- Add an exclusion to
_Defaultin the console: Logging, Log Router, the_Defaultsink, Edit sink, add exclusiondrop-debugwith filterseverity<=DEBUG. Confirm withgcloud logging sinks describe _Default --project=PROJECT_IDthat the exclusion is listed. This is metadata only. - Explain in your notes: which buckets hold the entry for the service account creation? (Answer:
_Requiredandlab-audit. It is not in_Default, because the_Defaultsink leaves out the activity log.)
Expected result. Step 5 prints one line with a timestamp, your email and the service account resource name. If your project already sends to the sink destination in another project, add the roles/logging.bucketWriter grant from Module 3; sinks to a bucket in the same project normally need no extra grant.
2026-11-25T10:02:41.554Z ana@example.com projects/lz-lab-0001/serviceAccounts/route-demo@lz-lab-0001.iam.gserviceaccount.com
Verification. No output after three minutes means a routing problem. Read the sink description, check the filter spelling, and look for sink errors: gcloud logging read 'protoPayload.serviceName="logging.googleapis.com" AND severity>=ERROR' --project=PROJECT_ID --freshness=1h.
Cost. Low (usually well under a few USD per day for this lab). Only the audit entries copied into lab-audit are billed as ingestion, and the volume is a handful of entries.
Cleanup.
gcloud logging sinks delete lab-audit-sink --project=PROJECT_ID --quiet gcloud logging buckets delete lab-audit --location=global --project=PROJECT_ID --quiet gcloud iam service-accounts delete route-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet
Deleted buckets go to a short recovery period, so the bucket ID is not reusable immediately. Remove the drop-debug exclusion from _Default if you do not want to keep it.
Real cases (typical patterns)
- The quiet exclusion. A cost-saving exclusion on
_Defaultused the filterseverity<WARNINGand, through a copy-paste, also matched the Data Access log for Secret Manager. Six months later an investigation found no read events. The remedy was a rule that every exclusion is a Terraform resource with a named reviewer, a test query showing what it drops, and a restriction that audit logs are routed by a separate non-excluded sink. - Retention by regulation. A financial team needed seven years of administrative records. They routed
cloudauditlogs to a Cloud Storage bucket with a locked retention policy, kept 400 days searchable in_Required, and kept 12 months searchable in a custom bucket with Log Analytics. Each layer had a purpose and cost. - Regional bucket for residency. A business unit with a data-residency rule created every bucket in a single region and used
gcp.resourceLocations(Hour 3) to prevent other regions. The bucket location was reviewed before the first entry was routed, because it cannot be changed.
Practices
- Leave the
_Requiredbucket alone and route a copy of audit logs to a project that only the logging team administers. - Set the
_Defaultretention deliberately. Thirty days is cheap but may be shorter than your incident-detection window. - Prefer inclusion filters on
logName,resource.typeandseverity. Broad filters like an empty one multiply ingestion. - Test every filter in Logs Explorer before saving it in a sink, and keep the tested query in the pull request.
- Use a naming standard for sinks and buckets such as
sink-audit-to-centralandbkt-audit-365. - Alert on changes to sinks and exclusions (Module 4).
Security notes
roles/editor for it.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Entries do not appear in the destination | Writer identity lacks permission, or the filter does not match | gcloud logging sinks describe SINK --format="value(writerIdentity)", then check IAM on the destination |
Entries missing from _Default that you expect | An exclusion filter, or the entry is in _Required (audit activity) | gcloud logging sinks describe _Default and read the exclusions |
Invalid destination when creating a sink | Wrong prefix or missing location in the bucket path | Compare with logging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_ID |
| Bucket cannot be reused after delete | The bucket is in the pending-deletion state | gcloud logging buckets list --location=global and look at LIFECYCLE_STATE |
| Cannot shorten or change a bucket | The bucket is locked, or you changed the location (not possible) | gcloud logging buckets describe BUCKET --location=LOCATION (check locked) |
| Ingestion cost rises after creating a sink | Broad filter copies a high-volume log a second time | Logs Explorer with the sink filter; check volume in the Logs Storage page |
| BigQuery sink creates no tables | Dataset in a different region than expected, or missing roles/bigquery.dataEditor | Read the sink error entries; check dataset IAM |
Triage order
- Is the entry produced at all? Search in Logs Explorer with a broad filter and a short window.
- Which sinks exist at this resource and at its parents (
gcloud logging sinks listwith--folderor--organization)? - Does the inclusion filter match the entry? Test the filter in Logs Explorer.
- Does an exclusion remove it? Read the sink's
exclusions. - Can the writer identity write at the destination? Check IAM and the destination's own rules (retention policy, dataset location, organization policy).
Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.
- YouTube search: Cloud Logging Log Router, sinks and exclusions
- YouTube search: Cloud Logging buckets, retention and Log Analytics
Official reading: Routing and storage overview · Configure and manage sinks · Configure log buckets.
Module 3 · Centralized logging architecture
- Design a central logging project and an organization-level aggregated sink that collects audit logs from every project.
- Grant the sink's writer identity the narrowest role on the destination and protect the destination with CMEK and restricted access.
- Explain Log Analytics and the main drivers of logging cost, and say what to do when there is no organization.
The short answer
A centralized logging architecture collects the logs that matter (above all audit logs) from every project into a small number of well-protected destinations, controlled by a platform or security team. The building block is an aggregated sink (聚合接收器): a sink created on the organization or on a folder with --include-children, so that logs from all projects below it follow one rule. The destination is usually a log bucket in a dedicated logging project.
What: the pieces
| Piece | Role |
|---|---|
Organization sink with --include-children | One routing rule for all current and future projects. New projects are covered automatically. |
Folder sink with --include-children | The same, limited to a subtree (for example only production), with its own retention or destination. |
Logging project (for example prj-logging) | Holds the central buckets, in the platform folder. Only the platform and security groups administer it. |
| Central log buckets | One bucket per purpose, such as org-audit (audit, long retention) and org-security (detections). Keep the bucket count small. |
| Writer identity grant | The sink's service account receives roles/logging.bucketWriter on the destination. |
| Log views and IAM | Decide who reads what: roles/logging.viewAccessor on a view, roles/logging.privateLogViewer for Data Access logs. |
| CMEK | Cloud KMS key that encrypts a bucket when policy requires customer-controlled keys. |
| Log Analytics | SQL over a bucket and optional linked BigQuery dataset. |
How it works internally
- You create the sink on the organization:
gcloud logging sinks create NAME DESTINATION --organization=ORG_ID --include-children --log-filter=.... - The service creates a unique writer identity for this sink, a service account such as
o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com. You read it withsinks describe. - You grant that identity
roles/logging.bucketWriteron the logging project. Until you do, the destination rejects the writes. - From then on, every matching entry in any project below the organization is also written to the central bucket. The original copy stays in the producing project's
_Requiredor_Defaultbucket, because the aggregated sink is non-intercepting by default. - With the
--intercept-childrenoption (checkgcloud logging sinks create --help) an aggregated sink can instead stop children from storing matching entries locally. Use it only with a deliberate design, because it changes what project owners can see and you can lose evidence if the sink breaks.
Why it is needed
- Tamper resistance. A project owner can delete a project and its logs. A central copy in another project survives.
- One view of the organization. Security investigates across projects with one query, instead of visiting dozens of projects.
- Consistency. A rule set once at the organization applies to new projects without a ticket.
- Separation of duties. The team that produces logs does not administer the team that retains them.
When to use which scope
| Situation | Design |
|---|---|
| You have an organization and a platform team | Organization sink to a central bucket; separate folder sinks if production needs a different retention or destination |
| One regulated folder (for example regulated data) | Folder sink with --include-children to a dedicated bucket in a dedicated region, plus the organization sink for the general case |
| No organization (a personal or small account) | A project-level sink in each project to a bucket in one logging project; the same grant steps apply, but there is no automatic coverage of new projects |
| You need a SIEM | Organization sink to a Pub/Sub topic in the logging project with a subscriber for the SIEM, in addition to the bucket |
Log Analytics
If you create the bucket with analytics enabled (or upgrade an existing bucket; check gcloud logging buckets create --help and update --help for --enable-analytics in your SDK version), you can run SQL in Logs Explorer, Log Analytics. You can create a linked dataset (gcloud logging links create) so BigQuery sees the bucket's data without a copy and without a second Logging ingestion. Analysts can join audit logs with other tables. This does not change retention, and it does not make the data free: ingestion is still billed once, and queries have their own cost model. Use it where analysis, not only search, is required.
CMEK for log buckets
Organizations with a key-control requirement encrypt buckets with a Cloud KMS key (Hour 3). The Cloud Logging service agent needs roles/cloudkms.cryptoKeyEncrypterDecrypter on the key. You can set a default key for the organization (gcloud logging settings update --organization=ORG_ID --kms-key-name=KEY; check the help for the flags in your SDK version) so that new buckets use it. If the key is disabled or destroyed, the logs become unreadable, so treat the key as part of the evidence chain: rotate, do not delete, and alert on key changes.
Cost drivers
| Driver | What increases it | Control |
|---|---|---|
| Ingestion into buckets | High-volume logs copied to extra buckets, Data Access logs, application DEBUG logs | Narrow inclusion filters, exclusions, enable only needed Data Access types |
| Retention | Long retention on high-volume buckets | Long retention only for the audit bucket; short for operational logs |
| Log Analytics and BigQuery | Repeated large queries; BigQuery storage of exports | Partitioned tables, query filters on time, a reservation or a budget alert |
| Cross-region transfer | Destination in a different region from the source | Check regional egress rules before choosing locations |
The principle: every copy is a cost and every copy is a risk. Route a copy only when someone has a use for it.
Common misunderstandings
roles/logging.configWriter on the organization.Figure 1. One organization sink collects audit logs from every project into the logging project. Producers keep their local copy; the central copy is protected by a separate trust boundary.
Figure 2. The four-step sequence for any cross-project sink. A new writer identity is created whenever a sink is recreated, so the grant must be part of the same code.
In the first diagram, follow the arrow from the application project: the producer never talks to the logging project directly. The writer identity does, which is why the application team needs no access there. In the second, note that verification reads from the destination.
The animation follows one audit entry from an application project to the central bucket. Pay attention to the fourth step: the IAM check on the logging project is the control that makes the central copy tamper-resistant, and the writer identity is the only principal that is allowed in.
Organization-level commands need an organization and roles/logging.configWriter on it. Creating a sink and a bucket is free; ingestion into the central bucket is billed by volume. IDs in the expected output are illustrative. Without an organization, use the project-level form shown in the Lab tab.
gcloud logging buckets create in the logging project
Purpose. Creates the central audit bucket with long retention and Log Analytics enabled.
gcloud logging buckets create org-audit \ --location=global \ --retention-days=400 \ --enable-analytics \ --description="Central audit logs" \ --project=LOG_PROJECT_ID
Created bucket [org-audit]. analyticsEnabled: true lifecycleState: ACTIVE name: projects/lz-logging/locations/global/buckets/org-audit retentionDays: 400
Flags. --enable-analytics turns on Log Analytics (check gcloud logging buckets create --help for your SDK version). Use a region instead of global if residency requires it; the location cannot be changed. Cost: the bucket is free to create; ingestion and retention are billed.
gcloud logging sinks create --organization --include-children
Purpose. Creates the aggregated sink for all audit logs of the organization.
gcloud logging sinks create org-audit-sink \ logging.googleapis.com/projects/LOG_PROJECT_ID/locations/global/buckets/org-audit \ --organization=ORG_ID \ --include-children \ --log-filter='logName:"logs/cloudaudit.googleapis.com"' \ --description="All audit logs to the central bucket"
Created [https://logging.googleapis.com/v2/organizations/123456789012/sinks/org-audit-sink]. Please remember to grant `serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com` the Logs Bucket Writer role on the destination.
Flags. --organization chooses the scope (use --folder=FOLDER_ID for a folder). --include-children includes every descendant. The filter limits the copy to audit logs, which controls cost. Common errors. PERMISSION_DENIED means you lack logging.sinks.create on the organization. Invalid destination means the project, location or bucket ID is wrong. Cost: free to create.
gcloud logging sinks describe (read the writer identity)
gcloud logging sinks describe org-audit-sink --organization=ORG_ID --format="value(writerIdentity)"
serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com
Purpose. Gives you the exact principal to authorise. Do not guess it; it is unique per sink and changes if you delete and recreate the sink. Cost: free.
gcloud projects add-iam-policy-binding (grant the writer)
Purpose. Lets the writer identity store entries in the logging project, restricted by a condition to one bucket.
gcloud projects add-iam-policy-binding LOG_PROJECT_ID \
--member="serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com" \
--role="roles/logging.bucketWriter" \
--condition='expression=resource.name.endsWith("locations/global/buckets/org-audit"),title=org-audit-writer-only'
Updated IAM policy for project [lz-logging].
bindings:
- condition:
expression: resource.name.endsWith("locations/global/buckets/org-audit")
title: org-audit-writer-only
members:
- serviceAccount:o123456789012-0001@gcp-sa-logging.iam.gserviceaccount.com
role: roles/logging.bucketWriter
etag: BwY…
version: 3
Flags. --condition adds an IAM Condition so the identity can write only to that bucket. Conditional bindings require policy version 3; gcloud handles this in current versions. Cost: free. Production use: in Terraform, use google_project_iam_member with a condition block, or google_logging_organization_sink outputs writer_identity.
gcloud logging links create (link a BigQuery dataset)
Purpose. Exposes the Log Analytics bucket as a read-only BigQuery dataset so analysts can query with their existing BigQuery tools.
gcloud logging links create audit_link \ --bucket=org-audit --location=global --project=LOG_PROJECT_ID
Flags. The link name becomes the dataset name; use letters, digits and underscores. Check gcloud logging links create --help for the flags in your SDK version. Cost: no extra ingestion; queries are billed by BigQuery.
gcloud logging settings describe (organization CMEK service agent)
gcloud logging settings describe --organization=ORG_ID
kmsServiceAccountId: service-org-123456789012@gcp-sa-logging.iam.gserviceaccount.com loggingServiceAccountId: service-org-123456789012@gcp-sa-logging.iam.gserviceaccount.com name: organizations/123456789012/settings
Purpose. Shows the service account that needs roles/cloudkms.cryptoKeyEncrypterDecrypter on the CMEK key. Output fields may differ by SDK version. Cost: free.
Lab: a central audit bucket with a project-level sink (about 20 minutes, low cost)
Goal. Build a miniature central logging design: one logging project, one bucket, one sink from another project, an explicit writer grant, and proof that an event arrives. If you have an organization, an extra step shows the organization form without changing the lab's cost. IDs in the expected output are illustrative.
Prerequisites. Two sandbox projects: LOG_PROJECT_ID (the logging project) and APP_PROJECT_ID (a producer), both with a billing account linked and a budget set first. You need roles/logging.configWriter on both, roles/resourcemanager.projectIamAdmin on LOG_PROJECT_ID, and roles/logging.viewer. No organization is needed; budgets alert and do not cap spend.
- Create the central bucket in the logging project.
gcloud logging buckets create central-audit --location=global --retention-days=30 --project=LOG_PROJECT_ID
Verify:gcloud logging buckets list --project=LOG_PROJECT_IDshowscentral-auditwith 30 days. - Create a project-level sink in the producer project that points at the central bucket.
gcloud logging sinks create central-audit-sink \ logging.googleapis.com/projects/LOG_PROJECT_ID/locations/global/buckets/central-audit \ --log-filter='logName:"logs/cloudaudit.googleapis.com%2Factivity"' --project=APP_PROJECT_ID
- Read the writer identity and store it in a shell variable.
WRITER=$(gcloud logging sinks describe central-audit-sink --project=APP_PROJECT_ID --format="value(writerIdentity)") echo "$WRITER"
Verify: the value starts withserviceAccount:and ends with@gcp-sa-logging.iam.gserviceaccount.com. - Test first without the grant: generate an event in the producer and look in the central bucket after two minutes.
gcloud iam service-accounts create central-demo --project=APP_PROJECT_ID gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \ --bucket=central-audit --location=global --view=_AllLogs --project=LOG_PROJECT_ID --freshness=1h --limit=1
Expected: no output, because the writer identity is not yet authorised. This shows the most common failure on purpose. - Grant the writer identity the bucket writer role on the logging project.
gcloud projects add-iam-policy-binding LOG_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter"
- Generate a second event and read again.
gcloud iam service-accounts create central-demo-2 --project=APP_PROJECT_ID gcloud logging read 'protoPayload.methodName="google.iam.admin.v1.CreateServiceAccount"' \ --bucket=central-audit --location=global --view=_AllLogs --project=LOG_PROJECT_ID --freshness=1h --limit=2 \ --format="value(timestamp,protoPayload.resourceName)"
- If you have an organization (optional, read-only): list organization sinks with
gcloud logging sinks list --organization=ORG_IDand describe any existing aggregated sink to see itsincludeChildrenvalue. Do not create an organization sink in a shared organization without approval.
Expected result. Step 4 prints nothing. Step 6 prints one line for central-demo-2 (and entries written after the grant). The first event, created before the grant, may be missing from the central bucket, which is the effect of the missing permission.
2026-11-25T11:20:08.771Z projects/lz-app-0002/serviceAccounts/central-demo-2@lz-app-0002.iam.gserviceaccount.com
Verification. Describe the sink and confirm the destination, then check IAM: gcloud projects get-iam-policy LOG_PROJECT_ID --flatten="bindings[].members" --filter="bindings.role=roles/logging.bucketWriter" --format="value(bindings.members)" must list the writer identity.
Cost. Low (usually well under a few USD per day for this lab). A handful of audit entries is copied into one bucket.
Cleanup.
gcloud projects remove-iam-policy-binding LOG_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter" gcloud logging sinks delete central-audit-sink --project=APP_PROJECT_ID --quiet gcloud logging buckets delete central-audit --location=global --project=LOG_PROJECT_ID --quiet gcloud iam service-accounts delete central-demo@APP_PROJECT_ID.iam.gserviceaccount.com --project=APP_PROJECT_ID --quiet gcloud iam service-accounts delete central-demo-2@APP_PROJECT_ID.iam.gserviceaccount.com --project=APP_PROJECT_ID --quiet
Real cases (typical patterns)
- The logging project that was an application project. A team reused an existing project as the central destination. Its owners could delete the bucket, and a developer with
roles/editorchanged retention. The rebuilt design used a new project in the platform folder, no basic roles, and an organization policy and alert on changes to its IAM policy. - One sink for everything. A first design routed every log of every project into one bucket with an empty filter. Cost grew with every new workload and nobody could find anything. The rebuilt design routed audit logs to one bucket, security product findings to another, and left application logs in each project's
_Defaultwith a 30-day retention; application teams used Logs Explorer in their own projects. - Key rotation and unreadable logs. A key for CMEK was scheduled for destruction during a cleanup because it looked unused. The bucket's logs would have become unreadable. The fix was a label and an alert on key lifecycle events, an organization policy limiting who can destroy keys, and a runbook that links the key to the evidence retention policy.
Practices
- Create a dedicated logging project in the
platformfolder, linked to a billing account that the platform team owns. - Use one organization sink for audit logs and separate sinks by purpose. Keep the filters in code and tested.
- Grant the writer identity the narrowest role on the destination, with a condition limiting it to one bucket.
- Give readers views and group-based roles, not project-wide viewer roles.
- Create the destination bucket and the grant before the sink in the pipeline, and verify with a canary event after every change.
- Alert on changes to sinks, buckets, retention, exclusions and CMEK keys of the logging project.
Security notes
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| No entries in the central bucket | Writer identity has no roles/logging.bucketWriter on the destination | sinks describe for the identity; get-iam-policy on the logging project |
| Entries only from some projects | Sink created without --include-children, or the project is outside the folder or organization scope | gcloud logging sinks describe NAME --organization=ORG_ID (look at includeChildren) |
| Writes stopped after a sink was recreated | A new sink has a new writer identity that was never granted | Compare the identity in describe with the member in the IAM policy |
| Logs unreadable or write errors on a CMEK bucket | Key disabled, destroyed or service agent lacks encrypt and decrypt | Key state in Cloud KMS; gcloud logging settings describe for the service agent |
| Ingestion cost jumped after the org sink | Filter too broad or Data Access enabled widely | Logs Storage page: volume by log name; test the filter in Logs Explorer |
| Readers see no entries in the central bucket | No view access, or Data Access logs need privateLogViewer | IAM roles on the bucket or view for the reader group |
| Sink creation denied | Missing roles/logging.configWriter at the organization or an organization policy blocks it | gcloud organizations get-iam-policy ORG_ID filtered to your group |
Triage order
- Confirm the sink scope and filter:
sinks describewith the right flag. - Confirm the writer identity and its role on the destination.
- Confirm the destination exists, is active and is in the expected location.
- Generate a canary event in a child project and read it from the destination.
- If CMEK is on, check the key and its permissions.
Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.
- YouTube search: Google Cloud aggregated log sinks at organization level
- YouTube search: Log Analytics and linked BigQuery datasets
Official reading: Aggregated sinks · Security foundations: operations · Log Analytics.
Module 4 · Cloud Monitoring
- Explain metrics scopes, metrics, alerting policies and notification channels, and how an incident is opened and closed.
- Create a notification channel and an alerting policy, including a log-based alert on an audit event such as an IAM policy change.
- Design a minimal landing-zone alert set that covers platform changes, budgets and the availability of one service.
The short answer
Cloud Monitoring (云监控) collects metrics, shows them in dashboards and raises alerts. In a landing zone it has two jobs. The first is platform health: availability of shared services (NAT, VPN tunnels, DNS, load balancers). The second is platform governance: being told when something that should rarely change does change (IAM, firewall, sinks, organization policy) or when spend crosses a threshold. Logs give the evidence; monitoring tells people to look at it.
What: the building blocks
| Concept | What it is |
|---|---|
| Metric | A time series of numbers, such as compute.googleapis.com/instance/cpu/utilization. Google Cloud services write system metrics automatically at no extra charge; custom and external metrics are billed. |
| Monitored resource | The thing a metric describes (VM instance, load balancer, project). Labels split a metric into series. |
| Metrics scope | The set of projects that one scoping project can view and alert on. Every project is its own scoping project by default. |
| Dashboard | A saved set of charts for a team or a service. |
| Alerting policy | Conditions + notification channels + documentation. Conditions can be metric threshold, metric absence, forecast, or log-match. |
| Notification channel | Email, SMS, Slack, mobile app, webhook, Pub/Sub, or an incident tool such as PagerDuty. |
| Incident | Opened when a condition is met, closed when it clears (or after an auto-close time for log alerts). |
| Uptime check | Synthetic probes of an HTTP(S), TCP or private endpoint from multiple regions. |
| Log-based metric | A metric computed from log entries (counter or distribution), usable in alerts and dashboards. |
| SLO | A service-level objective with an error budget, used for burn-rate alerting on important services. |
How it works internally
- Services and agents write time-series points to Cloud Monitoring (Google Cloud services automatically; VMs via the Ops Agent; applications via client libraries or Managed Service for Prometheus).
- An alerting policy is evaluated continuously against these points. A threshold condition checks an aligned value against a limit for a duration. An absence condition checks for missing data. A log-match condition watches the log stream for entries that match a filter.
- When a condition is met, an incident opens and the policy sends a notification to every attached channel. Documentation text in the policy is included, which is where the runbook link belongs.
- When the condition stops being met, the incident closes and, if configured, a "resolved" notification is sent. Log-match incidents close after an auto-close period.
The metrics-scope design for a landing zone
A common pattern uses one monitoring project (for example prj-monitoring in the platform folder) as the scoping project for shared platform projects, and a scoping project per environment or business unit for application projects. This keeps alert ownership clear. Add monitored projects with the console (Monitoring, Settings, Metrics Scope, Add projects) or with Terraform (google_monitoring_monitored_project). Check the current quota on the number of projects in one scope before you design around it. Grant roles/monitoring.viewer or roles/monitoring.editor on the scoping project, and use roles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor for people who manage alerts only.
Alerts every landing zone needs
| Signal | Type | Example filter or condition | Who is notified |
|---|---|---|---|
| IAM policy changed | Log-based | protoPayload.methodName:"SetIamPolicy" in the activity log | Security |
| Service account key created | Log-based | protoPayload.methodName="google.iam.admin.v1.CreateServiceAccountKey" | Security |
| Organization policy changed | Log-based | protoPayload.serviceName="orgpolicy.googleapis.com" (activity log) | Platform |
| Firewall or route changed | Log-based | protoPayload.methodName:("compute.firewalls.insert" OR "compute.firewalls.patch" OR "compute.firewalls.delete") | Network |
| Log sink or exclusion changed | Log-based | protoPayload.methodName:("UpdateSink" OR "DeleteSink" OR "UpdateExclusion") | Platform and security |
| Budget threshold reached | Budget notification (email or Pub/Sub) | Thresholds on actual and forecasted spend (Module 5) | Cost owner |
| Shared service availability | Uptime check or metric threshold | Probe failures from two or more regions | On-call |
| VPN tunnel down, NAT drops | Metric threshold or absence | Tunnel status, dropped_sent_packets_count | Network on-call |
| Log ingestion spike | Metric threshold | Logging bytes ingested per day vs a limit | Platform |
Keep the set small and meaningful. An alert that fires daily teaches the team to ignore alerts.
When to use what
| Question | Use |
|---|---|
| Is the service up from the outside? | Uptime check with an alert |
| Is a resource running hot or failing? | Metric threshold alert, dashboards |
| Did a job stop reporting? | Metric absence alert |
| Did someone change something critical? | Log-based alert on the audit entry |
| Are we spending too much? | Budget alerts (not a cap), billing export analysis |
| Is the user experience degrading? | SLO with burn-rate alerts |
What it is confused with
| Often confused with | Difference |
|---|---|
| Cloud Logging | Logging stores events. Monitoring stores numeric time series and sends alerts. They meet in log-based metrics and log-based alerts. |
| Security Command Center | SCC detects vulnerabilities and threats and creates findings. Monitoring alerts on metrics and logs you define. |
| Budget alerts | Budgets belong to Cloud Billing and use their own notifications; they can use Monitoring channels but are not Monitoring alerting policies. |
| Error Reporting, Cloud Trace, Profiler | Application diagnostics tools. They help find causes; they do not replace platform alerts. |
Common misunderstandings
Figure 1. Four sources, one alerting model. The alerting policy decides when something is an incident; the channel decides who hears about it.
Figure 2. A metrics scope. The scoping project holds alerting policies and channels; monitored projects only produce metrics.
Read the first diagram from the sources on the left: budgets are the only source that does not pass through the policy, and that is why you test them separately. In the second diagram, the arrow direction shows read access: the scoping project reads the monitored projects, and not the other way round.
The animation follows one platform event, an IAM policy change, from the audit entry to a person who is notified. Step 3 is the one that prevents alert storms: the notification rate limit. Step 6 shows that incidents close without manual work.
Alerting commands are in the alpha or beta release tracks in many SDK versions, and the console and Terraform are the stable way to manage them. Check gcloud alpha monitoring --help and gcloud beta monitoring --help for the commands and flags in your SDK version. Creating channels and policies is free; custom metrics and some log-based metrics can be billed. IDs in the expected output are illustrative.
gcloud logging metrics create (log-based metric)
Purpose. Counts audit entries that match a filter, so you can chart or alert on them.
gcloud logging metrics create iam-policy-changes \ --description="Count of SetIamPolicy calls" \ --log-filter='logName:"cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy"' \ --project=PROJECT_ID
Created [iam-policy-changes]. description: Count of SetIamPolicy calls filter: logName:"cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy" name: iam-policy-changes
Flags. --log-filter is the same Logging query language as for sinks. The metric counts from creation onward; it does not back-fill. The metric is visible as logging.googleapis.com/user/iam-policy-changes. Check gcloud logging metrics create --help for distribution metrics and labels. Cost: the metric is a user-defined metric; check the pricing page for chargeable metrics, and keep the label cardinality low.
gcloud logging metrics list and describe
gcloud logging metrics list --project=PROJECT_ID gcloud logging metrics describe iam-policy-changes --project=PROJECT_ID
Purpose. Confirms the filter that was saved. Cost: free.
gcloud alpha monitoring channels create (notification channel)
Purpose. Creates an email channel. Email channels must be verified by the recipient in the console before delivery is reliable.
gcloud alpha monitoring channels create \ --display-name="Platform ops email" \ --type=email \ --channel-labels=email_address=GROUP_EMAIL \ --project=PROJECT_ID
Created notification channel [projects/lz-monitoring/notificationChannels/1234567890123456789].
Flags. --type selects the channel kind (email, slack, pubsub, webhook_tokenauth and others); --channel-labels carries the type-specific labels. Slack channels need an OAuth step in the console. Use a group address, not a person, so rotations do not break delivery. Cost: free (SMS and some integrations depend on the provider). If the command is not found in your SDK version, create the channel in the console under Monitoring, Alerting, Edit notification channels.
gcloud alpha monitoring channels list
gcloud alpha monitoring channels list --project=PROJECT_ID --format="table(name,displayName,type,enabled)"
NAME DISPLAY_NAME TYPE ENABLED projects/lz-monitoring/notificationChannels/1234567890123456789 Platform ops email email True
Purpose. Gives you the channel resource name you place in the policy file. Cost: free.
gcloud alpha monitoring policies create --policy-from-file
Purpose. Creates a log-based alert that fires whenever an IAM policy change is written. Save the JSON as iam-alert.json, replacing PROJECT_ID and the channel ID.
{
"displayName": "IAM policy changed",
"combiner": "OR",
"conditions": [
{
"displayName": "SetIamPolicy audit entry",
"conditionMatchedLog": {
"filter": "logName:\"cloudaudit.googleapis.com%2Factivity\" AND protoPayload.methodName:\"SetIamPolicy\""
}
}
],
"alertStrategy": {
"notificationRateLimit": { "period": "300s" },
"autoClose": "604800s"
},
"notificationChannels": [
"projects/PROJECT_ID/notificationChannels/CHANNEL_ID"
],
"documentation": {
"content": "An IAM policy changed. Find the principal and the target with: gcloud logging read 'protoPayload.methodName:\"SetIamPolicy\"' --freshness=1h. Check the change ticket.",
"mimeType": "text/markdown"
}
}
gcloud alpha monitoring policies create --policy-from-file=iam-alert.json --project=PROJECT_ID
Created alert policy [projects/lz-monitoring/alertPolicies/9876543210987654321].
Flags. notificationRateLimit is required for log-match conditions and limits the notifications to one per period. autoClose closes the incident after the period with no new matches. Common errors. INVALID_ARGUMENT usually means a JSON typo, a missing rate limit, or a channel name from another project. The policy file shape can change between API versions; the console's View as JSON on an existing policy is the reference. Cost: free.
gcloud alpha monitoring policies list
gcloud alpha monitoring policies list --project=PROJECT_ID --format="table(displayName,enabled,combiner)"
Purpose. Lists policies so you can find and review them. Cost: free.
Uptime checks (console flow and Terraform)
Purpose. Probe an HTTPS endpoint from multiple regions. In the console: Monitoring, Uptime checks, Create uptime check; choose protocol HTTPS, the resource (URL or instance), the path, the frequency, the regions and the response validation; then use Create alert on the same page to attach a notification channel. In code, use google_monitoring_uptime_check_config with google_monitoring_alert_policy. Private endpoints need a private check with a Service Directory or VPC-based configuration; check the current documentation. Uptime checks are billed by the number of executions after a free allowance, so choose frequency and regions deliberately.
Lab: alert on an IAM change (about 15 minutes, free to low cost)
Goal. Create an email notification channel and a log-based alert policy for SetIamPolicy, trigger it with a harmless IAM change, and confirm that the incident opens and the email arrives. IDs in the expected output are illustrative.
Prerequisites. A sandbox project (PROJECT_ID), roles/monitoring.alertPolicyEditor and roles/monitoring.notificationChannelEditor (or roles/monitoring.editor), roles/logging.viewer, and an email address you can read. Budget set first (budgets alert and do not cap spend). No organization needed.
- Create the notification channel. If the alpha command is not available, use the console.
gcloud alpha monitoring channels create --display-name="Lab email" --type=email --channel-labels=email_address=YOUR_EMAIL --project=PROJECT_ID gcloud alpha monitoring channels list --project=PROJECT_ID --format="value(name)"
Verify: the second command printsprojects/PROJECT_ID/notificationChannels/NUMBER. Copy it. Check your mailbox for a verification email and accept it if one arrives. - Save the JSON policy from the Commands tab as
iam-alert.jsonand replace the channel line with the value from step 1. Keep"period": "300s". - Create the policy.
gcloud alpha monitoring policies create --policy-from-file=iam-alert.json --project=PROJECT_ID
Verify:gcloud alpha monitoring policies list --project=PROJECT_ID --format="table(displayName,enabled)"shows IAM policy changed withTrue. - Trigger the alert with a harmless, reversible change: create a service account and bind a harmless role on it to yourself, which writes
SetIamPolicy.gcloud iam service-accounts create alert-demo --project=PROJECT_ID gcloud iam service-accounts add-iam-policy-binding alert-demo@PROJECT_ID.iam.gserviceaccount.com \ --member="user:YOUR_EMAIL" --role="roles/iam.serviceAccountViewer" --project=PROJECT_ID
- Confirm the audit entry exists.
gcloud logging read 'protoPayload.methodName:"SetIamPolicy" AND protoPayload.resourceName:"alert-demo"' \ --project=PROJECT_ID --freshness=1h --limit=1 --format="value(timestamp,protoPayload.authenticationInfo.principalEmail)"
- Open Monitoring, Alerting in the console. Within a few minutes an incident named after the policy should appear, and an email should arrive. Open the incident and read the documentation text.
- Write down the delay between the change and the email. This is your detection time for this signal.
Expected result. One open incident for IAM policy changed and one email. If the entry exists but there is no incident, the policy filter does not match; compare it with the entry's methodName.
2026-11-25T12:41:07.220Z ana@example.com
Verification. gcloud alpha monitoring policies describe POLICY_NAME --project=PROJECT_ID shows the condition and the channel. In the console, the policy page lists the channel as Verified.
Cost. Free for the channel and the policy. Log-match alerts do not create custom metric charges, and the audit entries are not billed. Total: free to low.
Cleanup.
gcloud alpha monitoring policies delete POLICY_NAME --project=PROJECT_ID --quiet gcloud alpha monitoring channels delete CHANNEL_NAME --project=PROJECT_ID --quiet gcloud iam service-accounts delete alert-demo@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID --quiet
Use the full names from the list outputs for POLICY_NAME and CHANNEL_NAME. Closing the open incident in the console is optional; it auto-closes.
Real cases (typical patterns)
- The silent policy change. An organization-level IAM change granted a broad role to a contractor group. There was no alert, and the change was found in a quarterly review. After the incident the security team added log-based alerts for IAM, organization policy, service account key and sink changes, notification to a team channel, and a rule that each alert has an owner and a documented response.
- Alert fatigue. A platform team created dozens of CPU alerts for every project. Pages arrived at night and were ignored. The redesign kept a few symptom-based alerts (service unavailable, VPN tunnel down, error budget burning) paged to on-call, and moved the rest to dashboards and daily reports.
- Budget alert nobody read. A budget notified a former employee. Costs rose for six weeks. The fix was a group email address, a Pub/Sub notification that posts to the team's chat tool, and a quarterly check that every channel still reaches a person.
Practices
- Create a monitoring project in the
platformfolder as the scoping project for shared services, and give each environment its own scoping project. - Alert on symptoms that need a human (platform changes, outages, burning budgets), not on every metric.
- Always use group addresses and shared channels; test them quarterly with a real notification.
- Put a runbook link and the first command to run into the policy documentation.
- Manage alerts and channels in Terraform, review changes, and alert on changes to the monitoring configuration itself.
- Define severity levels so the channel matches the urgency (page, chat, email).
Security notes
roles/monitoring.admin and roles/monitoring.alertPolicyEditor, and alert on changes to alerting policies and channels through a log-based alert.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Incident opened, no notification | No channel attached, channel unverified, or sent to a mailbox nobody reads | Policy page: Notifications section; channel status |
| Log-based alert never fires | Filter does not match the entry, wrong log name, or entry is at another resource | Run the filter in Logs Explorer against a known event |
INVALID_ARGUMENT creating a policy from a file | JSON typo, missing notificationRateLimit for a log condition, channel from another project | Validate JSON, compare with console View as JSON |
| Dashboard is empty for a project | The project is not in the metrics scope | Monitoring, Settings, Metrics Scope |
| Alert fires constantly | Threshold too low, duration too short, or noisy source | Chart the metric for a week and set the threshold above normal |
| Uptime check shows failures from one region only | Regional network issue, firewall allowlist missing the probe addresses | Check the uptime check IP ranges against your firewall or Cloud Armor policy |
| Cost increase after custom metrics | High-cardinality labels or too many time series | Metrics Management page: volume by metric |
Triage order
- Is the signal produced? Check the metric or the log entry directly.
- Does the condition match it? Compare the filter, the aligner and the duration with the data.
- Is an incident open? Check the Alerting page.
- Is a channel attached, enabled and verified, and does it reach a person?
- Is the policy in the right scoping project and enabled?
Video content changes often, so the links below are search pages rather than pinned videos. Check the date against the documentation version you use.
- YouTube search: Cloud Monitoring alerting policies and notification channels
- YouTube search: log-based alerts on audit logs
- YouTube search: metrics scope for multiple projects
Official reading: Alerting overview · Metrics scopes · Log-based alerts · Uptime checks.
Module 5 · Cost governance
- Create and inspect a Cloud Billing budget with threshold rules, and explain why a budget alerts but does not cap spend.
- Describe how billing export to BigQuery and resource labels let you allocate cost to teams and environments.
- Choose between budget alerts, quotas, and automation for the different kinds of cost risk in a landing zone.
The short answer
Cost governance (成本治理) means three things working together: visibility (who spent what, by project, label and SKU), warning (the right people are told before the invoice arrives), and limits (some spend is blocked by quotas, policy or automation). In Google Cloud the first two are provided by Cloud Billing; the third is something you design.
What: the building blocks
| Building block | What it does | Does it stop spend? |
|---|---|---|
| Billing account | Pays for linked projects; holds budgets, exports and permissions (roles/billing.admin, roles/billing.user, roles/billing.viewer) | Unlinking a project from it stops paid usage, but that is a drastic manual action |
| Budget | Watches actual or forecasted spend and notifies at thresholds | No. Alerts only |
| Billing export to BigQuery | Writes standard usage cost, detailed usage cost and pricing data to datasets | No. Reporting only |
| Labels | Key and value pairs on projects and resources, carried into cost rows | No. Attribution only |
| Quotas | Per-project limits on API calls and resources | Yes, for the quota metric you limit |
| Organization Policy | Blocks classes of resources, for example gcp.resourceLocations or external IP creation | Yes, for what the constraint forbids |
| Commitments (CUD) | Lower unit rate in exchange for a one or three year commitment | No. It lowers cost, and adds a commitment you must use |
Why budgets are not caps
Google Cloud bills usage after it happens, so the platform cannot know at the moment of a request whether the budget will be exceeded. A budget is therefore evaluated periodically against reported spend, and billing data can lag by hours. A burst of expensive usage can pass the 100 percent mark before any alert is delivered. For this reason a landing zone treats a budget as an early-warning sensor and builds the actuators separately.
How a budget works internally
- Scope. A budget belongs to a billing account. Its scope can be the whole account, or filtered by projects, services, labels, or credits handling.
- Amount. A fixed amount for a period (usually a calendar month), or last period's spend.
- Threshold rules. A list of percentages of the budget amount, each based on actual spend or forecasted spend. The usual set is 50, 90 and 100 percent actual plus 100 or 110 percent forecast.
- Notifications. By default, email to Billing Account Administrators and Users. You can add Cloud Monitoring notification channels (email, chat, webhook) and a Pub/Sub topic that receives a JSON message for automation.
The Pub/Sub message contains fields such as budgetDisplayName, alertThresholdExceeded, costAmount, costIntervalStart, budgetAmount, budgetAmountType and currencyCode. A subscriber can read these and take action, for example posting to a chat room, opening a ticket, or reducing a quota.
Billing export to BigQuery
The export is configured once per billing account in the console (Billing, then Billing export). There are three datasets of interest:
- Standard usage cost: daily aggregated cost by project, service, SKU, labels and credits. Start here.
- Detailed usage cost: includes resource-level identifiers (for example a VM instance ID). Larger, and needed for per-resource analysis.
- Pricing: list price data, useful for comparing your rates with list prices.
The export starts from the day it is enabled and does not back-fill past months, so enable it on day one of a new landing zone. Use a dedicated billing project and dataset, give finance roles/bigquery.dataViewer on the dataset, and keep it in a location that matches your data residency rules.
Labels for allocation
Labels are set on projects and many resources. Cost rows carry labels (resource labels) and project.labels (project labels). A standard landing-zone label set is small: env, cost-center, owner, app, data-class. Labels are lowercase keys, up to 63 characters, with limited characters. Enforce them where projects are created (Hour 7 covers the project factory) and measure the share of cost with no cost-center label as a monthly governance metric.
Commitments and discounts
Committed use discounts (承诺使用折扣) are one or three year commitments. Resource-based commitments reserve vCPU and memory in a region; spend-based commitments commit to an hourly spend on a service family. Sustained use discounts are automatic for some older machine families; check the documentation for your machine type. FinOps practice is: first right-size and remove waste (Recommender reports idle resources), then commit to the stable baseline, and leave the variable part on demand. Do not buy a commitment to hide a workload nobody owns.
When to use which control
| Risk | Best control |
|---|---|
| Slow growth nobody noticed | Budget with 50, 90, 100 percent actual rules, reviewed monthly with the billing export |
| Fast runaway (a loop, a crypto-mining intrusion, an open endpoint) | Quotas, Organization Policy (no external IPs, allowed locations), forecast alerts, and a Pub/Sub automation for the worst case |
| Who should pay? | Labels and billing export; separate billing accounts only when legal entities differ |
| Steady baseline workload | Committed use discount sized from export data |
| Test projects forgotten | Sandbox folder with auto-expiry automation and a low budget |
What it is confused with
| Often confused | Difference |
|---|---|
| Budget vs quota | A budget notifies about money; a quota enforces a limit on usage of an API or resource. |
| Billing report vs billing export | The console report is for browsing; the export is the data you query, join and archive. |
| Label vs tag (Resource Manager tag) | Labels feed billing and filtering. Tags drive IAM conditions and Organization Policy. Module 5 of Hour 1 compares them. |
| Cloud Billing budget vs Monitoring alert | The budget evaluates billing data; a Monitoring alert evaluates metrics and logs in near real time. Use both. |
Figure 1. Cost data flow. The budget is a sensor. Only the automation on the right (or a quota) can reduce spend.
Figure 2. Choose the control from the risk. A single budget does not cover all four rows.
Look at Figure 1 from left to right: usage becomes cost in the billing account, then splits into reporting (export) and warning (budget). The only red box is the one that can change behaviour. In Figure 2, notice that "fast runaway" is the row where a budget alone is not enough.
The player follows one month of usage: metering, export to BigQuery, a threshold crossing, and the Pub/Sub message that automation can act on. Note that the last step is the only one that can change spend, and it is code you wrote, not the budget.
Budget commands need the Cloud Billing Budget API (billingbudgets.googleapis.com) and permission on the billing account (roles/billing.admin or billing.budgets.* permissions). The commands below only create metadata objects, so they are free. Check gcloud billing budgets create --help for the flags in your SDK version.
gcloud billing accounts list
Purpose. Find the billing account ID you will attach the budget to. Free, read-only.
gcloud billing accounts list --format="table(name,displayName,open)"
NAME DISPLAY_NAME OPEN billingAccounts/0X0X0X-0X0X0X-0X0X0X Platform billing True
Flags. --format picks the columns. Common error. An empty list means your identity has no billing role. In production the billing account is managed by a small group with roles/billing.admin, and engineers get roles/billing.viewer or billing.user only on what they need.
gcloud services enable billingbudgets.googleapis.com
Purpose. Enable the Budget API on the project that makes the call (the quota project). Free.
gcloud services enable billingbudgets.googleapis.com --project=PROJECT_ID
Operation "operations/acf.p2-123456789012-example" finished successfully.
Common error. API [billingbudgets.googleapis.com] not enabled on project on the next command. Enable it and retry after a short wait.
gcloud billing budgets create (write, free metadata)
Purpose. Create a monthly budget for one project with actual and forecasted threshold rules. It sends alerts only.
gcloud billing budgets create \ --billing-account=BILLING_ACCOUNT_ID \ --display-name="lz-lab-monthly" \ --budget-amount=50USD \ --filter-projects=projects/PROJECT_ID \ --calendar-period=month \ --threshold-rule=percent=0.5 \ --threshold-rule=percent=0.9 \ --threshold-rule=percent=1.0 \ --threshold-rule=percent=1.0,basis=forecasted-spend
Created budget [billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/11111111-2222-3333-4444-555555555555].
Flags. --budget-amount=50USD sets a specified amount (use --last-period-amount to base it on the previous period instead). --filter-projects restricts the scope; without a filter the budget covers the whole billing account. --calendar-period=month resets monthly. Each --threshold-rule is a fraction of the amount; basis=forecasted-spend uses the forecast instead of actual spend. The amount in a lab should be small and in the billing account currency.
Common errors. PERMISSION_DENIED: you need budget permissions on the billing account, not only on the project. currency mismatch: the amount currency must match the billing account currency.
Cost. Free. Production use. Budgets are created by Terraform (google_billing_budget) in the project factory, one per project or per team, with a Pub/Sub topic and Monitoring channels attached.
gcloud billing budgets create with notifications (write, free metadata)
Purpose. Add a Pub/Sub topic so that automation receives the JSON message, and a Monitoring notification channel so that people receive alerts outside the default billing email recipients.
gcloud billing budgets create \ --billing-account=BILLING_ACCOUNT_ID \ --display-name="prod-folder-monthly" \ --budget-amount=2000USD \ --filter-projects=projects/PROJECT_ID \ --threshold-rule=percent=0.9 \ --threshold-rule=percent=1.0,basis=forecasted-spend \ --notifications-rule-pubsub-topic=projects/PROJECT_ID/topics/budget-alerts \ --notifications-rule-monitoring-notification-channels=projects/PROJECT_ID/notificationChannels/CHANNEL_ID
Flags. --notifications-rule-pubsub-topic names the topic, which must exist and be writable by Cloud Billing. --notifications-rule-monitoring-notification-channels takes channel resource names (list them with gcloud beta monitoring channels list). Check --help for the exact flags available in your release, including --disable-default-iam-recipients.
gcloud billing budgets list and describe
Purpose. Audit the budgets on an account. Free, read-only.
gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID gcloud billing budgets describe BUDGET_ID --billing-account=BILLING_ACCOUNT_ID
---
amount:
specifiedAmount:
currencyCode: USD
units: '50'
budgetFilter:
calendarPeriod: MONTH
creditTypesTreatment: INCLUDE_ALL_CREDITS
projects:
- projects/987654321098
displayName: lz-lab-monthly
name: billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/11111111-2222-3333-4444-555555555555
thresholdRules:
- spendBasis: CURRENT_SPEND
thresholdPercent: 0.5
- spendBasis: CURRENT_SPEND
thresholdPercent: 0.9
- spendBasis: CURRENT_SPEND
thresholdPercent: 1.0
- spendBasis: FORECASTED_SPEND
thresholdPercent: 1.0
Note. The budget filter shows the project number, not the project ID. IDs in the expected output are illustrative.
gcloud projects update --update-labels (write, free metadata)
Purpose. Add allocation labels to a project so that the cost rows carry them from now on.
gcloud projects update PROJECT_ID --update-labels=env=lab,cost-center=cc1234,owner=platform-team gcloud projects describe PROJECT_ID --format="value(labels)"
{'cost-center': 'cc1234', 'env': 'lab', 'owner': 'platform-team'}
Common error. Label values with uppercase letters or spaces are rejected. Production use. Set labels in the project factory so that no project exists without them.
Query the billing export with bq query (read; BigQuery query cost applies)
Purpose. Cost by project and label for the current month. The export table name contains your billing account ID with dashes replaced by underscores.
bq query --use_legacy_sql=false --project_id=BILLING_PROJECT_ID '
SELECT
project.id AS project_id,
(SELECT value FROM UNNEST(labels) WHERE key = "cost-center") AS cost_center,
ROUND(SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0)), 2) AS net_cost
FROM `BILLING_PROJECT_ID.billing_export.gcp_billing_export_v1_0X0X0X_0X0X0X_0X0X0X`
WHERE invoice.month = FORMAT_DATE("%Y%m", CURRENT_DATE())
GROUP BY project_id, cost_center
ORDER BY net_cost DESC
LIMIT 20'
+-----------------+-------------+----------+ | project_id | cost_center | net_cost | +-----------------+-------------+----------+ | prj-app-a-prod | cc1234 | 812.40 | | prj-app-b-prod | NULL | 233.05 | | prj-sandbox-01 | cc9999 | 4.12 | +-----------------+-------------+----------+
Notes. NULL in cost_center is the unlabeled cost you must drive to zero. Credits are negative amounts, so the net cost adds them. Query cost depends on bytes scanned; always filter on invoice.month or a partition column, and keep the export dataset in a project with its own budget. Table and column names follow the documented export schema; check the schema page for your export type. Numbers in the output are illustrative.
Lab 5: budget with forecast alert and an allocation label (about 12 minutes, free)
Goal. Create a small monthly budget on a sandbox project, confirm that the label and threshold rules are stored as expected, and read the structure of the billing export query without running up cost.
Prerequisites.
- A sandbox project
PROJECT_IDlinked to a billing accountBILLING_ACCOUNT_ID. Never use a production billing account for a training lab. - Permission to create budgets on that billing account (
roles/billing.admin, or a custom role withbilling.budgets.create) androles/resourcemanager.projectIamAdminorroles/owneron the sandbox project to set labels. - If you have only a personal billing account, the steps still work; skip step 7 if no export is configured.
Cost. Free. Creating a budget and a label are metadata operations. IDs in the expected output are illustrative.
- Set variables and confirm the identity.
export PROJECT_ID=PROJECT_ID export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID gcloud config set project "$PROJECT_ID" gcloud auth list --filter=status:ACTIVE --format="value(account)"
Verify: the account printed is the one you intend to use. - Confirm the project is linked to the billing account.
gcloud billing projects describe "$PROJECT_ID" --format="value(billingAccountName,billingEnabled)"
billingAccounts/0X0X0X-0X0X0X-0X0X0X True
Verify:True. If it isFalse, link it:gcloud billing projects link "$PROJECT_ID" --billing-account="$BILLING_ACCOUNT_ID". - Enable the Budget API.
gcloud services enable billingbudgets.googleapis.com --project="$PROJECT_ID"
Verify:gcloud services list --enabled --filter="name:billingbudgets"shows the service. - Label the project for allocation.
gcloud projects update "$PROJECT_ID" --update-labels=env=lab,cost-center=cc0000,owner=you gcloud projects describe "$PROJECT_ID" --format="value(labels)"
Verify: all three labels appear. - Create the budget.
gcloud billing budgets create \ --billing-account="$BILLING_ACCOUNT_ID" \ --display-name="lz-lab-monthly" \ --budget-amount=20USD \ --filter-projects="projects/$PROJECT_ID" \ --calendar-period=month \ --threshold-rule=percent=0.5 \ --threshold-rule=percent=0.9 \ --threshold-rule=percent=1.0,basis=forecasted-spend
Verify: the command printsCreated budget [...]. Use the currency of your billing account in place ofUSDif it differs. - Read the budget back and check the rules.
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-monthly 20 USD
Verify:lz-lab-monthlyis listed. Then rundescribewith the budget ID and count three threshold rules (two actual, one forecast). - (Optional) Read the export. In the console open Billing, Billing export, and note whether BigQuery export is on. If it is, run the cost-by-label query from the commands tab on the billing project, using the real table name from the dataset. Verify: the sandbox project appears, or the result is empty because the project is new.
Expected result. One budget named lz-lab-monthly scoped to the sandbox project, three threshold rules, and a project that carries env, cost-center and owner labels.
Cleanup.
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(name,displayName)" gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"
Keep the labels (harmless). Module 7 reuses the budget idea, so you may keep this budget until the end of the hour and then delete it.
Real cases (typical, not named customers)
- The forgotten GPU. An experiment left a large accelerator VM running over a long weekend in a project that had no budget. The next month the invoice was the first signal. The fix was layered: a sandbox folder with a low budget on every project, Organization Policy that restricts allowed machine types in the sandbox, a Pub/Sub function that posts to a chat room at 90 percent actual and at 100 percent forecast, and a weekly report of resources older than seven days.
- Unattributable shared costs. A platform team ran a shared network project and a shared logging project, and finance could not charge them back. The team labeled projects with
cost-centerandowner, enabled the billing export, and added a monthly allocation rule: shared costs are split by each team's share of directly attributable spend. The unlabeled share was published monthly and fell from a large figure to under a few percent in two quarters. - Premature commitment. A group bought a three-year commitment sized on a peak week. After a migration the baseline dropped and part of the commitment went unused. The correction was a rule: commitments are proposed by FinOps from at least three months of export data, cover a conservative share of the steady baseline, and are reviewed quarterly.
Practices
- Create a budget for every project at creation time (Terraform project factory), with 50, 90 and 100 percent actual and 100 percent forecast rules.
- Send alerts to a group alias and a shared channel, not to one person's mailbox. A person on leave must not be the single recipient.
- Enable billing export on day one, to a dedicated project that only the platform and finance groups can read.
- Make labels mandatory in the project factory and report the unlabeled cost each month.
- Set quotas on expensive APIs and use Organization Policy to remove risky options (external IPs, unlimited regions) in non-production folders.
- Review the Recommender idle-resource and rightsizing recommendations each month before buying any commitment.
- Keep one owner for each budget: a budget with no owner becomes noise.
Security notes
- Billing data reveals business activity. Grant
roles/billing.viewerand BigQuery dataset access to groups, not individuals, and review them with the access reviews from Hour 2. - A sudden cost spike is often a security signal (leaked service account key, compromised workload). Route the budget Pub/Sub topic to the security team as well as to FinOps, and read the audit logs from Module 1 when a spike has no change record.
- The billing account is itself a resource with its own IAM policy. Audit who holds
roles/billing.adminand log changes to it.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
PERMISSION_DENIED creating a budget | The role is on the project, not on the billing account | gcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID and look for your identity |
API [billingbudgets.googleapis.com] not enabled | Budget API disabled on the quota project | gcloud services list --enabled --filter="name:billingbudgets" |
| Budget exists but nobody got an email | Only default IAM recipients are used and they are not on the account, or the mail was filtered | Describe the budget, check the notification rules, and add a Monitoring channel or Pub/Sub topic |
| Pub/Sub topic receives nothing | Topic in a different project without publisher rights, wrong topic name, or no threshold has been crossed yet | Check the topic name in describe output, then the topic IAM policy |
| Spend passed 100 percent before any alert | Billing data lag, or only the 100 percent rule exists | Add 50, 90 and forecast rules; add quotas for fast runaways |
Cost rows show no cost-center label | Label added after the usage, or resource-level label missing | Query for NULL labels in the export and fix them at the project factory |
| Export dataset is empty | Export enabled recently (no back-fill) or dataset location mismatch | Billing, Billing export in the console; wait up to a day for the first rows |
| Currency error when creating a budget | Amount currency differs from the billing account currency | Check the billing account currency in the console, then repeat the amount in that currency |
Triage order
- Is it a money question or a permission question? Run
gcloud billing projects describe PROJECT_IDto confirm the billing link. - List budgets and read the threshold rules and notification settings.
- Check the Pub/Sub topic and subscription for the message, and the subscriber logs.
- For a cost spike, query the export by service and SKU for the last seven days, then find the project and resource.
- Read the Admin Activity audit log for the project for the same period (Module 1) to find who created the resource.
Video content changes often, so these are search pages. Check the video date against the current documentation for budgets and billing export.
- YouTube search: Google Cloud billing budgets and alerts
- YouTube search: billing export to BigQuery and FinOps
- YouTube search: committed use discounts explained
Official reading: Create, edit, or delete budgets and budget alerts · Export Cloud Billing data to BigQuery · Programmatic budget notifications.
Module 6 · Asset inventory and change history
- Search resources and IAM policies across an organization with Cloud Asset Inventory and read the result fields.
- Export a point-in-time snapshot of assets to Cloud Storage or BigQuery, and explain how snapshots support drift reporting.
- Create an asset feed that publishes changes to Pub/Sub, and distinguish feeds, history and audit logs.
The short answer
Cloud Asset Inventory (云资产清单) is a metadata service. It keeps an index of resources and IAM policies for an organization, a folder or a project, and lets you search it, export a snapshot, look at a history window, and receive feeds of changes. It does not read your data (no objects, no table rows), and it is not a log. It answers questions such as "which buckets are public?", "which projects have an external IP?", "who has Owner anywhere in this folder?" and "what changed since last Friday?"
What it contains
| Content type | What you get | Typical use |
|---|---|---|
| Resource | Resource metadata: name, type, location, labels, state, and the resource's own fields | Inventory, label compliance, finding unlabeled cost |
| IAM policy | The allow policy attached to each resource | Who holds privileged roles, external members, allUsers bindings |
| Organization Policy | Policies attached to resources | Show where constraints are set |
| Access policy | Access Context Manager policies and perimeters (organization scope) | VPC Service Controls review |
| Relationship | Links between assets (for example, an instance and its disks) | Impact analysis |
The four capabilities
- Search (
search-all-resources,search-all-iam-policies): interactive queries with a query language, results paged, eventually consistent within a short time of a change. - Export (
gcloud asset export): a batch snapshot at a time you choose (including a recent past time), delivered to Cloud Storage or BigQuery. Use it for reports and drift. - Feeds (
gcloud asset feeds create): near real-time change events to Pub/Sub for the assets and content types you pick. - History (
gcloud asset get-history): the recorded state of named assets over a recent time window (a limited look-back, check the current limit in the documentation). It is not an unlimited archive; keep your own snapshots for long retention.
There is also policy analysis (gcloud asset analyze-iam-policy), which answers "who can access this resource?" or "what can this identity access?" by expanding groups and roles. Check gcloud asset analyze-iam-policy --help for the flags in your SDK version.
Why it is needed in a landing zone
- Visibility. With dozens or hundreds of projects, no one remembers what exists. A scope-level search is the only way to answer inventory questions quickly.
- Compliance evidence. Auditors ask for lists: all buckets, all service accounts, all external members. A saved snapshot with a date is evidence.
- Drift detection. Terraform state knows what code created. Inventory knows everything. The difference is your unmanaged resources.
- Incident response. During an incident you need to find every resource a compromised identity may have created, and every place a role was granted.
How it works internally
Google Cloud services report resource and policy changes to the asset service. The service indexes them by scope. Searches run against this index (so no calls to individual product APIs), which is why a search across thousands of projects returns quickly. The index is eventually consistent: a resource created seconds ago may not show yet, and a deleted one may linger briefly. Export reads the same data into a file. Feeds fan changes out to Pub/Sub as they are indexed, with the old and new state in the asset and priorAsset fields, and a deleted flag for removals.
Search query language
| Query | Meaning |
|---|---|
name:prod | The name contains prod |
labels.env=prod | Label env equals prod |
location:europe-west1 | In that location |
state:RUNNING | Resource state |
NOT labels.cost-center:* | Has no cost-center label (check the query syntax page for negation forms in your release) |
policy:roles/owner | (IAM search) bindings that mention the role |
Combine terms with spaces for AND. The documented query syntax is large; keep your own saved queries in the repository next to the code.
When to use which
| Question | Use |
|---|---|
| "What exists right now?" | Search |
| "Give me everything for the auditor, as a file." | Export |
| "Tell me the moment someone creates a public bucket." | Feed (and an Organization Policy to prevent it) |
| "What did this firewall rule look like last Tuesday?" | History (recent) or an older snapshot |
| "Who did it?" | Cloud Audit Logs (Module 1) |
| "Does the code match reality?" | Snapshots plus Terraform plan (Hour 7) |
What it is confused with
| Often confused | Difference |
|---|---|
| Asset Inventory vs Security Command Center | Inventory lists assets and policies. Security Command Center evaluates them and produces findings (Hour 3). SCC uses asset data, but they are different products. |
| Asset Inventory vs Audit Logs | State of an asset vs the API call that changed it. |
| Asset Inventory vs Terraform state | State holds only what Terraform manages; inventory sees everything, including console-created resources. |
| Feeds vs log sinks | Feeds publish asset changes; sinks route log entries. A sink on Admin Activity logs gives the actor, a feed gives the new state. |
Figure 1. One index, four outputs. Choose by the question: interactive, report, event, or recent history.
Figure 2. Drift reporting with snapshots. Compare inventory with state and with the previous period, then decide for each difference.
In Figure 1 notice that the index sits between the services and the four outputs, so no search calls the product APIs. In Figure 2, the amber box is the only output that needs a human decision: every item is adopted, removed or explicitly excepted.
The player follows a new VM through the inventory: indexing, a feed message, an alert from a subscriber, a search from the command line, and a scheduled snapshot. The feed and the snapshot are different paths to the same index.
Enable the API once on the project that you use for calls (the quota project): gcloud services enable cloudasset.googleapis.com --project=PROJECT_ID (free). Read commands are free; export and feeds create metadata, and storage or BigQuery costs apply to the files you write. Check gcloud asset --help and each subcommand's --help for the flags in your SDK version.
gcloud asset search-all-resources (read, free)
Purpose. Find resources across a scope without calling each product's API.
gcloud asset search-all-resources \ --scope=organizations/ORG_ID \ --query="labels.env=prod" \ --asset-types=compute.googleapis.com/Instance \ --format="table(name.basename(),assetType.basename(),location,project)"
NAME ASSET_TYPE LOCATION PROJECT vm-web-01 Instance europe-west1-b projects/987654321098 vm-web-02 Instance europe-west1-c projects/987654321098 vm-batch-01 Instance europe-west1-b projects/123450987654
Flags. --scope is organizations/ID, folders/ID or projects/ID. --query uses the asset query language. --asset-types filters by type (a comma-separated list). --page-size and --order-by help with large results.
Common errors. PERMISSION_DENIED: ... cloudasset.assets.searchAllResources: grant roles/cloudasset.viewer on the scope. Cloud Asset API has not been used in project ...: enable the API. A newly created resource missing from results: wait a minute, the index is eventually consistent. IDs in the expected output are illustrative.
gcloud asset search-all-iam-policies (read, free)
Purpose. Find who holds a role, or where an external identity has access, across a scope.
gcloud asset search-all-iam-policies \ --scope=organizations/ORG_ID \ --query="policy:roles/owner" \ --format="table(resource.basename(),policy.bindings.role,policy.bindings.members)"
RESOURCE ROLE MEMBERS prj-legacy-01 ['roles/owner'] ['user:former.employee@example.com'] prj-app-a-dev ['roles/owner'] ['group:app-a-admins@example.com']
Production use. Run this monthly and report any roles/owner or roles/editor binding to a user (not a group), and any member outside your domain. Table columns depend on the result structure; if a column prints empty, run once with --format=json to see the field names.
gcloud asset export (write: file in Cloud Storage, storage cost applies)
Purpose. Write a snapshot of resources (or IAM policies) to a bucket. This is the evidence file for audits and the input for drift diffs.
gcloud asset export \ --organization=ORG_ID \ --content-type=resource \ --asset-types="compute.googleapis.com/Instance,storage.googleapis.com/Bucket" \ --output-path=gs://SNAPSHOT_BUCKET/snapshots/2026-11-resource.json \ --billing-project=PROJECT_ID
Export in progress for root asset [organizations/123456789012]. Use [gcloud asset operations describe organizations/123456789012/operations/ExportAssets/RESOURCE/123456789] to check the status of the operation.
Flags. --organization, --folder or --project choose the root. --content-type is resource, iam-policy, org-policy, access-policy or relationship. --asset-types limits the volume (and the file size). --output-path is a gs:// URI; use --snapshot-time to export an earlier time within the retention window. --billing-project names the project that is billed and has the API enabled. For BigQuery output, use the BigQuery destination flags in gcloud asset export --help.
Common errors. The caller does not have permission on the bucket: the Cloud Asset service agent of the billing project needs write access to the bucket (roles/storage.objectCreator) and the exporting user needs cloudasset.assets.exportResource. Check the operation with the command printed in the output.
Production use. Run it from a scheduled job (Cloud Scheduler plus a function, or CI) under a service account with only the asset exporter permission, write to a retention-locked bucket in the logging project, and keep monthly snapshots for the audit retention period.
gcloud asset feeds create (write, free metadata; Pub/Sub cost is small)
Purpose. Get a message each time an instance is created, changed or deleted.
gcloud pubsub topics create asset-changes --project=PROJECT_ID gcloud asset feeds create instance-changes \ --organization=ORG_ID \ --content-type=resource \ --asset-types="compute.googleapis.com/Instance" \ --pubsub-topic=projects/PROJECT_ID/topics/asset-changes
Created feed [organizations/123456789012/feeds/instance-changes].
Flags. --asset-types or --asset-names select what to watch; --content-type selects the payload; --pubsub-topic is the full resource name. Optional --condition-expression filters changes with a CEL expression (check --help). Common errors. No messages: the topic must grant publish rights to the Cloud Asset service agent (service-ORG_NUMBER@gcp-sa-cloudasset.iam.gserviceaccount.com form) or, for project feeds, the project's service agent; the first publish then works. Verify with gcloud asset feeds describe.
gcloud asset feeds list --organization=ORG_ID gcloud asset feeds delete instance-changes --organization=ORG_ID
gcloud asset get-history (read, free)
Purpose. Show how a specific asset looked over a recent window.
gcloud asset get-history \ --project=PROJECT_ID \ --content-type=resource \ --asset-names="//compute.googleapis.com/projects/PROJECT_ID/global/firewalls/allow-ssh" \ --start-time=2026-11-20T00:00:00Z \ --end-time=2026-11-25T00:00:00Z
Flags. --asset-names takes the full resource name (starting with //). --start-time and --end-time are RFC 3339 timestamps. The window is limited by the service retention; older questions need your own snapshots. The result lists each recorded version with its time window; compare the sourceRanges field to see when a rule was widened.
gcloud asset analyze-iam-policy (read, free)
Purpose. Answer "who can reach this resource?" with groups expanded. Check gcloud asset analyze-iam-policy --help for the flags in your SDK version; the documented form uses a scope (--organization), a --full-resource-name, and optional --permissions or --roles filters.
Lab 6: search, snapshot and feed (about 12 minutes, low cost)
Goal. Use the inventory on a sandbox project: search, export a small snapshot to Cloud Storage, create a feed, and trigger and see one change message.
Prerequisites.
- A sandbox project
PROJECT_IDwith billing linked and your identity as Owner (orroles/cloudasset.ownerand rights to create buckets and topics). - Region
REGIONfor the bucket, for example one close to you. - No organization needed: all commands use
--project.
Cost. Low (usually well under a few USD per day for this lab; in practice a few kilobytes of storage and a handful of Pub/Sub messages). IDs in the expected output are illustrative.
- Enable the APIs.
export PROJECT_ID=PROJECT_ID export REGION=REGION gcloud services enable cloudasset.googleapis.com pubsub.googleapis.com --project="$PROJECT_ID"
Verify:gcloud services list --enabled --project="$PROJECT_ID" --filter="name:(cloudasset OR pubsub)"shows both. - Search the project.
gcloud asset search-all-resources --scope="projects/$PROJECT_ID" --page-size=10 \ --format="table(assetType.basename(),name.basename())"
Verify: a short list with at least one row (enabled services appear as resources). Empty output in a brand new project: wait one or two minutes. - Create the snapshot bucket and export.
export SNAP_BUCKET="${PROJECT_ID}-asset-snapshots" gcloud storage buckets create "gs://$SNAP_BUCKET" --project="$PROJECT_ID" \ --location="$REGION" --uniform-bucket-level-access gcloud asset export --project="$PROJECT_ID" --content-type=resource \ --output-path="gs://$SNAP_BUCKET/snap-1.json"Verify: after about a minute,gcloud storage ls "gs://$SNAP_BUCKET/"listssnap-1.json. If the export reports a permission error, grant the Cloud Asset service agent write access to the bucket, as described in the commands tab, and run it again. - Create a topic and a feed.
gcloud pubsub topics create asset-changes --project="$PROJECT_ID" gcloud pubsub subscriptions create asset-changes-sub --topic=asset-changes --project="$PROJECT_ID" gcloud asset feeds create lab-feed --project="$PROJECT_ID" --content-type=resource \ --asset-types="pubsub.googleapis.com/Topic" \ --pubsub-topic="projects/$PROJECT_ID/topics/asset-changes"
Verify:gcloud asset feeds describe lab-feed --project="$PROJECT_ID"prints the feed with the topic. - Trigger a change and read the message.
gcloud pubsub topics create inventory-test --project="$PROJECT_ID" sleep 60 gcloud pubsub subscriptions pull asset-changes-sub --project="$PROJECT_ID" --auto-ack --limit=3 --format=json
Verify: the JSON contains anassetwith a name ending intopics/inventory-test. If the pull is empty, wait another minute and pull again. If it stays empty, check the publisher permission of the Cloud Asset service agent on the topic. - Export again and compare.
gcloud asset export --project="$PROJECT_ID" --content-type=resource \ --output-path="gs://$SNAP_BUCKET/snap-2.json" sleep 60 gcloud storage cat "gs://$SNAP_BUCKET/snap-1.json" | wc -l gcloud storage cat "gs://$SNAP_BUCKET/snap-2.json" | wc -l
Verify: snap-2 contains at least one more line than snap-1 (the new topic). A real drift report would diff the asset names, as described in the concepts tab.
Expected result. A search result, two snapshot files in the bucket, one feed message that names the new topic, and a line count that grew by at least one.
Cleanup.
gcloud asset feeds delete lab-feed --project="$PROJECT_ID" gcloud pubsub subscriptions delete asset-changes-sub --project="$PROJECT_ID" gcloud pubsub topics delete asset-changes --project="$PROJECT_ID" gcloud pubsub topics delete inventory-test --project="$PROJECT_ID" gcloud storage rm --recursive "gs://$SNAP_BUCKET"
Verify the cleanup: gcloud storage buckets list --project="$PROJECT_ID" --filter="name:$SNAP_BUCKET" returns nothing and gcloud asset feeds list --project="$PROJECT_ID" shows no feed.
Real cases (typical, not named customers)
- Public bucket in minutes, not months. A company relied on a quarterly review to find public buckets. They added an organization feed for
storage.googleapis.com/Bucketwithiam-policycontent, a subscriber that checks forallUsersorallAuthenticatedUsers, and an Organization Policy (iam.allowedPolicyMemberDomainsplus public access prevention) so the finding became rare. The feed became the early warning, the policy the prevention. - The unmanaged estate. After two years the Terraform state described only 60 percent of the projects. A monthly export to BigQuery, joined with a table of project IDs from Terraform, listed 240 resources that had no code. The team classified them (adopt, delete, exception), and reduced the list each month, with a visible metric.
- Incident scoping. After a leaked service account key was found, the security team used
search-all-iam-policiesto find every binding for that account,search-all-resourcesto find resources created by projects it could reach, and audit logs (Module 1) to find what it did. Inventory gave the map and the audit log gave the timeline.
Practices
- Enable the Cloud Asset API in a dedicated platform or security project, and use it as the quota and billing project (
--billing-project). - Grant
roles/cloudasset.viewerto security and audit groups at the organization, and keep export permissions narrower. - Store snapshots in a bucket with a retention policy and Object Versioning in the logging project, and restrict deletion to a break-glass role.
- Prefer BigQuery export for monthly reports, because a diff in SQL is easier to review than a file comparison.
- Always pair a detective control (feed) with a preventive one (Organization Policy, Hour 3).
- Version your saved queries and feed definitions with Terraform (
google_cloud_asset_organization_feed) so that the monitoring itself is reviewed.
Security notes
- Feed messages contain resource metadata. Restrict the topic and subscription to the security service accounts.
- Search results respect the caller's permissions, so a person with project-level access cannot see the organization. Do not use a personal account for automation; use a service account with the minimum role.
- Resource metadata can include labels with business information. Avoid putting secrets or personal data in labels.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Cloud Asset API has not been used in project | API disabled on the quota project | gcloud services enable cloudasset.googleapis.com --project=PROJECT_ID and pass --billing-project |
PERMISSION_DENIED on search | No asset role on the scope | gcloud organizations get-iam-policy ORG_ID, look for roles/cloudasset.viewer |
| New resource missing from search | Eventual consistency | Wait a minute, search again; use a feed for events |
| Export operation fails | Service agent cannot write to the bucket | gcloud asset operations describe OPERATION_NAME, then the bucket IAM policy |
| Export file is huge or slow | No --asset-types filter | Export by type, or to BigQuery |
| Feed created but silent | Topic permission, asset type typo, or no change occurred | gcloud asset feeds describe; trigger a known change |
get-history returns nothing | Outside the look-back window, or wrong asset name format | Use the full name starting with //; shorten the time window |
| Search results seem incomplete | The caller sees only part of the scope | Run as an identity with organization-level viewer, or pick a smaller scope |
Triage order
- Confirm the API and the billing project (
--billing-project). - Confirm the permission on the scope (not only on a project below it).
- Check the operation (
gcloud asset operations describe) for exports. - For feeds, check the topic IAM policy and then publish a manual test message.
- If the data looks stale, wait and retry; if it is wrong, compare with the product API for one resource.
Search pages only. Confirm the video date and the commands against the current documentation, because asset flags and content types are extended over time.
- YouTube search: Cloud Asset Inventory overview
- YouTube search: asset feeds with Pub/Sub
- YouTube search: asset export to BigQuery and drift
Official reading: Cloud Asset Inventory overview · Searching resources · Monitor asset changes with feeds · Export to Cloud Storage.
Module 7 · Lab: organization sink and budget alert
- Create a log bucket and a sink that routes Admin Activity audit logs to it, at project scope or organization scope.
- Generate an audit event, find it in the source project and in the central bucket, and read who did what.
- Create a budget with threshold rules and verify it, then clean every resource up in the right order.
What this lab proves
Modules 1 to 6 explained parts of the audit and cost story. This lab connects them in one thread you can repeat in any sandbox: an action happens, it is logged, the log is routed to a central place, you can read who did it, and a budget watches the cost of the exercise. It also shows the one difference between the sandbox and the landing zone: the sink's scope.
Two scopes, one design
| Sandbox path (project sink) | Landing-zone path (organization sink) | |
|---|---|---|
| Needs an organization? | No | Yes |
| Sink command | gcloud logging sinks create NAME DEST --project=PROJECT_ID | gcloud logging sinks create NAME DEST --organization=ORG_ID --include-children |
| Which entries are seen | Those written in that project | Those written anywhere below the organization (with --include-children) |
| Destination | Log bucket in the same project | Log bucket in a central logging project |
| Writer identity permission | Not needed for a bucket in the same project (check the current documentation) | Needed on the central bucket for the sink's writer identity (for example roles/logging.bucketWriter) |
| Who may create it | Project owner | roles/logging.configWriter on the organization |
The commands in this lab are identical in structure for both paths. Use the sandbox path unless your instructor gives you an organization and a logging project.
Why an audit event on purpose
Alerts and sinks are tested by causing the event they are meant to catch. Creating and deleting a Pub/Sub topic is the cheapest safe write: it is metadata only, it costs nothing, it is a configuration change, so it lands in the Admin Activity log, and the audit entry names the principal, the method and the resource.
The three artifacts of the lab
- A log bucket (
lab-audit), with a 30-day retention. User-defined buckets are the destination for central logging, and they offer retention, location and optional Log Analytics. - A sink (
lab-audit-sink) with a filter on the Admin Activity log name, pointing to the bucket. - A budget (
lz-lab-h6) on the sandbox project, with a few threshold rules.
How to read an audit entry
An audit log entry is a LogEntry whose protoPayload is an AuditLog object. The fields to read, in order:
| Field | Tells you |
|---|---|
protoPayload.authenticationInfo.principalEmail | Who made the call (a user or a service account) |
protoPayload.methodName | What API method was called |
protoPayload.resourceName | Which resource |
protoPayload.serviceName | Which service |
protoPayload.status | Success (empty or code 0) or the error |
protoPayload.requestMetadata.callerIp | Where the call came from |
timestamp and insertId | When, and a unique ID for the entry |
What you must be able to say after the lab
- "The Admin Activity entry for the topic creation shows my identity in
principalEmail." - "The same entry exists in the central bucket, because the sink filter matched it."
- "The budget exists, has these rules, and only alerts."
- "Everything I created has been removed, in this order."
Figure 1. The lab in one picture. The audit entry travels from the API to the Admin Activity log, the sink copies it to the bucket, and you read it back.
Figure 2. The only structural difference between the two paths is the sink scope and the destination permission.
Compare the two halves of Figure 2: the lab commands are the same, and the production version adds --organization, --include-children and a role grant for the writer identity.
The player runs the lab as a sequence of real interactions: the topic creation call, the audit entry, the router matching the sink filter, the routed copy, the read-back, and finally the deletion of the sink. Watch the log lines; they are the ones you will see in the commands.
This tab lists every command used in the lab with its purpose and expected result. Run them in the Lab tab, in order. Costs: topic, sink and budget are free metadata; the log bucket ingests only Admin Activity audit entries (free to ingest at the sandbox's volume), so the lab is low cost. Check gcloud logging sinks create --help and gcloud billing budgets create --help for the flags in your SDK version.
gcloud logging buckets create (write, low cost)
Purpose. Create the central bucket, with a retention period.
gcloud logging buckets create lab-audit \ --project="$PROJECT_ID" \ --location=global \ --retention-days=30 \ --description="Lab: routed audit logs"
Created bucket [lab-audit]. createTime: '2026-11-25T09:12:41.123456789Z' lifecycleState: ACTIVE name: projects/prj-lab-0123/locations/global/buckets/lab-audit retentionDays: 30 updateTime: '2026-11-25T09:12:41.123456789Z'
Flags. --location cannot be changed later, choose it for data residency (use global or a region such as REGION). --retention-days sets how long entries stay (the default for user buckets is 30 days). Common error. Bucket already exists (including a bucket in pending deletion with the same ID): choose a new name.
gcloud logging sinks create (write, free)
Purpose. Route Admin Activity entries to the bucket.
gcloud logging sinks create lab-audit-sink \ "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/lab-audit" \ --project="$PROJECT_ID" \ --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"'
Created [https://logging.googleapis.com/v2/projects/prj-lab-0123/sinks/lab-audit-sink]. Please remember to grant `serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com` the appropriate permissions on the destination.
Flags. The first positional argument is the sink name and the second the destination. A bucket destination is logging.googleapis.com/projects/PROJECT_ID/locations/LOCATION/buckets/BUCKET_ID. --log-filter uses the Logging query language. In the organization form add --organization=ORG_ID --include-children and omit --project.
Note. The message about granting permissions appears for all sinks. For a destination bucket in the same project as the sink, no extra grant is normally needed; for a central bucket in another project, grant the writer identity roles/logging.bucketWriter on that project. Check the current routing documentation.
gcloud logging sinks describe (read, free)
Purpose. Confirm the filter, destination and writer identity.
gcloud logging sinks describe lab-audit-sink --project="$PROJECT_ID"
createTime: '2026-11-25T09:13:10.001Z' destination: logging.googleapis.com/projects/prj-lab-0123/locations/global/buckets/lab-audit filter: logName="projects/prj-lab-0123/logs/cloudaudit.googleapis.com%2Factivity" name: lab-audit-sink updateTime: '2026-11-25T09:13:10.001Z' writerIdentity: serviceAccount:service-123456789012@gcp-sa-logging.iam.gserviceaccount.com
IDs in the expected output are illustrative.
gcloud pubsub topics create (write, free)
Purpose. Generate the audit event. Enable the Pub/Sub API first if needed: gcloud services enable pubsub.googleapis.com.
gcloud pubsub topics create lab-audit-topic --project="$PROJECT_ID"
Created topic [projects/prj-lab-0123/topics/lab-audit-topic].
gcloud logging read (read; reads of the source are free, the bucket query follows log storage rules)
Purpose. Find the audit entry, first in the source project, then in the central bucket.
# In the source (the _Required bucket holds Admin Activity entries) gcloud logging read \ 'logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \ --project="$PROJECT_ID" --freshness=1h --limit=3 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.resourceName)" # In the central bucket gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \ --project="$PROJECT_ID" --bucket=lab-audit --location=global --view=_AllLogs \ --freshness=1h --limit=3 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL METHOD_NAME RESOURCE_NAME 2026-11-25T09:14:02.331Z you@example.com google.pubsub.v1.Publisher.CreateTopic projects/prj-lab-0123/topics/lab-audit-topic
Flags. --freshness limits to recent entries. --bucket, --location and --view read a specific bucket (every user bucket has a _AllLogs view). --limit caps rows. Common errors. Empty result: the sink only routes entries that arrive after it was created, and routing can take a minute; run the topic creation again. Invalid filter: check quote nesting in the shell.
gcloud billing budgets create (write, free metadata)
gcloud billing budgets create \ --billing-account="$BILLING_ACCOUNT_ID" \ --display-name="lz-lab-h6" \ --budget-amount=20USD \ --filter-projects="projects/$PROJECT_ID" \ --threshold-rule=percent=0.5 \ --threshold-rule=percent=0.9 \ --threshold-rule=percent=1.0,basis=forecasted-spend
Created budget [billingAccounts/0X0X0X-0X0X0X-0X0X0X/budgets/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee].
Purpose. Early warning for the sandbox. It alerts and does not cap. Use your billing account currency.
Cleanup commands (writes, free; the bucket enters a pending-deletion period)
gcloud logging sinks delete lab-audit-sink --project="$PROJECT_ID" gcloud pubsub topics delete lab-audit-topic --project="$PROJECT_ID" gcloud logging buckets delete lab-audit --project="$PROJECT_ID" --location=global gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"
google_logging_project_bucket_config, google_logging_organization_sink (or google_logging_project_sink) and google_billing_budget. The commands in this lab are how you verify what Terraform created.Lab 7: central audit sink and budget (10 minutes, low cost)
Goal. Route Admin Activity audit logs to a log bucket, cause one audit event, read it back from the source and from the bucket, create a budget, and remove everything.
Prerequisites.
- A sandbox project
PROJECT_IDlinked toBILLING_ACCOUNT_ID, with you as Owner. Do not use a production project. gcloudauthenticated (gcloud auth list) and the project set as default.- APIs: Cloud Logging is on by default; enable
pubsub.googleapis.comandbillingbudgets.googleapis.comin step 1. - Optional organization path:
ORG_ID, a central logging project, androles/logging.configWriteron the organization. The lab marks the differences. - No real secrets and no data are involved.
Cost. Low (usually well under a few USD per day for this lab; Admin Activity ingestion is free and the other objects are metadata). Budgets send alerts and do not cap spend. IDs in the expected output are illustrative.
- Safety first: variables, billing link and APIs.
export PROJECT_ID=PROJECT_ID export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID gcloud config set project "$PROJECT_ID" gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled)" gcloud services enable pubsub.googleapis.com billingbudgets.googleapis.com --project="$PROJECT_ID"
Verify: the describe command printsTrue. - Create the budget before any other resource. Run the budget command from the commands tab. Verify:
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)"listslz-lab-h6. Note the budget ID for cleanup. - Create the log bucket. Run the
buckets createcommand. Verify:gcloud logging buckets describe lab-audit --project="$PROJECT_ID" --location=global --format="value(retentionDays,lifecycleState)"
30 ACTIVE
- Create the sink. Run the
sinks createcommand. For the organization path, replace--projectwith--organization=ORG_ID --include-children, use the central bucket as the destination, and grant the writer identity the bucket writer role on the logging project:WRITER=$(gcloud logging sinks describe lab-audit-sink --project="$PROJECT_ID" --format="value(writerIdentity)") echo "$WRITER" # Only when the destination is in another project: # gcloud projects add-iam-policy-binding LOGGING_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter"
Verify:sinks describeshows your filter, the destination string and awriterIdentity. - Generate the audit event.
gcloud pubsub topics create lab-audit-topic --project="$PROJECT_ID"
Verify:gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)"lists the topic. - Read the event in the source. Run the first
logging readcommand. Verify: one row with your identity as the principal and the methodgoogle.pubsub.v1.Publisher.CreateTopic. If the row is missing, wait 30 seconds and run it again; audit entries can take a short time to appear. - Read the event in the central bucket. Run the second
logging readcommand. Verify: the same entry appears. If it does not, create another topic (lab-audit-topic-2), wait a minute, and read again; the sink routes only entries written after it exists. If it still does not appear, runsinks describeand check the filter and destination. - Prove who did it. Print the full entry once as JSON and locate
principalEmail,callerIpanduserAgent:gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \ --project="$PROJECT_ID" --bucket=lab-audit --location=global --view=_AllLogs \ --freshness=1h --limit=1 --format=json
Verify: your own address is inprotoPayload.authenticationInfo.principalEmail. - (Optional) Add an exclusion on the sink and see its effect. Create a second sink with a filter that matches nothing you do (for example a different service) and confirm that it routes nothing. This reproduces the most common "missing logs" case from Module 8.
Expected result. The CreateTopic entry exists in the source and in lab-audit, with your identity as the principal. The budget exists and is listed.
Cleanup (in this order).
gcloud logging sinks delete lab-audit-sink --project="$PROJECT_ID" gcloud pubsub topics delete lab-audit-topic --project="$PROJECT_ID" gcloud logging buckets delete lab-audit --project="$PROJECT_ID" --location=global gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"
Verify the cleanup.
gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)" gcloud logging buckets list --project="$PROJECT_ID" --location=global --format="value(name,lifecycleState)" gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)" gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)"
The sink and topic lists must not show lab resources. The bucket may be listed as DELETE_REQUESTED for several days, which is normal and free for an empty bucket. The budget list must not show lz-lab-h6.
NOT_FOUND. If you use a shared sandbox, also delete any lab-audit-topic-2 from the optional steps.Real cases (typical, not named customers)
- Proving a sink, not trusting it. A platform team created an organization sink and assumed it worked because the command succeeded. Months later an auditor asked for evidence, and the bucket was empty because the filter had a typo in the log name. After that, the team added a canary: a scheduled job that creates and deletes a topic in a canary project each day and a Monitoring alert that fires if the CreateTopic entry is not seen in the central bucket within 15 minutes.
- Writer identity forgotten. A sink to a central bucket in another project was created, but nothing arrived, because the writer identity had no role on the destination. The platform team made the role grant part of the same Terraform module as the sink, so that the sink and its permission can never be separated.
- Sandbox with a budget from minute one. A training program creates a sandbox project per learner with a small budget, labels and a Pub/Sub notification to the instructor. A forgotten VM from one learner was found by the 50 percent alert before the second day.
Practices
- Treat every control as unproven until you have seen the evidence: generate the event, then read it from the destination.
- Keep the lab commands as a smoke test for the landing zone, and run them whenever the logging layer changes.
- Create sinks and buckets with Terraform, and use the commands only to verify.
- Set the budget first, create resources second, and delete in reverse order.
- Use filters that name the log by its full name, so that a sink does not copy more than intended.
- Put the central bucket in a dedicated logging project that application teams cannot administer.
Security notes
roles/logging.configWriter and roles/logging.admin sparingly, alert on changes to sinks (google.logging.v2.ConfigServiceV2.DeleteSink and UpdateSink), and lock retention on the central bucket.- The lab prints your email in the output. Do not paste real audit output into public tickets.
- Do not use a service account key for the lab. Use your own identity or impersonation.
- Never route audit logs to a bucket that application teams can read in full; entries include IP addresses and resource names.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Event visible in the source, not in the bucket | Filter does not match, or the entry was written before the sink existed | gcloud logging sinks describe; create a new event after the sink |
| Sink created but destination error in the sink metrics | Writer identity lacks permission on the destination | Destination IAM policy for the writer identity; grant roles/logging.bucketWriter |
Bucket already exists | Same ID used before; deleted buckets remain for a pending period | gcloud logging buckets list --location=global; use a new ID |
Invalid filter | Shell quotes broke the filter | Print the filter with echo; use single quotes outside, double inside |
PERMISSION_DENIED creating a sink | Missing logging.sinks.create | gcloud projects get-iam-policy PROJECT_ID for roles/logging.configWriter |
read from the bucket returns nothing but the sink is fine | Wrong --view or --location | Use --view=_AllLogs and the bucket's location |
| Budget creation fails | No billing permission or API disabled | gcloud services list --enabled --filter="name:billingbudgets", then the billing account IAM policy |
Cleanup says NOT_FOUND | Already deleted | Harmless; verify with the list commands |
Triage order
- Is the entry in the source? If not, the problem is the event or the filter, not the sink.
- Describe the sink: filter, destination, writer identity.
- Check the destination permission for the writer identity.
- Check the sink's own metrics in Cloud Monitoring (
logging.googleapis.com/exports/error_count) for delivery errors. - Check exclusions on the source project and the bucket's view.
Search pages only; confirm dates against the current documentation.
- YouTube search: Cloud Logging sink to a log bucket
- YouTube search: Cloud Audit Logs explained
- YouTube search: set up a Cloud Billing budget alert
Official reading: Configure and manage sinks · Configure log buckets · Cloud Audit Logs overview.
Module 8 · Troubleshooting logs and cost
- Follow a fixed triage order for missing logs: source, filters and exclusions, sink, destination permission, then query.
- Diagnose a sink that does not deliver and an alert or budget notification that was never received.
- Find the source of an ingestion cost spike with log volume metrics, and reduce it without losing audit evidence.
The short answer
Troubleshooting logging and cost means walking the path of a log entry or a charge in order and finding where it stopped or grew. Almost every incident in this hour is one of five things: a filter or exclusion removed the entry, a sink did not match or could not write, a permission was missing on the destination, an alert had no working channel, or volume from one producer grew.
The path of a log entry
- Source. The workload writes the entry (stdout, agent, API). Was it ever written? Is the Logging agent installed and permitted (
roles/logging.logWriteron the workload's service account)? - Cloud Logging API. Quota (write requests per minute) and the entry size limit apply.
- Log router. For every entry, each sink evaluates its filter and exclusions. The
_Requiredsink always keeps Admin Activity and System Event audit logs. The_Defaultsink keeps most other entries unless it is disabled or has exclusions. - Destination. A log bucket (retention, location, views), BigQuery, Cloud Storage or Pub/Sub. The writer identity must be permitted.
- Query. You read through a view; the bucket's location, the view and your IAM (log view access) decide what you see.
An entry can be missing at any step. The triage order below checks them from left to right so that each answer narrows the next question.
Why logs go missing
| Cause | How it looks | Fix |
|---|---|---|
| Exclusion filter | Entries of a type disappear from a bucket after a cost change | Review gcloud logging sinks describe _Default, narrow or remove the exclusion |
| Sink disabled | All new entries are missing from the destination | gcloud logging sinks update NAME --no-disabled (check --help) |
| Filter typo | Sink exists, destination empty | Test the same filter with gcloud logging read on the source |
| Writer identity without role | Sink exists, filter matches, destination empty; sink error metric above zero | Grant roles/logging.bucketWriter (bucket), roles/bigquery.dataEditor (BigQuery), roles/storage.objectCreator (Storage) or roles/pubsub.publisher (Pub/Sub) to the writer identity |
| Wrong scope | Organization sink does not contain a project's entries | Add --include-children, or create the sink at the right level |
| Retention expired | Old entries gone | Raise retention before the data is needed (not retroactively) |
| Data Access logs not enabled | Reads of data are not recorded | Enable Data Access audit logs for the required services (cost applies) |
| Wrong view or location | Query returns empty though the bucket has data | Use --view=_AllLogs and the bucket location |
Why sinks fail to deliver
When a sink cannot write, the log router counts errors in logging.googleapis.com/exports/error_count and sends no further notice. The command that created the sink printed success because it only wrote the sink configuration. Always verify a new sink with an end-to-end test (Module 7) and alert on the error metric for production sinks.
Why alerts are not received
- The alert policy never evaluated true: wrong metric, wrong filter, wrong duration (it must be true for the whole duration window).
- The policy has no notification channel, or the channel is unverified (email not confirmed) or its webhook is failing.
- The incident is open and not closed: for metric alerts, a new notification is not sent while the incident remains open, so a recurring condition seems quiet.
- Notification rate limiting or snooze is active.
- For budgets: only default recipients are notified, and the thresholds were never crossed, or the Pub/Sub topic is mis-set (Module 5).
Why ingestion cost spikes
Cloud Logging charges for ingested volume into buckets (beyond free allotments, and with exceptions such as the _Required bucket) and for storage beyond the default retention. The usual drivers are:
| Driver | Example |
|---|---|
| Debug verbosity left on | A release shipped with DEBUG logging in production |
| Data Access audit logs on a busy service | BigQuery or Cloud Storage Data Access logs enabled for every project |
| VPC Flow Logs and firewall rules logging | Sampling set to 100 percent on a busy subnet |
| Load balancer request logs | Logging enabled at 1.0 sampling on a high-traffic service |
| Crash loops and retries | A failing job writes a stack trace every second |
| Double routing | The same entries stored in _Default and in a central bucket (a second copy is a second ingestion) |
Measure first, then reduce: the cheapest fix is almost always at the producer (log level, sampling), then exclusions for low-value entries on _Default, then routing choices (a central bucket for audit, none for debug).
What it is confused with
| Often confused | Difference |
|---|---|
| Exclusion vs retention | An exclusion stops entries from being stored; retention deletes stored entries after N days. |
Exclusion on _Default vs exclusion on a custom sink | They are independent. Excluding from _Default does not stop a custom sink from routing the same entry. |
| Alert policy vs budget | Alert policies watch metrics and logs now; budgets watch billed spend with a delay. |
| Logs vs metrics for alerting | Metrics are cheaper and steadier for thresholds; logs fit rare events such as an audit entry. |
Figure 1. The five-step triage for a missing log entry. Each step has one command that gives evidence.
Figure 2. Three places to reduce ingestion cost, in order of preference: producer, exclusion, routing.
In Figure 1 read the evidence list below the boxes: each step has exactly one command. In Figure 2, the best saving is on the left because it avoids creating the entry at all.
The player follows a DEBUG entry that is dropped by an exclusion on _Default while ERROR entries are stored and feed an alert policy. It makes the point that "missing" is often a rule that did exactly what it was told.
The troubleshooting set. All read commands are free; the update commands change configuration and are free metadata operations, but exclusions change what is stored, so record the old value first. Check --help for each command in your SDK version.
gcloud logging sinks list and describe (read, free)
Purpose. See every sink at a scope, including _Required and _Default, and read exclusions.
gcloud logging sinks list --project=PROJECT_ID gcloud logging sinks describe _Default --project=PROJECT_ID
createTime: '2026-03-02T10:00:00.000Z'
destination: logging.googleapis.com/projects/prj-app-a/locations/global/buckets/_Default
exclusions:
- description: Cost review 2026-10
filter: severity=DEBUG
name: exclude-debug
filter: NOT LOG_ID("cloudaudit.googleapis.com/activity") AND NOT LOG_ID("externalaudit.googleapis.com/activity") AND NOT LOG_ID("cloudaudit.googleapis.com/system_event") AND NOT LOG_ID("externalaudit.googleapis.com/system_event") AND NOT LOG_ID("cloudaudit.googleapis.com/access_transparency") AND NOT LOG_ID("externalaudit.googleapis.com/access_transparency")
name: _Default
Reading it. The exclusions list shows exclude-debug. Anyone looking for DEBUG entries in _Default will find none. IDs and dates in the expected output are illustrative. For organization sinks add --organization=ORG_ID.
gcloud logging sinks update (write, free metadata)
Purpose. Fix a filter, enable a sink, or change exclusions.
gcloud logging sinks update lab-audit-sink --project=PROJECT_ID \ --log-filter='logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"' # Remove an exclusion from the default sink (flag names: check help) gcloud logging sinks update _Default --project=PROJECT_ID --remove-exclusions=exclude-debug
Flags. --log-filter replaces the sink filter. Exclusions are managed with --add-exclusion=name=NAME,filter=FILTER and --remove-exclusions=NAME; a sink can be disabled with --disabled and re-enabled with --no-disabled. Check gcloud logging sinks update --help for the flags in your SDK version. Common error. PERMISSION_DENIED: you need roles/logging.configWriter on the scope of the sink.
Production use. Never edit production sinks by hand; change the Terraform, review the plan, and apply. Use the command only to confirm what is deployed.
gcloud logging read to test a filter on the source (read, free for the source)
Purpose. Test whether the entries your sink should match exist. Use the same filter as the sink.
gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName:"SetIamPolicy"' \ --project=PROJECT_ID --freshness=1d --limit=5 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL RESOURCE_NAME 2026-11-24T16:02:11.120Z tf-org@prj-seed.iam.gserviceaccount.com projects/prj-app-a
Reading it. If this finds entries in the source and the destination is empty, the problem is steps 3 or 4 of the triage. If it finds nothing, the problem is the event or the filter text itself. Common error. A filter that uses logName= must have the exact encoded name (%2F for the slash). The : operator is a substring match, = is exact.
Check delivery errors with the sink error metric (read, free)
Purpose. Prove that a sink is failing to write. In Metrics Explorer, chart logging.googleapis.com/exports/error_count, grouped by sink_name. Use the console, or list the metric descriptor:
gcloud monitoring metrics-descriptors describe logging.googleapis.com/exports/error_count --project=PROJECT_ID
Note. If the gcloud monitoring group is not available in your SDK release, use the console or the Monitoring API. Check gcloud monitoring --help. A non-zero value for your sink means the router matched entries but could not write them: look at the destination permission first.
Check the writer identity and destination permission (read, free)
WRITER=$(gcloud logging sinks describe SINK_NAME --project=PROJECT_ID --format="value(writerIdentity)") echo "$WRITER" gcloud projects get-iam-policy LOGGING_PROJECT_ID \ --flatten="bindings[].members" \ --filter="bindings.members:$WRITER" \ --format="table(bindings.role)"
ROLE roles/logging.bucketWriter
Reading it. An empty table means the writer identity holds no role on the destination project. Grant the right role for the destination type (see the concepts tab) with gcloud projects add-iam-policy-binding LOGGING_PROJECT_ID --member="$WRITER" --role="roles/logging.bucketWriter". For a tighter grant, add an IAM condition on the bucket resource name. Check the logging routing documentation for the current recommended form.
Find the noisy producer (read, free)
Purpose. Group ingested bytes by log. The console route is the quickest: Logging, Logs Storage shows the volume per bucket, and Logs Explorer's Log Analytics or Metrics Explorer can group logging.googleapis.com/billing/bytes_ingested by resource_type and log. As a command, list the log names that exist in a project and sample the most recent entries of a suspect:
gcloud logging logs list --project=PROJECT_ID --limit=30 gcloud logging read 'severity=DEBUG' --project=PROJECT_ID --freshness=15m --limit=5 --format="value(logName,resource.type)"
projects/prj-app-a/logs/cloudaudit.googleapis.com%2Factivity projects/prj-app-a/logs/compute.googleapis.com%2Fvpc_flows projects/prj-app-a/logs/stdout projects/prj-app-a/logs/run.googleapis.com%2Frequests
Reading it. Names such as vpc_flows or requests that appear in large volume are candidates for lower sampling. IDs are illustrative.
gcloud logging sinks update _Default --add-exclusion (write, free metadata)
Purpose. Reduce cost by excluding low-value entries from _Default only, after the measurement above.
gcloud logging sinks update _Default --project=PROJECT_ID \ --add-exclusion='name=exclude-lb-health,description=Health check noise,filter=resource.type="http_load_balancer" AND httpRequest.requestUrl:"/healthz"'
Flags. --add-exclusion takes name, description and filter as comma-separated keys; quote carefully because the filter contains quotes and may contain commas (check --help for the exact syntax). Common mistake. An exclusion that is too wide, such as severity<ERROR, removes every INFO and WARNING entry from _Default, which makes the next incident harder to investigate. Production use. Every exclusion has a name, a description with the ticket number and a review date.
gcloud billing budgets describe (read, free)
Purpose. For "alert not received": inspect the notification rules.
gcloud billing budgets describe BUDGET_ID --billing-account=BILLING_ACCOUNT_ID --format="yaml(displayName,thresholdRules,notificationsRule)"
displayName: prod-folder-monthly notificationsRule: disableDefaultIamRecipients: true pubsubTopic: projects/prj-billing/topics/budget-alerts thresholdRules: - spendBasis: CURRENT_SPEND thresholdPercent: 0.9
Reading it. disableDefaultIamRecipients: true with only a Pub/Sub topic means no email goes to anyone. If nobody reads the topic, the alert is silent. Add a Monitoring channel or re-enable the default recipients. IDs are illustrative.
Lab 8: break it, find it, fix it (about 15 minutes, low cost)
Goal. Create three deliberate faults in a sandbox, use the triage order to find each one, and fix it. You will practise the exact commands you would use at 3 a.m.
Prerequisites. The sandbox project from Module 7 (PROJECT_ID), roles/logging.configWriter and roles/pubsub.admin (or Owner), and a budget safety net. Do not run this in a shared project. IDs in the expected output are illustrative.
Cost. Low (usually well under a few USD per day for this lab). Budgets alert and do not cap spend.
- Prepare.
export PROJECT_ID=PROJECT_ID gcloud config set project "$PROJECT_ID" gcloud services enable pubsub.googleapis.com --project="$PROJECT_ID" gcloud logging buckets create fault-bucket --location=global --retention-days=7 --project="$PROJECT_ID"
Verify:gcloud logging buckets list --location=global --project="$PROJECT_ID" --format="value(name)"includesfault-bucket. - Fault 1: filter typo. Create a sink with a deliberately wrong log name, then generate an event.
gcloud logging sinks create fault-sink-1 \ "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/fault-bucket" \ --project="$PROJECT_ID" \ --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivty"' gcloud pubsub topics create fault-topic-1 --project="$PROJECT_ID"
Wait a minute, then read the bucket:gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic"' \ --project="$PROJECT_ID" --bucket=fault-bucket --location=global --view=_AllLogs --freshness=1h --limit=3
Observe: the result is empty. Diagnose: the event exists in the source (rungcloud logging readwithout--bucket), so the problem is the sink;sinks describe fault-sink-1showsactivty. Fix:gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"', createfault-topic-2and read again. Verify: the new entry appears. - Fault 2: an exclusion. Add an exclusion to your own sink and see the effect.
gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" \ --add-exclusion='name=exclude-all-topics,filter=protoPayload.methodName:"Publisher.CreateTopic"' gcloud pubsub topics create fault-topic-3 --project="$PROJECT_ID"
Observe: after a minute,fault-topic-3is in the source but not in the bucket. Diagnose:gcloud logging sinks describe fault-sink-1 --project="$PROJECT_ID"listsexclusions. Fix:gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --remove-exclusions=exclude-all-topicsand repeat withfault-topic-4. Verify: the entry forfault-topic-4arrives. - Fault 3: disabled sink.
gcloud logging sinks update fault-sink-1 --project="$PROJECT_ID" --disabled gcloud pubsub topics create fault-topic-5 --project="$PROJECT_ID"
Observe: no new entry arrives. Diagnose:sinks describeshowsdisabled: true. Fix:--no-disabled, then test withfault-topic-6. If your SDK rejects these flags, checkgcloud logging sinks update --helpand use the console toggle. - Practise the cost question. Run the "find the noisy producer" commands from the commands tab on your project. Verify: you can name the three log names with the most entries in the last hour, or confirm the project is quiet.
- Write the incident note. For each fault, write two lines: symptom and first check, cause and fix. Compare with the troubleshooting table.
Expected result. After each fix, a new CreateTopic entry appears in fault-bucket. You have seen filter, exclusion, and disabled-sink faults and the one command that exposes each of them (sinks describe).
Cleanup.
gcloud logging sinks delete fault-sink-1 --project="$PROJECT_ID" for n in 1 2 3 4 5 6; do gcloud pubsub topics delete "fault-topic-$n" --project="$PROJECT_ID" --quiet; done gcloud logging buckets delete fault-bucket --location=global --project="$PROJECT_ID"
Verify: gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)" shows only _Default and _Required. Topics that were never created return NOT_FOUND, which is harmless.
Real cases (typical, not named customers)
- The cost-cutting exclusion. A cost review added an exclusion on
_Defaultfor everything below ERROR. Two weeks later an outage needed the INFO entries that showed the request path, and they were gone. The team replaced the blanket exclusion with specific ones (health checks, a chatty library), required a ticket and an expiry date on each exclusion, and reduced volume at the producers by changing log levels. - The 40 percent surprise. The ingestion bill rose by about 40 percent after a network change. Grouping bytes by log showed VPC Flow Logs at full sampling on one busy subnet. Setting the sampling rate lower and filtering the aggregation interval kept enough data for investigations at a fraction of the volume.
- The alert that never arrived. A budget notification was set up to a Pub/Sub topic with the default recipients disabled. The subscriber function had failed after a library upgrade, so the 90 percent alert disappeared. The team added a dead-letter subscription, an alert on the subscription's oldest unacknowledged message age, and a monthly test message.
Practices
- Keep audit logs in
_Requiredand in a central bucket; do not exclude audit entries anywhere. - Alert on sink delivery errors, not only on the application.
- Name every exclusion, give it an owner, a reason and a review date, and keep it in Terraform.
- Check ingestion volume weekly by log name; a sudden 2x is an incident.
- Test notification channels every quarter with a test notification.
- Write the triage order into the on-call runbook and practice it in game days.
Security notes
UpdateSink, DeleteSink, UpdateBucket, DeleteBucket and changes to exclusions, and restrict roles/logging.admin.- Keep a copy of audit logs in a central bucket in a project that workload owners cannot administer, with a locked retention policy.
- Cost spikes with no matching change record are a security signal; read the Admin Activity log for the same period.
- Do not paste log excerpts that contain tokens or personal data into tickets; scrub first.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Expected log entries missing from _Default | Exclusion filter, or entries were never written | gcloud logging sinks describe _Default and read the source with a filter |
| Central bucket empty, source has entries | Filter mismatch, wrong scope, or writer identity without role | sinks describe, then destination IAM policy, then exports/error_count |
| Org sink does not include one project's entries | Missing --include-children, or the project is in another organization | Describe the sink at the organization scope |
| Alert policy never fires | Metric or filter wrong, duration longer than the condition lasts | Chart the same metric in Metrics Explorer for the period |
| Alert fires in the console, nobody is told | No notification channel, unverified channel, or open incident | Policy details: channels; channel verification status |
| Budget notification not received | Default recipients disabled, thresholds not crossed, or topic subscriber failing | gcloud billing budgets describe; check the topic and the subscriber |
| Ingestion cost doubled | Debug logs, flow logs sampling, Data Access logs, crash loop, double routing | Chart billing/bytes_ingested grouped by log; list recent noisy logs |
read returns older entries only | Retention shorter than the question, or index delay | Bucket retentionDays; wait a minute for recent entries |
Cannot delete or change _Required | It is managed by Google Cloud and cannot be changed | Use a custom bucket for different retention |
Triage order
- Source. Does the entry or the charge exist where it was produced?
- Filters and exclusions.
sinks describe _Defaultand project-level exclusions. - Sink. Describe the sink: filter, scope, disabled, destination string.
- Permission. Writer identity role on the destination; sink error metric.
- Query. View, location, retention, your own log view access.
- For cost: measure by log and resource before changing anything; reduce at the producer first.
- For alerts: policy condition, channel, incident state, then the budget notification rules.
Search pages only; compare the video date to the documentation for log routing and exclusions, which change often.
- YouTube search: Cloud Logging exclusion filters and cost
- YouTube search: troubleshooting Cloud Logging sinks
- YouTube search: Cloud Monitoring alerting and notification channels
Official reading: Routing and storage overview · Troubleshoot sinks · Exclusion filters · Alerting overview.
Command cheat sheet
Hour 6 command cheat sheet: logging, audit, monitoring, inventory and cost
Placeholders are in UPPERCASE: PROJECT_ID, ORG_ID, BILLING_ACCOUNT_ID, REGION. Every command here is documented for the gcloud CLI (current release channel). Flags change between releases, so run gcloud COMMAND --help before you rely on a flag in automation. The "Cost" column in the legend below says whether a write command is free metadata or has a metered effect.
Audit logs and reading logs
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud logging read 'FILTER' | Read log entries from a project, folder, organization or bucket | --project, --freshness=1h, --limit, --format, --order=desc, --bucket --location --view | Quote nesting breaks filters. = is exact, : is a substring match. Without --freshness the default window is large and slow. |
gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity"' | Admin Activity entries (who changed configuration) | Add protoPayload.methodName="..." and protoPayload.authenticationInfo.principalEmail="..." | The slash in the log name is encoded as %2F. Data Access logs are data_access and are off by default for most services. |
gcloud logging logs list | List the log names that exist in a project | --project, --limit | Lists names, not volume. Use Metrics Explorer for bytes. |
gcloud projects get-iam-policy PROJECT_ID | Check who holds logging or billing roles on a project | --flatten="bindings[].members", --filter, --format | Shows direct bindings only; inherited bindings come from the folder and organization. |
Log buckets and sinks
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud logging buckets create BUCKET_ID | Create a user-defined log bucket (central destination) | --location, --retention-days, --description, --project (also CMEK and analytics flags; check help) | Location cannot be changed. A deleted bucket stays for a pending period, and its ID is not reusable during that time. |
gcloud logging buckets list / describe | Check retention, location and lifecycle state | --location=global, --format="value(retentionDays,lifecycleState)" | List needs a location; use global or the region you created the bucket in. |
gcloud logging buckets update BUCKET_ID | Change retention or description | --location, --retention-days | A shorter retention deletes data as soon as it applies. Locking retention is permanent; check the lock flags before using them. |
gcloud logging buckets delete BUCKET_ID | Delete a user-defined bucket | --location, --project | Delete the sinks that point to it first. _Required and _Default cannot be deleted. |
gcloud logging sinks create NAME DESTINATION | Route matching entries to a bucket, BigQuery, Cloud Storage or Pub/Sub | --log-filter, --project, --organization, --folder, --include-children, --exclusion | The command succeeds even if the writer identity has no permission. Grant the destination role to the writer identity and test end to end. Bucket destination form: logging.googleapis.com/projects/P/locations/L/buckets/B. |
gcloud logging sinks list / describe NAME | Inspect filter, destination, exclusions, writer identity | --project / --organization | Remember _Required and _Default are sinks too; exclusions live on them. |
gcloud logging sinks update NAME | Fix a filter, enable or disable, change exclusions | --log-filter, --add-exclusion, --remove-exclusions, --disabled, --no-disabled | Exclusions remove entries silently. Keep a ticket number in the description. Check help for exact syntax in your SDK. |
gcloud logging sinks delete NAME | Remove a sink | --project / --organization | Does not delete entries already routed. Deleting audit sinks should alert the security team. |
Monitoring and alerting
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud monitoring channels list | List notification channels | --project, --format | In older SDK releases the group is under alpha or beta. Check gcloud monitoring --help. |
gcloud monitoring policies list | List alerting policies and their channels | --project, --format="table(displayName,enabled)" | An enabled policy with no channel fires silently. |
gcloud monitoring policies create --policy-from-file=FILE | Create an alerting policy from JSON or YAML | --policy-from-file, --project | Keep the file in Terraform or the repository. The file schema follows the AlertPolicy API. |
gcloud monitoring metrics-descriptors describe METRIC | Check that a metric type exists, for example logging.googleapis.com/exports/error_count | --project | Metrics exist only for resources in the metrics scope you query. Check --help if the group is missing. |
gcloud logging metrics create NAME --log-filter=FILTER / --config-from-file | Create a log-based metric (count of matching entries) | --description, --log-filter | Counts entries only from creation time. Labels create one time series per value; high-cardinality labels raise cost. |
Billing, budgets and labels
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud billing accounts list | Find billing account IDs you can use | --format="table(name,displayName,open)" | Empty output means no billing role for your identity. |
gcloud billing projects describe PROJECT_ID | Check the billing link of a project | --format="value(billingAccountName,billingEnabled)" | billingEnabled: False blocks paid services and API calls that need billing. |
gcloud billing projects link PROJECT_ID --billing-account=ID | Link a project to a billing account | --billing-account | Needs roles/billing.user on the account and project owner rights. Free metadata change. |
gcloud billing budgets create | Create a budget with threshold rules | --billing-account, --display-name, --budget-amount=50USD, --filter-projects, --calendar-period=month, --threshold-rule=percent=0.9[,basis=forecasted-spend], --notifications-rule-pubsub-topic | Budgets alert, they do not cap spend. Currency must match the account. Needs billingbudgets.googleapis.com. |
gcloud billing budgets list / describe / delete | Audit and remove budgets | --billing-account | The filter shows the project number, not the project ID. |
gcloud projects update PROJECT_ID --update-labels=k=v | Add allocation labels to a project | --update-labels, --remove-labels | Labels apply to future cost rows only. Keys and values are lowercase. |
bq query --use_legacy_sql=false 'SQL' | Query the billing export in BigQuery | --project_id, --use_legacy_sql=false, --dry_run | Query cost depends on bytes scanned. Use --dry_run first and filter by invoice.month. Export has no back-fill. |
Cloud Asset Inventory
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud services enable cloudasset.googleapis.com | Enable the API on the quota project | --project | Also pass --billing-project to asset commands when running from another project. |
gcloud asset search-all-resources | Search resources in a scope | --scope=organizations/ORG_ID, --query, --asset-types, --page-size, --format | Eventually consistent. Results are limited to what the caller can see. |
gcloud asset search-all-iam-policies | Find IAM bindings across a scope | --scope, --query="policy:roles/owner" | Run as an identity with organization-level viewer rights for complete results. |
gcloud asset export | Write a snapshot to Cloud Storage or BigQuery | --organization / --folder / --project, --content-type, --asset-types, --output-path=gs://BUCKET/FILE, --snapshot-time | The service agent needs write access to the bucket. Filter by asset type to keep the file small. |
gcloud asset feeds create FEED_ID | Publish asset changes to Pub/Sub | --organization / --project, --content-type, --asset-types, --pubsub-topic | Topic must allow the Cloud Asset service agent to publish. Test with a known change. |
gcloud asset get-history | See an asset's recorded state over a recent window | --asset-names="//compute.googleapis.com/...", --content-type, --start-time, --end-time | Limited look-back. Keep snapshots for older questions. |
Typical one-liners
# Who created or changed IAM on a project in the last day? gcloud logging read 'protoPayload.methodName:"SetIamPolicy"' --project=PROJECT_ID --freshness=1d \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)" # Is the central sink healthy? (filter, destination, writer identity) gcloud logging sinks describe SINK_NAME --organization=ORG_ID # Which projects have no cost-center label? (resource search; check query syntax in your release) gcloud asset search-all-resources --scope=organizations/ORG_ID \ --asset-types=cloudresourcemanager.googleapis.com/Project --format=json # Budgets on a billing account gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID --format="table(displayName,amount.specifiedAmount.units)"
Decision shortcuts
| Question | Use |
|---|---|
| Who did it? | gcloud logging read on the Admin Activity log (principalEmail, methodName) |
| What exists now across the organization? | gcloud asset search-all-resources |
| Evidence file for the auditor? | gcloud asset export to a retention-locked bucket |
| Tell me when a public bucket appears? | Asset feed plus Organization Policy to prevent it |
| Central copy of audit logs? | Organization sink with --include-children to a log bucket |
| Warn me before the bill? | Budget with 50, 90, 100 percent actual and forecast rules |
| Limit damage from a runaway? | Quota, Organization Policy, and automation on the budget topic (budgets alone do not cap) |
| Logs are missing? | Source, exclusions, sink filter, writer identity, query view (in that order) |
gcloud components update in a sandbox, read --help, and prefer Terraform for anything that must be repeated.Capstone lab and final quiz
Capstone lab, Hour 6: a governed audit and cost pipeline
Goal. Build the smallest complete version of the logging, audit and cost layer of a landing zone and prove each part works: a central log bucket with a controlled retention, an audit sink with a verified writer identity, an alert on changes to the sink, an asset snapshot and feed, and a budget with notifications. Then break one part on purpose, find it with the triage order, and clean everything up.
Total time: about 45 minutes. Cost: low (usually well under a few USD per day for this lab). The resources are mostly metadata; log ingestion of Admin Activity entries is free and the data volume is tiny. Budgets send alerts and do not cap spend, so the cleanup at the end is part of the lab. IDs in the expected output are illustrative.
Prerequisites
- A sandbox project
PROJECT_IDwith billing linked toBILLING_ACCOUNT_ID, and you as Owner. Never run this in a production project. - gcloud CLI (current release channel), authenticated with your own identity. No service account keys, no passwords.
- Roles for the optional organization path:
roles/logging.configWriterandroles/cloudasset.vieweronORG_ID, and a logging project. Without an organization, every command below works at project scope. - A region
REGIONfor the snapshot bucket.
Architecture of the result
- Audit path: Admin Activity entries from the project go through the sink
cap-audit-sinkinto the log bucketcap-audit(retention 30 days). - Detection path: a log-based metric counts changes to sinks, and an alerting policy (console flow) notifies a channel.
- Inventory path: a snapshot of resources goes to Cloud Storage, and a feed publishes topic changes to Pub/Sub.
- Cost path: the budget
cap-h6-monthlywith actual and forecast rules and a Pub/Sub notification topic.
Steps
- Variables, billing link, APIs.
export PROJECT_ID=PROJECT_ID export BILLING_ACCOUNT_ID=BILLING_ACCOUNT_ID export REGION=REGION gcloud config set project "$PROJECT_ID" gcloud billing projects describe "$PROJECT_ID" --format="value(billingEnabled)" gcloud services enable logging.googleapis.com monitoring.googleapis.com pubsub.googleapis.com \ cloudasset.googleapis.com billingbudgets.googleapis.com --project="$PROJECT_ID"
Verification. The describe command prints
True.gcloud services list --enabled --filter="name:(cloudasset OR billingbudgets OR pubsub)"shows three services. - Budget first.
gcloud pubsub topics create cap-budget-alerts --project="$PROJECT_ID" gcloud billing budgets create \ --billing-account="$BILLING_ACCOUNT_ID" \ --display-name="cap-h6-monthly" \ --budget-amount=20USD \ --filter-projects="projects/$PROJECT_ID" \ --calendar-period=month \ --threshold-rule=percent=0.5 \ --threshold-rule=percent=0.9 \ --threshold-rule=percent=1.0,basis=forecasted-spend \ --notifications-rule-pubsub-topic="projects/$PROJECT_ID/topics/cap-budget-alerts"
Verification.
gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="table(displayName,amount.specifiedAmount.units)"listscap-h6-monthly. Describe it and confirm three threshold rules and the topic. Use your billing account currency in place ofUSDif it differs. If the notification flag is rejected, checkgcloud billing budgets create --helpand attach the topic in the console.DISPLAY_NAME UNITS cap-h6-monthly 20
- Allocation labels.
gcloud projects update "$PROJECT_ID" --update-labels=env=lab,cost-center=cc0000,owner=you
Verification.
gcloud projects describe "$PROJECT_ID" --format="value(labels)"shows the three labels. - Central log bucket.
gcloud logging buckets create cap-audit --project="$PROJECT_ID" --location=global \ --retention-days=30 --description="Capstone: routed audit logs"
Verification.
gcloud logging buckets describe cap-audit --project="$PROJECT_ID" --location=global --format="value(retentionDays,lifecycleState)"prints30 ACTIVE. - Audit sink.
gcloud logging sinks create cap-audit-sink \ "logging.googleapis.com/projects/$PROJECT_ID/locations/global/buckets/cap-audit" \ --project="$PROJECT_ID" \ --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivity"' gcloud logging sinks describe cap-audit-sink --project="$PROJECT_ID"
Verification. The describe output shows your filter, the bucket destination and a
writerIdentity. Organization form: create the same sink with--organization=ORG_ID --include-children(no--project), point it to the bucket in the logging project, and grant the writer identityroles/logging.bucketWriterthere. - Generate an audit event and read it back.
gcloud pubsub topics create cap-event-1 --project="$PROJECT_ID" sleep 45 gcloud logging read 'protoPayload.methodName="google.pubsub.v1.Publisher.CreateTopic" AND protoPayload.resourceName:"cap-event-1"' \ --project="$PROJECT_ID" --bucket=cap-audit --location=global --view=_AllLogs \ --freshness=1h --limit=1 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName)"
TIMESTAMP PRINCIPAL_EMAIL METHOD_NAME 2026-11-25T10:21:07.452Z you@example.com google.pubsub.v1.Publisher.CreateTopic
Verification. One row with your own address as the principal. If it is empty, wait 30 seconds and read again. If it stays empty, run
sinks describe(filter and destination), then createcap-event-2; the sink only routes entries written after it exists. - Detect changes to the sink (log-based metric and alert). Create a log-based metric that counts sink changes, then create the alerting policy in the console.
gcloud logging metrics create cap-sink-changes \ --project="$PROJECT_ID" \ --description="Counts UpdateSink and DeleteSink calls" \ --log-filter='protoPayload.methodName=("google.logging.v2.ConfigServiceV2.UpdateSink" OR "google.logging.v2.ConfigServiceV2.DeleteSink")'Console flow. Monitoring, Alerting, Create policy: select the metric
logging/user/cap-sink-changes, condition "above 0" over a short window, add a notification channel (your email), name the policycap-sink-changed. Alternatively, create a log-based alert from Logs Explorer with the same filter.Verification.
gcloud logging metrics describe cap-sink-changes --project="$PROJECT_ID"prints the filter, and the alerting page lists the policy with one channel. To test, update the sink description or filter once (step 11 does this) and look for the notification and the incident; metrics and alerts can take a few minutes. A policy with no channel is a failed step. - Inventory: search, snapshot, feed.
export SNAP_BUCKET="${PROJECT_ID}-cap-snapshots" gcloud storage buckets create "gs://$SNAP_BUCKET" --project="$PROJECT_ID" \ --location="$REGION" --uniform-bucket-level-access gcloud asset search-all-resources --scope="projects/$PROJECT_ID" --asset-types=pubsub.googleapis.com/Topic \ --format="table(name.basename(),location)" gcloud asset export --project="$PROJECT_ID" --content-type=resource \ --output-path="gs://$SNAP_BUCKET/cap-snap-1.json" gcloud pubsub topics create cap-asset-changes --project="$PROJECT_ID" gcloud pubsub subscriptions create cap-asset-changes-sub --topic=cap-asset-changes --project="$PROJECT_ID" gcloud asset feeds create cap-topic-feed --project="$PROJECT_ID" --content-type=resource \ --asset-types="pubsub.googleapis.com/Topic" \ --pubsub-topic="projects/$PROJECT_ID/topics/cap-asset-changes"Verification. The search lists the topics you created. After about a minute
gcloud storage ls "gs://$SNAP_BUCKET/"showscap-snap-1.json. Create a topic (gcloud pubsub topics create cap-event-3), wait one to two minutes, and rungcloud pubsub subscriptions pull cap-asset-changes-sub --auto-ack --limit=3 --format=json: a message namestopics/cap-event-3. If the export fails with a permission error, grant the Cloud Asset service agent write access to the bucket and run it again. - Cost visibility check. In the console open Billing, Billing export and note whether BigQuery export is enabled. If yes, run the cost-by-label query from Module 5 against your billing dataset (use
--dry_runfirst).Verification. The query returns rows, with a visible
cost_centervalue orNULLfor unlabeled cost. If export is not enabled, write down the dataset and project you would use, and note that export is not back-filled. - Break it on purpose, then find it. Edit the sink filter with a typo, create a new event, and use the triage order.
gcloud logging sinks update cap-audit-sink --project="$PROJECT_ID" \ --log-filter='logName="projects/'"$PROJECT_ID"'/logs/cloudaudit.googleapis.com%2Factivty"' gcloud pubsub topics create cap-event-4 --project="$PROJECT_ID" sleep 60 gcloud logging read 'protoPayload.resourceName:"cap-event-4"' --project="$PROJECT_ID" \ --bucket=cap-audit --location=global --view=_AllLogs --freshness=1h --limit=1
Verification of the fault. The bucket read is empty, while
gcloud logging read 'protoPayload.resourceName:"cap-event-4"' --project="$PROJECT_ID" --freshness=1h --limit=1(the source) returns the entry. Following the triage order: source has it (step 1 passes), no exclusions on_Defaultapply to this sink (step 2),sinks describe cap-audit-sinkshowsactivty(step 3 fails). Fix with the correct filter, createcap-event-5, and confirm it arrives. The sink change itself should also have produced anUpdateSinkentry and, after a few minutes, the alert from step 7.
Expected output summary
| Part | What you should see |
|---|---|
| Budget | cap-h6-monthly listed, three threshold rules, Pub/Sub topic attached |
| Labels | env, cost-center, owner on the project |
| Log bucket | cap-audit, 30 days, ACTIVE |
| Sink | Filter on the Admin Activity log, bucket destination, writer identity present |
| Audit event | CreateTopic entry in the bucket with your identity as principalEmail |
| Detection | Metric cap-sink-changes and a policy with a notification channel; an incident after the sink edit |
| Inventory | One snapshot file and one feed message naming a new topic |
| Fault | Empty bucket read until the filter typo is fixed; entries appear again afterwards |
Cost
Low (usually well under a few USD per day for this lab). Admin Activity audit entries are free to ingest, the log bucket holds only a few entries, Pub/Sub carries a handful of messages, and the snapshot files are tiny. The budget, labels, sink, metric and feed are metadata. A forgotten lab still costs little, but forgotten resources in a real project are how bills grow, so run the cleanup. Budgets send alerts and do not cap spend.
Cleanup (in this order)
gcloud asset feeds delete cap-topic-feed --project="$PROJECT_ID" gcloud logging sinks delete cap-audit-sink --project="$PROJECT_ID" gcloud logging metrics delete cap-sink-changes --project="$PROJECT_ID" gcloud pubsub subscriptions delete cap-asset-changes-sub --project="$PROJECT_ID" for t in cap-asset-changes cap-budget-alerts cap-event-1 cap-event-2 cap-event-3 cap-event-4 cap-event-5; do gcloud pubsub topics delete "$t" --project="$PROJECT_ID" --quiet done gcloud storage rm --recursive "gs://$SNAP_BUCKET" gcloud logging buckets delete cap-audit --project="$PROJECT_ID" --location=global gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(name,displayName)" gcloud billing budgets delete BUDGET_ID --billing-account="$BILLING_ACCOUNT_ID"
Delete the alerting policy cap-sink-changed in the console (Monitoring, Alerting) or with gcloud monitoring policies delete POLICY_ID if your SDK has the command, and delete the notification channel if you created it only for this lab. Topics that you did not create return NOT_FOUND, which is harmless.
Verify the cleanup.
gcloud logging sinks list --project="$PROJECT_ID" --format="value(name)" gcloud logging metrics list --project="$PROJECT_ID" --format="value(name)" gcloud logging buckets list --project="$PROJECT_ID" --location=global --format="value(name,lifecycleState)" gcloud pubsub topics list --project="$PROJECT_ID" --format="value(name)" gcloud asset feeds list --project="$PROJECT_ID" gcloud billing budgets list --billing-account="$BILLING_ACCOUNT_ID" --format="value(displayName)"
Only _Default and _Required sinks remain, the metric and feed lists are empty, cap-audit is DELETE_REQUESTED (it disappears after the pending period), no cap- topics remain, and the budget is gone. Keep the project labels if you like; they are free.
gcloud COMMAND --help for every command in your SDK release, and keep the final configuration in Terraform rather than in a shell history.Knowledge check
Sources and versions
Reference documentation for Hour 6
These are the official pages behind the commands and concepts in this hour. They are the source of truth when a flag, a role name, or a default differs from what is written in the course.
Cloud Logging and Cloud Audit Logs
- Cloud Audit Logs overview: Admin Activity, Data Access, System Event and Policy Denied logs, log names, and what is enabled by default.
- Routing and storage overview: the log router, the
_Requiredand_Defaultsinks and buckets, exclusions, retention. - Configure and manage sinks: sink destinations, writer identity, filters, organization and folder sinks with
--include-children. - Configure log buckets: user-defined buckets, locations, retention, views, locking, CMEK, Log Analytics.
- Logging query language: the filter syntax used in
gcloud logging readand sinks. - Log-based metrics: counting entries and alerting on them.
- Log Analytics: SQL queries over log buckets upgraded for analytics.
- Cloud Logging pricing: where ingestion, storage and retention charges are defined. Check current figures there; this course states no prices.
- gcloud logging reference:
read,sinks,buckets,metrics.
Cloud Monitoring
- Alerting overview: policies, conditions, notification channels, incidents.
- Notification options: channel types and how to create and verify them.
- Uptime checks: public and private checks and their alerts.
- Metrics scopes: which projects a Monitoring view can see.
Cloud Billing, budgets and cost
- Create, edit, or delete budgets and budget alerts: amounts, filters, threshold rules, recipients.
- Programmatic budget notifications: the Pub/Sub message and automation patterns, including that a budget does not cap usage.
- Export Cloud Billing data to BigQuery: standard, detailed and pricing exports, and the schema.
- Creating and managing labels: label rules and limits.
- Committed use discounts: resource-based and spend-based commitments.
- gcloud billing budgets reference.
Cloud Asset Inventory
- Cloud Asset Inventory overview.
- Search resources and search IAM policies.
- Export to Cloud Storage and export to BigQuery.
- Monitor asset changes with feeds and Pub/Sub.
- gcloud asset reference.
Landing zone guidance and infrastructure as code
- Google Cloud enterprise foundations blueprint (security foundations): the centralized logging and billing patterns this hour follows.
- terraform-example-foundation on GitHub: a Terraform reference for the foundation, including organization sinks and budgets.
- terraform-google-log-export on GitHub: a module for log sinks and destinations.
- google_logging_organization_sink and google_billing_budget in the Terraform Google provider documentation.
Tools and versions used in this hour
| Tool | Version used in the course | How to check |
|---|---|---|
Google Cloud CLI (gcloud) | Current release channel. Cloud Shell always has a current version. | gcloud version and gcloud components update (local installs) |
bq (BigQuery command-line tool) | Installed with the Google Cloud CLI | bq version |
| Terraform (referenced, not required in this hour) | Terraform 1.x with the Google provider (pin the major version in required_providers) | terraform version |
| Cloud Logging, Cloud Monitoring, Cloud Billing, Cloud Asset Inventory | Managed services; behaviour follows the live documentation | Release notes pages for each product |
gcloud command groups move from alpha or beta to GA. Every command in this course was written to be conservative, but you must check gcloud COMMAND --help, the reference pages above and the current pricing pages in a sandbox before you apply anything to a production organization. Keep production changes in Terraform with reviewed plans, not in a shell history.Examples in this hour use illustrative IDs, project names and dates, and the output blocks are samples of the documented format, not recorded measurements. No prices are quoted: use the official pricing pages and your own billing export.