Skip to content

🏗️ Resource Hierarchy

Level: Foundation Solves: Thiết kế và quản lý resource organization theo chuẩn enterprise với proper inheritance và governance

🎯 Mục tiêu (Outcomes)

Sau khi áp dụng kiến thức trong trang này, bạn sẽ có khả năng:

  • Thiết kế GCP Organization Structure với proper folder hierarchy
  • Triển khai Organization Policies cho governance và compliance
  • Xây dựng Project Naming Convention consistent và scalable
  • Cấu hình Labels và Tags cho cost allocation và IAM conditions
  • Hiểu Policy Inheritance và override mechanisms
  • So sánh với AWS Organizations và OUs

Khi nào dùng

PatternUse CaseLý do
Environment foldersSeparate prod/non-prodPolicy isolation, blast radius
Team sub-foldersMulti-team organizationOwnership, self-service
Shared services folderCentral logging, monitoringCross-cutting concerns
Sandbox folderDeveloper experimentationRelaxed policies, isolation
Organization PoliciesCompliance requirementsEnforce guardrails

Khi nào KHÔNG dùng

PatternVấn đềThay thế
Flat project structureKhó manage scaleFolder hierarchy
Deep nesting (> 5 levels)Complexity, policy conflictsFlatter structure
One project per serviceProject quota exhaustionConsolidate related services
Same project cho all envsBlast radius, access controlSeparate proj per env

⚠️ Cảnh báo từ Raizo

"Một startup bắt đầu với 1 project cho tất cả. 2 năm sau với 50 microservices, billing là nightmare - không biết service nào tốn bao nhiêu. Migration sang multi-project mất 6 tháng. Plan hierarchy từ đầu."

Core Concepts

GCP Resource Hierarchy

┌─────────────────────────────────────────────────────────────────┐
│                  GCP RESOURCE HIERARCHY                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│                    ┌─────────────────┐                          │
│                    │  Organization   │  ← Cloud Identity/       │
│                    │  (example.com)  │    Workspace domain      │
│                    └────────┬────────┘                          │
│                             │                                   │
│         ┌───────────────────┼───────────────────┐               │
│         │                   │                   │               │
│         ▼                   ▼                   ▼               │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐         │
│  │   Folder    │    │   Folder    │    │   Folder    │         │
│  │ Production  │    │   Staging   │    │    Dev      │         │
│  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘         │
│         │                  │                  │                 │
│    ┌────┴────┐        ┌────┴────┐        ┌────┴────┐           │
│    │         │        │         │        │         │           │
│    ▼         ▼        ▼         ▼        ▼         ▼           │
│ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐         │
│ │Proj A│ │Proj B│ │Proj C│ │Proj D│ │Proj E│ │Proj F│         │
│ └──────┘ └──────┘ └──────┘ └──────┘ └──────┘ └──────┘         │
│                                                                 │
│  KEY INSIGHT: IAM policies và Organization Policies             │
│  inherit DOWN the hierarchy                                     │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Hierarchy Components

ComponentPurposeLimit
OrganizationRoot node, tied to Cloud Identity domain1 per domain
FolderGrouping mechanism for projects10 levels deep
ProjectContainer for resources, billing boundaryUnlimited
ResourceActual GCP services (VMs, buckets, etc.)Per-project quotas

Enterprise Folder Structure

Organization (example.com)
├── 📁 Bootstrap
│   └── 📦 prj-bootstrap (Terraform state, CI/CD)
├── 📁 Common
│   ├── 📦 prj-logging (Centralized logs)
│   ├── 📦 prj-monitoring (Centralized monitoring)
│   └── 📦 prj-security (Security tools)
├── 📁 Network
│   ├── 📦 prj-network-hub (Shared VPC host)
│   └── 📦 prj-network-dns (Cloud DNS)
├── 📁 Production
│   ├── 📁 Team-A
│   │   ├── 📦 prj-prod-team-a-app1
│   │   └── 📦 prj-prod-team-a-app2
│   └── 📁 Team-B
│       └── 📦 prj-prod-team-b-app1
├── 📁 Non-Production
│   ├── 📁 Staging
│   │   └── 📦 prj-stg-*
│   └── 📁 Development
│       └── 📦 prj-dev-*
└── 📁 Sandbox
    └── 📦 prj-sandbox-* (Experimentation)

Folder Design Principles

💡 Design Guidelines

  1. Environment-first: Top-level folders by environment (prod/non-prod)
  2. Team ownership: Sub-folders by team or business unit
  3. Shared services: Dedicated folders for cross-cutting concerns
  4. Sandbox isolation: Separate folder for experimentation

Organization Policies

Policy Inheritance

Essential Organization Policies

yaml
# Restrict resource locations
constraints/gcp.resourceLocations:
  allowedValues:
    - asia-southeast1
    - asia-southeast2
    - us-central1

# Disable service account key creation
constraints/iam.disableServiceAccountKeyCreation:
  enforced: true

# Require OS Login for VMs
constraints/compute.requireOsLogin:
  enforced: true

# Restrict public IP on VMs
constraints/compute.vmExternalIpAccess:
  deniedValues:
    - all

# Restrict VPC peering
constraints/compute.restrictVpcPeering:
  allowedValues:
    - under:organizations/123456789

Policy Hierarchy Example

┌─────────────────────────────────────────────────────────────────┐
│              ORGANIZATION POLICY INHERITANCE                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Organization Level:                                            │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ • Disable SA key creation: ENFORCED                     │    │
│  │ • Require OS Login: ENFORCED                            │    │
│  │ • Resource locations: asia-*, us-*                      │    │
│  └─────────────────────────────────────────────────────────┘    │
│                          │                                      │
│                          ▼                                      │
│  Production Folder:                                             │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ • Inherits all org policies                             │    │
│  │ • + Restrict external IPs: ENFORCED                     │    │
│  │ • + Resource locations: asia-southeast1 ONLY            │    │
│  └─────────────────────────────────────────────────────────┘    │
│                          │                                      │
│                          ▼                                      │
│  Sandbox Folder:                                                │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ • Inherits org policies                                 │    │
│  │ • EXCEPTION: Allow external IPs (for testing)           │    │
│  │ • EXCEPTION: Allow SA keys (for local dev)              │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Project Naming Convention

{org-prefix}-{env}-{team}-{app}-{random}

Examples:
- acme-prod-platform-api-a1b2
- acme-dev-data-pipeline-c3d4
- acme-stg-mobile-backend-e5f6

Naming Rules

ComponentFormatExample
org-prefix2-4 chars, lowercaseacme
envprod/stg/dev/sbxprod
teamteam or BU nameplatform
appapplication nameapi
random4 chars for uniquenessa1b2

⚠️ Project ID Constraints

  • Globally unique across all of GCP
  • 6-30 characters
  • Lowercase letters, digits, hyphens
  • Must start with letter
  • Cannot end with hyphen
  • Cannot be changed after creation

Labels & Tags

Label Strategy

yaml
# Required labels for all resources
labels:
  environment: production|staging|development|sandbox
  team: platform|data|mobile|security
  cost-center: cc-12345
  application: api-gateway
  managed-by: terraform|console|gcloud
  
# Optional labels
  owner: team-email@example.com
  compliance: pci|hipaa|sox
  data-classification: public|internal|confidential|restricted

Tags for IAM Conditions

┌─────────────────────────────────────────────────────────────────┐
│                    TAGS vs LABELS                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  LABELS                              TAGS                       │
│  ──────                              ────                       │
│  • Key-value metadata                • Hierarchical namespace   │
│  • For organization/billing          • For IAM conditions       │
│  • Applied to resources              • Applied to resources     │
│  • No IAM integration                • IAM-aware                │
│                                                                 │
│  Example Label:                      Example Tag:               │
│  environment: production             tagKeys/env/tagValues/prod │
│                                                                 │
│  Use Case:                           Use Case:                  │
│  Cost allocation, filtering          Conditional access control │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

GCP vs AWS Comparison

ConceptGCPAWS
RootOrganizationOrganization
GroupingFolders (10 levels)OUs (5 levels)
Workload ContainerProjectAccount
Policy InheritanceOrganization PoliciesSCPs
BillingBilling Account → ProjectsConsolidated Billing
Identity SourceCloud Identity/WorkspaceIAM Identity Center

Best Practices Checklist

  • [ ] Organization linked to Cloud Identity domain
  • [ ] Folder structure reflects environment and team ownership
  • [ ] Organization policies enforced at appropriate levels
  • [ ] Project naming convention documented and enforced
  • [ ] Labels strategy defined for cost allocation
  • [ ] Tags configured for IAM conditions
  • [ ] Sandbox folder with relaxed policies for experimentation
  • [ ] Shared services in dedicated projects

⚖️ Trade-offs

Trade-off 1: Folder Depth vs Simplicity

Khía cạnhDeep HierarchyFlat Hierarchy
GranularityHighLow
Policy flexibilityMore override pointsSimpler inheritance
Management overheadCaoThấp
NavigationComplexSimple

Khuyến nghị: 2-4 levels là optimal. Environment > Team > (Optional: Application)


Trade-off 2: Project Granularity

ApproachProject per...ProsCons
FineMicroserviceIsolation, billing clarityQuota issues, many projects
MediumApplicationBalancedMedium complexity
CoarseTeamSimpleBlast radius, billing unclear

Trade-off 3: Shared VPC vs Standalone VPCs

Khía cạnhShared VPCStandalone VPCs
IP managementCentralizedDistributed
Firewall rulesHost projectPer project
ComplexityHigherLower
SecurityBetter controlProject-level

🚨 Failure Modes

Failure Mode 1: Organization Policy Blocks Production

🔥 Incident thực tế

Org policy "Disable external IPs" enforced tại org level. Team cần external IP cho NAT Gateway trong new project. Deployment blocked 2 ngày pending exception approval.

Cách phát hiệnCách phòng tránh
Deployment failuresTest policies trong sandbox
Policy violation errorsException process documented
Blocked resource creationFolder-level overrides ready

Failure Mode 2: Project Quota Exhaustion

Cách phát hiệnCách phòng tránh
"Quota exceeded" errorsMonitor project quotas
Cannot create new projectsRequest quota increase early
Rate limitingUse folders to distribute

Failure Mode 3: Label Inconsistency

Cách phát hiệnCách phòng tránh
Cost allocation gapsTerraform label enforcement
"Untagged" in billingOrganization policy for labels
Billing reconciliation issuesRegular label audit

🔐 Security Baseline

Essential Organization Policies

PolicySettingVì sao
iam.disableServiceAccountKeyCreationEnforcedPrevent key leaks
compute.requireOsLoginEnforcedSSH key management
compute.vmExternalIpAccessDeny all (prod)Reduce attack surface
storage.uniformBucketLevelAccessEnforcedSimplify ACLs
iam.allowedPolicyMemberDomainsYour domains onlyPrevent external sharing

Hierarchy Security

LevelSecurity Focus
OrganizationIdentity, global policies
Folder (Prod)Strictest policies
Folder (Non-prod)Moderate policies
Folder (Sandbox)Minimal restrictions
ProjectResource-specific

📊 Ops Readiness

Metrics cần Monitoring

MetricSourceAlert Threshold
Project countResource Manager> 80% quota
Policy violationsSecurity Command CenterAny
Unlabeled resourcesAsset Inventory> 5%
Folder depthCustom> 5 levels

Runbook Entry Points

Tình huốngRunbook
New project creationrunbook/project-provisioning.md
Organization policy exceptionrunbook/org-policy-exception.md
Folder restructuringrunbook/folder-migration.md
Label remediationrunbook/label-enforcement.md
Quota increase requestrunbook/quota-increase.md

Design Review Checklist

Structure

  • [ ] Organization linked và verified
  • [ ] Folder hierarchy reflects environment/team
  • [ ] Shared services isolated
  • [ ] Sandbox folder available

Governance

  • [ ] Organization policies defined
  • [ ] Exception process documented
  • [ ] Naming convention enforced
  • [ ] Labels mandatory

Security

  • [ ] Security policies at org level
  • [ ] Production folder stricter
  • [ ] SA key creation disabled
  • [ ] External IP restricted

Operations

  • [ ] Project quota monitored
  • [ ] Label compliance tracked
  • [ ] Runbooks documented
  • [ ] IaC for provisioning

📎 Liên kết