Generated banner for Google Cloud Solution N Tier Serverless Web App
Generated logo for Google Cloud Solution N Tier Serverless Web App

Google Cloud Solution N Tier Serverless Web App

GoogleOfficialPublished by Google

  • Skill
  • Workflow
  • Cloud and DevOps
  • Apache-2.0
  • Low risk

From the author

Assists in designing and implementing secure n-tier serverless web applications and microservices on Google Cloud. Use when users need architecture designs, security checklists, Terraform code, or deployment guidance for multi-tier serverless apps, regional data residency / European sovereignty compliance, zero-trust private VPC networking, or Private Service Connect. Don't use for VM, GKE, or non-Google Cloud architectures.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for designing and deploying multi-tier serverless web applications using Google Cloud Run and Cloud SQL. It focuses on implementing strict network isolation, zero-trust VPC networking, and secure service-to-service communication. The skill guides users through requirements analysis, architecture design, Infrastructure as Code (Terraform) generation, and validation, ensuring adherence to specific security boundaries and network configurations.

What it does

  • Generates architecture designs for multi-tier serverless applications on Google Cloud.
  • Provides Terraform templates for secure infrastructure deployment.
  • Enforces security boundaries including VPC-internal ingress and least-privilege firewall policies.
  • Creates custom automated validation scripts to verify deployment integrity.
  • Offers step-by-step gcloud CLI commands for manual or scripted deployment.
  • Maps application components to specific Google Cloud products like Cloud Run, Cloud SQL, and Cloud Armor.

When to use it

  • When designing a multi-tier serverless web application on Google Cloud.
  • When you need to implement strict network isolation between frontend, application, and data tiers.
  • When you require Terraform code that adheres to specific security and networking best practices.
  • When you need to validate that a serverless deployment meets defined security and connectivity requirements.

Advantages

  • Provides a consistent, opinionated golden path for secure serverless architectures.
  • Reduces manual configuration errors through standardized Terraform and gcloud scripts.
  • Ensures security best practices are integrated directly into the infrastructure design.
  • Facilitates automated verification of complex multi-tier network and security configurations.

Usage examples

“Design a 3-tier serverless web app on Google Cloud using Cloud Run and Cloud SQL.”
The agent will provide a 3-tier architecture design, including the necessary security boundaries, and offer to generate the corresponding Terraform code.
“Generate Terraform code for a secure serverless application with Private Service Connect.”
The agent will output the complete Terraform HCL code block configured for Private Service Connect and secure VPC networking.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/google-cloud-solution-n-tier-serverless-web-app/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip google-cloud-solution-n-tier-serverless-web-app.zip -d .agents/skills

Documentation by Google

<!-- disableFinding(all) -->

<!-- mdlint off -->

Secure n-tier serverless web application with strict private application tiers

This skill guides agents through the workflow of designing and implementing a secure serverless web application with as many architectural design layers as specified by the user. It uses Cloud Run for the serverless layers and Cloud SQL for PostgreSQL as the data layer. A three-tier web application might be represented in three architectural layers: a Cloud Run presentation layer, a Cloud Run application layer, and a Cloud SQL for PostgreSQL database layer.

The architecture enforces strict physical and network isolation across all tiers (T1 to TN):

  • Tier 1 presentation tier (frontend / reverse proxy): Public-facing UI rendering/gateway service (Cloud Run). Exposes the entry point via Cloud Load Balancing and routes requests downstream to internal tiers privately via Direct VPC Egress.

  • Tier 2..N application tier (internal microservices / business logic): Private application services (Cloud Run). 100% isolated from the internet (Ingress: VPC-internal, INGRESS_TRAFFIC_INTERNAL_ONLY), reachable exclusively via upstream VPC routing (egress = "ALL_TRAFFIC" with Private Google Access on the subnet for *.run.app URLs).

  • Data tier: Private Cloud SQL for persistent data and Memorystore for Redis for caching, reachable exclusively from authorized application tiers.

Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read and follow the instructions in Usage Attribution.

General guidance to the LLM

1. Direct Resource Map (Zero-Search File Access)

All necessary reference architectures, HCL templates, and checklists are co-located in this skill. Use exact relative paths from this skill folder:

Asset PathPurpose & Usage
assets/main.tfSingle Source of Truth for Terraform (HCL). Contains all security boundaries, Cloud Run v2 configs, PSC endpoints, DNS private zones, and firewall rules.
assets/output-template.mdStandardized Solution Architecture report markdown structure.
references/non-negotiable-architectural-rules.mdNon-negotiable security rules, audit checklist, and product mappings.
references/related-guidance.mdSupplemental deep reference (do NOT read for standard design or IaC tasks; read only if specialized edge-case troubleshooting is explicitly required).
  • No Directory Crawling: Do NOT run list_dir chains down workspace directories to discover these files.

  • No Search Thrashing on Local Files: Do NOT run code_search or find_by_name queries to look inside assets/main.tf. Read the file directly using view_file once and reuse the context.

  • No Redundant Skill Searches: Do NOT call skill_search for serverless or n-tier architecture skills while executing this skill.

2. Direct Inline Generation (No Subagent Delegation)
  • Perform all architecture compilation, Terraform drafting, gcloud command assembly, and validation script generation directly in the primary conversation.

  • Do NOT invoke subagents (invoke_subagent) to research external GitHub Terraform modules, probe environment configs, or draft reports. All required patterns are fully contained in assets/main.tf and references/.

3. One-Shot Clean Artifact Writing
  • Generate complete, fully-rendered, and valid HCL blocks and Markdown reports in a single write_to_file call.

  • Avoid leaving placeholders or malformed code fences that require multi-turn replace_file_content and grep_search patch loops.

  • No Unpopulated Placeholders: When embedding code or scripts inside architecture reports (e.g., Section 6 of assets/output-template.md), always inline the actual complete Terraform code, gcloud commands, and validation script code. Never output literal template placeholder comments (e.g., # [Paste of main.tf file contents]).

  • In-Response Direct Rendering (Mandatory): Whenever Terraform code, deployment scripts, or architecture reports are requested or generated (e.g., "provide a design and Terraform code", "generate IaC"), you MUST print the complete generated terraform ... HCL code block and full solution report directly in your chat response text, in addition to writing them to files on disk. Never output only an architectural design summary or file links when code is requested; automated evaluation frameworks (such as Yardstick) evaluate the raw response text and fail all code assertions if the terraform code block is missing from the message.

4. Technical Completeness Checklist
  • When providing a concise architecture summary or security checklist (e.g., when instructed not to generate full IaC), you MUST explicitly include the following technical specifications:

    • For regional load balancer deployments: regional proxy-only subnet purpose (REGIONAL_MANAGED_PROXY) and network parameter on regional forwarding rules.

    • Cloud SQL PostgreSQL version (POSTGRES_18), Edition (Enterprise Edition), High Availability (Regional HA), and Private Service Connect (psc_enabled = true).

    • Cloud NGFW Firewall Policies:

      • MUST configure explicit Cloud NGFW network firewall policies (google_compute_network_firewall_policy, google_compute_network_firewall_policy_association, and google_compute_network_firewall_policy_rule with enable_logging = var.enable_monitoring) rather than legacy google_compute_firewall.

      • Enforce default egress deny (0.0.0.0/0).

      • Allow frontend egress to backend / PGA VIPs.

      • Allow backend database egress explicitly permitting TCP port 443 to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) in addition to TCP port 5432 so the Cloud SQL Auth Proxy sidecar can query sqladmin.googleapis.com on startup for IAM certificate exchange.

Workflow

[!TIP] Optional MCP Server Integration: If your AI coding client supports the Model Context Protocol (MCP), you can connect the Google Developer Knowledge MCP Server (npx -y @google/mcp-developer-knowledge-server) to dynamically query real-time Google Cloud documentation (cloud.google.com/docs) alongside this skill's offline knowledge base (references/related-guidance.md).

The solution design and implementation workflow is divided into the following phases:

  • Phase 1: Requirements discovery and analysis: Analyze the workload's requirements, constraints, dependencies, and current state.

  • Phase 2: Solution design & IaC drafting: Build a technology stack, architecture, and deployment configuration for the workload. IMPORTANT: You should offer to generate the complete Terraform code (based on assets/main.tf and adhering to all Phase 3 specifications) alongside the solution architecture during this phase. This allows the user to immediately review and iteratively modify the code as the conversation continues. However, if the user explicitly states they do not want code, do not generate it yet.

  • Phase 3: Implementation plan & iterative refinement: Modify and refine the generated design and deployment instructions as the conversation and user feedback evolve.

  • Phase 4: Solution validation: Validate that the deployment meets the requirements of the workload.


Phase 1: Requirements discovery and analysis

To prevent multi-turn interview fatigue and maintain trajectory determinism across evaluations, adopt an opinionated 80% default golden path unless the user explicitly requests deviations:

  1. Default Golden Path Configuration (80% Baseline):

    • Architecture: Secure 3-tier serverless pipeline (frontend Cloud Run -> backend application Cloud Run -> Cloud SQL PostgreSQL).

    • Region: us-central1.

    • Database: Cloud SQL for PostgreSQL (POSTGRES_18) Enterprise Edition via Private Service Connect (psc_enabled = true).

    • Edge Protection: Global external Application Load Balancer with Cloud Armor WAF (sqli-v33-stable) and Cloud CDN (enable_cdn = true).

    • Domain & SSL Mode: If the user specifies a domain (e.g., app.mycompany.com), configure var.domain_name with a Google-managed certificate (use_self_signed_cert = false) and provide DNS A record instructions. If testing in a sandbox without a domain, enable self-signed mode (use_self_signed_cert = true) for immediate testability.

    • Networking & Security: Direct VPC Egress (ALL_TRAFFIC), run.app. Cloud DNS private zone, least-privilege Cloud NGFW egress firewall policies (TCP 5432, 443), and Cloud SQL Auth Proxy sidecar (DB_SOCKET_PATH with IAM Auth).

  2. Disambiguation Protocol (Optional Clarification Questions): If the user's initial prompt leaves requirements open-ended (and is not fast-forwarding with exact specs), do not present a multi-topic questionnaire. Only ask concise clarifying questions as needed before confirmation:

    1. Load Balancer & Residency Topology: Do you require a Global Application Load Balancer with Cloud CDN (default for worldwide users), or a Regional Application Load Balancer without CDN (for strict EU/regional data residency compliance)?

    2. Custom Domain vs. Sandbox Testing: Do you have a registered domain name to configure with a Google-managed certificate, or should we configure self-signed testing mode (use_self_signed_cert = true) for immediate sandbox testing over IP?

    3. In-Memory Caching Tier: Should we provision an optional Memorystore for Redis caching tier (Private Services Access) alongside Cloud SQL to accelerate read queries?

  3. Verify & Confirm: Present the confirmed 3-tier golden path decomposition to the user and request confirmation before proceeding to Phase 2 (or fast-forward automatically when instructed).

Phase 2: Solution design
  1. Retrieve Architectural Guidance Efficiently:

    • Architecture Design & Security Checklist Requests: Retrieve ONLY the 9 architectural security boundaries and audit checklist from references/non-negotiable-architectural-rules.md. Do NOT retrieve references/related-guidance.md or assets/main.tf when only high-level design/checklists are requested without full Terraform code.

    • Terraform Implementation Requests: Retrieve references/non-negotiable-architectural-rules.md and assets/main.tf (Single Source of Truth for exact HCL). Do NOT retrieve references/related-guidance.md unless specialized edge-case troubleshooting is explicitly required.

  2. Map components to Google Cloud products: Map your confirmed decomposition directly to Google Cloud products using these mandatory product mapping specifications:

    • Public Ingress & WAF: global or regional external Application Load Balancer (INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER), Cloud Armor (sqli-v33-stable), Cloud CDN (if global Application Load Balancer; note that Cloud CDN is NOT supported on regional Application Load Balancers). Note: When deploying a regional external Application Load Balancer, an explicit proxy-only subnet (purpose = "REGIONAL_MANAGED_PROXY") is required in the VPC and network must be specified on the regional forwarding rule.

    • Internal compute tiers (T1 to TN): Cloud Run microservices (INGRESS_TRAFFIC_INTERNAL_ONLY), Direct VPC Egress configured with egress = "ALL_TRAFFIC", Private Google Access enabled on the subnet, and a Cloud DNS Managed Private Zone (google_dns_managed_zone) for run.app. bound to vpc_network mapping *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30) when calling internal *.run.app URLs, deployed from specified/placeholder container image.

    • Private data tier: Cloud SQL for PostgreSQL (POSTGRES_18) via Private Service Connect + IAM DB Auth. If database caching was selected, add Memorystore Redis via Private Services Access. Depending on reliability requirements, specify either "Cloud SQL for PostgreSQL Enterprise edition instance" or a "Cloud SQL for PostgreSQL Enterprise Plus edition instance".

    • Secrets, Registry, & Security: Secret Manager, Artifact Registry, Cloud NGFW global/regional network firewall policies (google_compute_network_firewall_policy + google_compute_network_firewall_policy_rule explicitly permitting outbound TCP port 5432 to Cloud SQL PSC IP and TCP port 443 to Private Google Access VIPs 199.36.153.4/30, 199.36.153.8/30 on allow_backend_db_egress), and optional VPC Service Controls.

  3. Create architecture diagram: Create a clean Mermaid format architecture diagram (assets/output-template.md) illustrating the multi-tier request and data flow across entry point, public reverse proxy, private microservice compute tiers, and private database/caching endpoints.

  4. Draft solution architecture and generate Terraform & gcloud CLI code: Compile the requirements, technical decomposition, product mapping, architecture diagram, design recommendations, AND the complete Infrastructure as Code (Terraform based on assets/main.tf alongside a self-contained sequence of gcloud CLI deployment commands adhering to all Phase 3 mandatory specifications) into a single Markdown file structured strictly per the standardized Google Cloud Solution Architecture output When saving or outputting the report artifact, append an ISO 8601 UTC timestamp and ensure the filename strictly ends with the .md extension (e.g., workload_name_architecture_report-20260701T212820Z.md). Verify that all 9 security boundaries from assets/main.tf are documented cleanly in your report and all template placeholders are replaced with actual complete code blocks. In your response, provide the executive architecture overview, the 9 key security & network boundaries enforced, the complete deploy-ready Terraform code block (```terraform ... ```), and step-by-step deployment instructions with links to the generated artifacts (always inlining the complete Terraform code directly in the response when code is requested, rather than only providing file links).

  5. Request review and iterate: Present the solution architecture (and Terraform code, gcloud script, or validation script if generated) to the user and request feedback. Modify and refine both the architecture and code iteratively as the conversation continues.


Phase 3: Implementation plan
  1. Retrieve relevant building block templates from the assets/ directory. Important: Use the code in assets/main.tf as the foundation for your Terraform implementation plan (assets/output-template.md for architecture structure).

  2. Identify deployment prerequisites:

    • Required Google Cloud APIs (run.googleapis.com, sqladmin.googleapis.com, redis.googleapis.com, servicenetworking.googleapis.com, secretmanager.googleapis.com, monitoring.googleapis.com, dns.googleapis.com).

    • Required IAM permissions (Project Editor, Security Admin, etc.).

  3. Generate Infrastructure as Code (IaC) (Architectural Specifications): Retrieve relevant architectural and hierarchy guidance from references/non-negotiable-architectural-rules.md. Base code strictly on the building blocks in assets/main.tf (Section 1.5 for Cloud NGFW firewall policies, Section 5.1 for Tier 1, Section 5.2 for Tiers 2..N), ensuring database_version = "POSTGRES_18" is preserved exactly. Ensure firewall policies strictly use Cloud NGFW resources (google_compute_network_firewall_policy, google_compute_network_firewall_policy_association, and google_compute_network_firewall_policy_rule with enable_logging = var.enable_monitoring). NEVER generate legacy google_compute_firewall resources or revert to older database versions like POSTGRES_15.

  4. Write deployment instructions & README.md: Draft comprehensive step-by-step deployment instructions (or a complete README.md artifact), ensuring you include:

    • Instructions to initialize and apply Terraform (terraform init, terraform apply). Zero-Install Environment Recommendation: Explicitly recommend running terraform commands and your generated automated validation script inside Google Cloud Shell (https://shell.cloud.google.com), where python3, gcloud, and terraform are 100% pre-installed and authenticated out of the box so developers without local SDKs can deploy and validate immediately.

    • Step-by-Step gcloud CLI Deployment Commands (Bottom-Up Wiring): In Section 6.3 ("Step-by-step gcloud CLI deployment commands") inside assets/output-template.md, provide a complete, self-contained sequence of gcloud CLI commands required to deploy this exact architecture without Terraform. These commands must enforce reverse/bottom-up order (VPC/subnets -> data tiers -> internal microservices -> public gateway -> load balancer), specify --database-version=POSTGRES_18 when provisioning Cloud SQL, and extract downstream container URLs (gcloud run services describe... --format='value(status.url)') into shell variables to dynamically pass them via --update-env-vars into upstream services.

    • Explanation of all Terraform variables, explicitly including and documenting the enable_vpc_sc and use_self_signed_cert variables (explaining how setting use_self_signed_cert = true enables immediate sandbox verification via curl -k https://<LB_IP>/ without waiting for DNS propagation).

    • Dedicated VPC Service Controls Guidance Section: Provide specific instructions and gcloud commands for implementing an Org-level VPC-SC service perimeter around Cloud Run (run.googleapis.com), Cloud SQL (sqladmin.googleapis.com), and Secret Manager (secretmanager.googleapis.com) when enable_vpc_sc = true.

    • Container image deployment strategies (specifying pre-existing image URLs or placeholder bootstrapping followed by CI/CD).

    • Cloud DNS Managed Private Zone (google_dns_managed_zone) configuration for run.app. bound to vpc_network, mapping *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30), alongside external DNS records and database schema initialization.

  5. Request review: Present the implementation plan to the user for approval. Iterate as needed.


Phase 4: Solution validation
  1. Define solution verification steps & requirements: During validation planning, mandate these 5 verification steps across any deployed environment:

    • SSL Provisioning: Verify that the Google-managed SSL certificate (google_compute_managed_ssl_certificate) becomes ACTIVE (checking --global status or regional equivalents).

    • Frontend Ingress Block: Verify that direct internet access targeting the Tier 1 Frontend's default *.run.app URL is blocked (HTTP 403 Forbidden from edge screening).

    • Backend Ingress Block: Verify that direct internet access targeting internal compute tiers' *.run.app URLs (INGRESS_TRAFFIC_INTERNAL_ONLY) is blocked across all internal microservice tiers (HTTP 404 Not Found or HTTP 403 Forbidden).

    • Frontend Public Access via Application Load Balancer: Verify that accessing the custom domain routes successfully to the presentation tier via the Application Load Balancer (HTTP 200 to 399).

    • Edge WAF Protection: Verify that a simulated SQL injection request (/?id=1%20OR%201=1 on the custom domain) is intercepted and blocked (HTTP 403 Forbidden from Cloud Armor).

    • Private Server-to-Server Connectivity: Verify via Cloud Run application logs (Logs Explorer) and database connection pooling telemetry (Cloud SQL Query Insights) that tier 1 -> tier 2 -> data tier queries succeed over private VPC fiber (Direct VPC Egress + Private Service Connect / Private Services Access).

  2. Generate tailored automated validation script: Rather than relying on a static pre-packaged script, generate a custom automated validation script (e.g., self-contained Python validation script using standard built-in urllib / subprocess libraries, or a cross-platform bash/PowerShell script) customized precisely to the user's deployed domain, SSL certificate name, and exact multi-tier *.run.app URIs.

  3. Provide cross-platform execution guidance: Explain how the user can execute the generated script across their target OS (macOS, Linux, Windows PowerShell, or zero-install Google Cloud Shell (https://shell.cloud.google.com)).

  4. Compile validation report: Document the validation checks, the generated verification script code, execution commands, and expected outcomes in Section 6.4 ("Solution verification guide and custom automated validation script") inside assets/output-template.md.

  5. Conduct validation and finalize: Assist the user in running the generated verification script, inspecting logs, and troubleshooting any DNS or WAF propagation issues. Request final approval.

Files

assets/main.tf

# Terraform template: strict secure serverless n-tier web application
#

terraform {
  required_version = ">= 1.3.0"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = ">= 4.50.0"
    }
    google-beta = {
      source  = "hashicorp/google-beta"
      version = ">= 4.50.0"
    }
    tls = {
      source  = "hashicorp/tls"
      version = ">= 4.0.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

provider "google-beta" {
  project = var.project_id
  region  = var.region
}

# ==========================================
# Variables
# ==========================================

variable "project_id" {
  type        = string
  description = "The Google Cloud project ID to deploy resources into."
}

variable "region" {
  type        = string
  description = "The Google Cloud region for regional resources (Cloud Run, Subnet, Cloud SQL, Redis)."
  default     = "us-central1"
}

variable "domain_name" {
  type        = string
  description = "The custom domain name for the application (e.g., app.example.com)."
  default     = "app.example.com"
}

variable "use_self_signed_cert" {
  type        = bool
  description = "Set to true to generate a self-signed certificate for immediate sandbox/dev testing without requiring a registered public domain. Set to false to provision a production Google-managed SSL certificate (requires pointing your domain's DNS A record to the load balancer IP)."
  default     = false
}

variable "frontend_image" {
  type        = string
  description = "The container image URL for the frontend service (presentation tier), stored in Google Cloud Artifact Registry or another accessible registry. Defaults to a lightweight placeholder image during initial infrastructure bootstrapping."
  default     = "us-docker.pkg.dev/cloudrun/container/hello" # Placeholder
}

variable "backend_image" {
  type        = string
  description = "The container image URL for the backend application service (application tier), stored in Google Cloud Artifact Registry or another accessible registry. Defaults to a lightweight placeholder image during initial infrastructure bootstrapping."
  default     = "us-docker.pkg.dev/cloudrun/container/hello" # Placeholder
}

variable "enable_cdn" {
  type        = bool
  description = "Whether to enable Cloud CDN on the Frontend Load Balancer backend service."
  default     = true
}

variable "enable_redis" {
  type        = bool
  description = "Whether to deploy a Memorystore for Redis instance for caching in the private VPC."
  default     = true
}

variable "enable_monitoring" {
  type        = bool
  description = "Whether to enable advanced logging and monitoring (VPC Flow Logs, Firewall Rules Logging, Load Balancer Access Logs, and Cloud Monitoring Alerting Policies)."
  default     = true
}

variable "enable_vpc_sc" {
  type        = bool
  description = "Whether to configure/enforce VPC Service Controls (VPC-SC) API perimeter boundary protections (requires Organization-level IAM permissions)."
  default     = false
}

variable "enable_ha" {
  type        = bool
  description = "Whether to configure Regional High Availability (availability_type = REGIONAL) and Point-in-Time Recovery (point_in_time_recovery_enabled) for Cloud SQL."
  default     = false # Set true for production HA across zones
}

variable "db_edition" {
  type        = string
  description = "The Cloud SQL edition to provision (ENTERPRISE for general-purpose workloads, or ENTERPRISE_PLUS for mission-critical sub-second read data cache & <10s maintenance downtime)."
  default     = "ENTERPRISE"
}

# ==========================================
# 1. Networking (VPC & PSA)
# ==========================================

# VPC Network
resource "google_compute_network" "vpc_network" {
  name                    = "secure-3tier-vpc"
  auto_create_subnetworks = false
}

# Subnet for Cloud Run Direct VPC Egress (Shared by Frontend & Backend)
resource "google_compute_subnetwork" "cloud_run_subnet" {
  name                     = "cloud-run-subnet"
  ip_cidr_range            = "10.0.1.0/24"
  region                   = var.region
  network                  = google_compute_network.vpc_network.id
  private_ip_google_access = true # Required for Private Google Access when routing *.run.app requests via ALL_TRAFFIC egress

  # Optional VPC Flow Logs (toggled via enable_monitoring)
  dynamic "log_config" {
    for_each = var.enable_monitoring ? [1] : []
    content {
      aggregation_interval = "INTERVAL_1_MIN"
      flow_sampling        = 0.1 # Sample 10% of traffic (adjust for prod cost control)
      metadata             = "INCLUDE_ALL_METADATA"
    }
  }
}

# Allocate IP range for Google services (Private Services Access / PSA for Memorystore Redis & managed VPC peering)
resource "google_compute_global_address" "private_ip_alloc" {
  name          = "google-managed-services-range"
  purpose       = "VPC_PEERING"
  address_type  = "INTERNAL"
  prefix_length = 16
  network       = google_compute_network.vpc_network.id
}

# VPC Peering connection to Google services (PSA for Memorystore Redis)
resource "google_service_networking_connection" "private_vpc_connection" {
  network                 = google_compute_network.vpc_network.id
  service                 = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.private_ip_alloc.name]
}

# ==========================================
# 1.2 Cloud DNS Managed Private Zone for run.app (Private Google Access VIP Mapping)
# ==========================================
# BACKEND_URL (*.a.run.app) resolves via public Google DNS to public IPv4 VIPs (216.58.x.x) by default.
# When frontend uses ALL_TRAFFIC egress, packets to that public VIP hit the deny_all_egress firewall (which blocks 0.0.0.0/0)
# OR fail at the backend because its ingress requires VPC-internal traffic.
# This Cloud DNS Managed Private Zone maps *.run.app directly to Private Google Access VIPs (199.36.153.4/30 / 199.36.153.8/30),
# ensuring packets stay strictly internal and pass egress policies clean.

resource "google_dns_managed_zone" "run_app_zone" {
  name        = "run-app-zone"
  dns_name    = "run.app."
  description = "Private DNS zone for *.run.app internal routing via Private Google Access"
  visibility  = "private"

  private_visibility_config {
    networks {
      network_url = google_compute_network.vpc_network.id
    }
  }
}

resource "google_dns_record_set" "run_app_record" {
  name         = "*.run.app."
  managed_zone = google_dns_managed_zone.run_app_zone.name
  type         = "A"
  ttl          = 300
  rrdatas = [
    "199.36.153.8",
    "199.36.153.9",
    "199.36.153.10",
    "199.36.153.11"
  ] # Private Google Access VIP range 199.36.153.8/30 (or 199.36.153.4/30)
}

# ==========================================
# 1.5 Cloud NGFW Network Firewall Policy (Least-Privilege Network Isolation)
# ==========================================
# MANDATORY PATTERN: Always configure explicit Cloud NGFW global or regional network firewall policies
# (google_compute_network_firewall_policy and google_compute_network_firewall_policy_rule with enable_logging = var.enable_monitoring).
# Do NOT use legacy/standard VPC firewall rules (google_compute_firewall).

resource "google_compute_network_firewall_policy" "egress_policy" {
  name        = "cloud-run-egress-policy"
  description = "Zero-trust egress firewall policy for Cloud Run tiers"
}

resource "google_compute_network_firewall_policy_association" "egress_policy_association" {
  name              = "cloud-run-egress-policy-association"
  attachment_target = google_compute_network.vpc_network.id
  firewall_policy   = google_compute_network_firewall_policy.egress_policy.name
}

# Deny unauthorized outbound egress from Cloud Run subnet by default
resource "google_compute_network_firewall_policy_rule" "deny_all_egress" {
  firewall_policy = google_compute_network_firewall_policy.egress_policy.name
  priority        = 65534 # Low priority default deny
  action          = "deny"
  direction       = "EGRESS"
  rule_name       = "deny-cloud-run-default-egress"

  match {
    layer4_configs {
      ip_protocol = "all"
    }
    dest_ip_ranges = ["0.0.0.0/0"]
  }

  target_service_accounts = [
    google_service_account.frontend_sa.email,
    google_service_account.backend_sa.email
  ]

  enable_logging = var.enable_monitoring
}

# Allow Frontend SA to send egress only to Backend Application (VPC internal routing) and Google APIs
resource "google_compute_network_firewall_policy_rule" "allow_frontend_egress" {
  firewall_policy = google_compute_network_firewall_policy.egress_policy.name
  priority        = 1000
  action          = "allow"
  direction       = "EGRESS"
  rule_name       = "allow-frontend-to-backend-egress"

  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports       = ["443", "80"]
    }
    dest_ip_ranges = [
      google_compute_subnetwork.cloud_run_subnet.ip_cidr_range,
      "199.36.153.4/30", # Private Google Access VIP ranges for *.run.app internal routing via Cloud DNS Managed Private Zone
      "199.36.153.8/30"
    ]
  }

  target_service_accounts = [
    google_service_account.frontend_sa.email
  ]

  enable_logging = var.enable_monitoring
}

# Allow Backend SA to send egress to Cloud SQL PSC Endpoint (TCP 5432) AND Private Google Access VIPs (TCP 443 for sqladmin.googleapis.com sidecar IAM cert exchange)
resource "google_compute_network_firewall_policy_rule" "allow_backend_db_egress" {
  firewall_policy = google_compute_network_firewall_policy.egress_policy.name
  priority        = 1001
  action          = "allow"
  direction       = "EGRESS"
  rule_name       = "allow-backend-to-cloudsql-psc-egress"

  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports       = ["5432", "443"] # PostgreSQL (5432) and HTTPS (443 to PGA VIPs for Cloud SQL Auth Proxy sidecar IAM cert exchange)
    }
    dest_ip_ranges = [
      "${google_compute_address.db_psc_ip.address}/32",
      "199.36.153.4/30", # Private Google Access VIP ranges for sidecar sqladmin.googleapis.com IAM certificate refresh on startup
      "199.36.153.8/30"
    ]
  }

  target_service_accounts = [
    google_service_account.backend_sa.email
  ]

  enable_logging = var.enable_monitoring
}

# Allow Backend API SA to send egress to Redis cache when enabled
resource "google_compute_network_firewall_policy_rule" "allow_backend_redis_egress" {
  count           = var.enable_redis ? 1 : 0
  firewall_policy = google_compute_network_firewall_policy.egress_policy.name
  priority        = 1002
  action          = "allow"
  direction       = "EGRESS"
  rule_name       = "allow-backend-to-redis-egress"

  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports       = ["6379"] # Redis
    }
    dest_ip_ranges = [
      "${google_redis_instance.private_cache[0].host}/32"
    ]
  }

  target_service_accounts = [
    google_service_account.backend_sa.email
  ]

  enable_logging = var.enable_monitoring
}

# ==========================================
# 2. Data Tier (Private Cloud SQL & Redis)
# ==========================================

# Private Cloud SQL PostgreSQL Instance (Connected via PSC)
resource "google_sql_database_instance" "private_db" {
  name                = "private-postgres-db"
  database_version    = "POSTGRES_18"
  region              = var.region
  deletion_protection = true # Protected stateful resource per TF best practices

  settings {
    edition           = var.db_edition
    availability_type = var.enable_ha ? "REGIONAL" : "ZONAL"
    tier              = "db-f1-micro" # Choose appropriate tier for production (or compatible perf tier like db-perf-optimized-N-4 when condition is ENTERPRISE_PLUS)

    backup_configuration {
      enabled                        = true
      point_in_time_recovery_enabled = var.enable_ha
    }

    ip_configuration {
      ipv4_enabled = false # Disable Public IP

      psc_config {
        psc_enabled               = true
        allowed_consumer_projects = [var.project_id]
      }
    }

    database_flags {
      name  = "cloudsql.iam_authentication"
      value = "on"
    }

    dynamic "insights_config" {
      for_each = var.enable_monitoring ? [1] : []
      content {
        query_insights_enabled  = true
        query_string_length     = 1024
        record_application_tags = true
        # Note: record_client_address is omitted because it is not supported for Cloud SQL instances with PSC connectivity enabled.
      }
    }
  }
}

# PSC Endpoint IP Address for Cloud SQL in Cloud Run Subnet
resource "google_compute_address" "db_psc_ip" {
  name         = "cloudsql-psc-ip"
  subnetwork   = google_compute_subnetwork.cloud_run_subnet.id
  address_type = "INTERNAL"
  region       = var.region
}

# PSC Endpoint Forwarding Rule connecting to Cloud SQL Service Attachment
resource "google_compute_forwarding_rule" "db_psc_endpoint" {
  name                  = "cloudsql-psc-endpoint"
  region                = var.region
  network               = google_compute_network.vpc_network.id
  subnetwork            = google_compute_subnetwork.cloud_run_subnet.id
  ip_address            = google_compute_address.db_psc_ip.id
  target                = google_sql_database_instance.private_db.psc_service_attachment_link
  load_balancing_scheme = ""
}

resource "google_sql_database" "database" {
  name     = "app_db"
  instance = google_sql_database_instance.private_db.name
}

# IAM-authenticated Database User for Backend API Service Account
resource "google_sql_user" "iam_db_user" {
  name     = trimsuffix(google_service_account.backend_sa.email, ".gserviceaccount.com")
  instance = google_sql_database_instance.private_db.name
  type     = "CLOUD_IAM_SERVICE_ACCOUNT"
}

# Private Memorystore for Redis (caching tier)
resource "google_redis_instance" "private_cache" {
  count          = var.enable_redis ? 1 : 0
  name           = "private-redis-cache"
  tier           = "BASIC" # Use STANDARD for production HA
  memory_size_gb = 1
  region         = var.region

  authorized_network = google_compute_network.vpc_network.id
  connect_mode       = "PRIVATE_SERVICE_ACCESS"

  # Ensure the VPC peering is established first
  depends_on = [google_service_networking_connection.private_vpc_connection]
}

# ==========================================
# 3. Security (Cloud Armor WAF)
# ==========================================

resource "google_compute_security_policy" "security_policy" {
  name        = "cloud-armor-waf-policy"
  description = "WAF and Rate Limiting policy for Strict 3-Tier Web App"
  provider    = google-beta

  # Rule 1: Prevent SQL Injection (WAF) - protecting the Frontend entry point
  rule {
    action   = "deny(403)"
    priority = "1000"
    preview  = false

    match {
      expr {
        expression = "evaluatePreconfiguredExpr('sqli-v33-stable')"
      }
    }
    description = "Block SQL injection attacks"
  }

  # Rule 2: Rate Limiting (Prevent DDoS/Brute Force)
  rule {
    action   = "throttle"
    priority = "2000"
    preview  = false

    match {
      versioned_expr = "SRC_IPS_V1"
      config {
        src_ip_ranges = ["*"]
      }
    }

    rate_limit_options {
      conform_action = "allow"
      exceed_action  = "deny(429)"
      
      rate_limit_threshold {
        count        = 100
        interval_sec = 60
      }
    }
    description = "Rate limit traffic to 100 requests/min per IP"
  }

  # Rule 3: Default Allow
  rule {
    action   = "allow"
    priority = "2147483647"
    match {
      versioned_expr = "SRC_IPS_V1"
      config {
        src_ip_ranges = ["*"]
      }
    }
    description = "default rule"
  }
}

# ==========================================
# 4. Service Accounts & IAM
# ==========================================

# Service Account for frontend (presentation tier)
resource "google_service_account" "frontend_sa" {
  account_id   = "frontend-app-sa"
  display_name = "Service Account for Frontend Cloud Run"
}

# Service Account for backend application (application tier)
resource "google_service_account" "backend_sa" {
  account_id   = "backend-app-sa"
  display_name = "Service Account for Backend Application Cloud Run"
}

# Grant Cloud SQL Client role to Backend SA only
resource "google_project_iam_member" "backend_cloudsql_client" {
  project = var.project_id
  role    = "roles/cloudsql.client"
  member  = "serviceAccount:${google_service_account.backend_sa.email}"
}

# ==========================================
# 5. Compute Tier: Building Block Modules for N-Tier Architecture
# ==========================================
# This section defines modular compute building blocks across N tiers (N >= 2).
# Use this simple mapping to adapt or scale your tiers:
#
# - Tier 1 (Public Gateway): Base on Section 5.1 ("Tier 1 presentation tier: frontend reverse proxy") inside `assets/main.tf` (`google_cloud_run_v2_service.frontend`, `roles/run.invoker` for Application Load Balancer).
# - Tiers 2..N (Internal Services): Replicate and customize Section 5.2 ("Tier 2 application tier: private backend API") inside `assets/main.tf` (`google_cloud_run_v2_service.backend_api`),
#   its dedicated service account, and its `google_cloud_run_v2_service_iam_member` block granting `roles/run.invoker`
#   to the immediate upstream calling service account (`serviceAccount:<upstream_sa>`).
# ==========================================

# 5.1 Tier 1 presentation tier: frontend reverse proxy (public ingress via load balancer only)
# Exposed to the public Load Balancer. Connects to Backend API via VPC.
resource "google_cloud_run_v2_service" "frontend" {
  name     = "frontend-service"
  location = var.region
  ingress  = "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER" # Block direct public URL bypass

  template {
    service_account = google_service_account.frontend_sa.email

    containers {
      image = var.frontend_image
      
      env {
        name  = "BACKEND_URL"
        value = google_cloud_run_v2_service.backend_application.uri # Private internal URL
      }
    }

    # Direct VPC Egress for Frontend to reach the private Backend Application (*.run.app via Private Google Access & Cloud DNS Managed Private Zone)
    vpc_access {
      network_interfaces {
        network    = google_compute_network.vpc_network.name
        subnetwork = google_compute_subnetwork.cloud_run_subnet.name
      }
      egress = "ALL_TRAFFIC" # Must use ALL_TRAFFIC + private_ip_google_access + Cloud DNS Managed Private Zone mapping *.run.app to PGA VIPs so requests traverse VPC and satisfy INGRESS_TRAFFIC_INTERNAL_ONLY
    }
  }
}

# Allow unauthenticated invocations from the Load Balancer (or specific Application Load Balancer identities) on Tier 1 Frontend
resource "google_cloud_run_v2_service_iam_member" "frontend_invoker" {
  location = google_cloud_run_v2_service.frontend.location
  name     = google_cloud_run_v2_service.frontend.name
  role     = "roles/run.invoker"
  member   = "allUsers"
}

# 5.2 Tier 2 application tier: private backend application (100% private ingress - zero internet access)
# COMPLETELY PRIVATE. Reachable only from the VPC (Frontend).
resource "google_cloud_run_v2_service" "backend_application" {
  name     = "backend-application-service"
  location = var.region
  ingress  = "INGRESS_TRAFFIC_INTERNAL_ONLY" # 100% Private, no public URL

  template {
    service_account = google_service_account.backend_sa.email

    containers {
      image = var.backend_image

      env {
        name  = "DB_USER"
        value = google_sql_user.iam_db_user.name # Use IAM-authenticated DB user
      }
      env {
        name  = "DB_NAME"
        value = google_sql_database.database.name
      }
      # PRIMARY / DEFAULT RECOMMENDED CONNECTION PATH: Unix Socket via built-in Cloud SQL Auth Proxy sidecar.
      # DB_SOCKET_PATH (/cloudsql/project:region:instance) is strongly recommended over direct TCP
      # because the Auth Proxy sidecar automatically handles transparent IAM authentication, short-lived OAuth
      # access token refresh, and mutual TLS (mTLS) encryption out of the box without requiring password
      # rotation or custom token acquisition code in application database drivers.
      env {
        name  = "DB_SOCKET_PATH"
        value = "/cloudsql/${google_sql_database_instance.private_db.connection_name}"
      }

      # SECONDARY / ALTERNATIVE CONNECTION PATH: Direct TCP via Private Service Connect (PSC) Endpoint.
      # DB_PSC_ENDPOINT (cloudsql-psc-endpoint:5432) is provided as an alternative for direct TCP connections.
      # Note: Direct TCP PSC connections using IAM database authentication require application code / drivers
      # to manually fetch and refresh temporary OAuth access bearer tokens (`scopes = cloudsql.client`) every hour.
      env {
        name  = "DB_PSC_ENDPOINT"
        value = google_compute_address.db_psc_ip.address
      }

      # Conditionally inject Redis environment variables if enabled
      dynamic "env" {
        for_each = var.enable_redis ? [1] : []
        content {
          name  = "REDIS_HOST"
          value = google_redis_instance.private_cache[0].host
        }
      }
      dynamic "env" {
        for_each = var.enable_redis ? [1] : []
        content {
          name  = "REDIS_PORT"
          value = tostring(google_redis_instance.private_cache[0].port)
        }
      }

      # Mount the unix socket directory provided by the Cloud SQL Auth Proxy sidecar volume
      volume_mounts {
        name       = "cloudsql"
        mount_path = "/cloudsql"
      }
    }

    # Automatically run the Cloud SQL Auth Proxy sidecar
    volumes {
      name = "cloudsql"
      cloud_sql_instance {
        instances = [google_sql_database_instance.private_db.connection_name]
      }
    }

    # Direct VPC Egress to access Cloud SQL & Redis privately
    vpc_access {
      network_interfaces {
        network    = google_compute_network.vpc_network.name
        subnetwork = google_compute_subnetwork.cloud_run_subnet.name
      }
      egress = "PRIVATE_RANGES_ONLY" # If using ALL_TRAFFIC (or Private Google Access DNS routing for googleapis.com), allow_backend_db_egress explicitly permits TCP 443 to PGA VIPs so sidecar IAM cert exchange (sqladmin.googleapis.com) succeeds on startup.
    }
  }
}

# Allow Tier 1 Frontend Service Account (`frontend_sa`) to invoke Tier 2 Backend Application (`backend_application`)
resource "google_cloud_run_v2_service_iam_member" "backend_invoker" {
  location = google_cloud_run_v2_service.backend_application.location
  name     = google_cloud_run_v2_service.backend_application.name
  role     = "roles/run.invoker"
  member   = "serviceAccount:${google_service_account.frontend_sa.email}"
}

# ==========================================
# 6. Edge Ingress: Load Balancing & WAF (Exposing TIER 1 Frontend ONLY)
# ==========================================

# 6.1 Serverless NEG for Frontend
resource "google_compute_region_network_endpoint_group" "frontend_neg" {
  name                  = "frontend-neg"
  network_endpoint_type = "SERVERLESS"
  region                = var.region
  cloud_run {
    service = google_cloud_run_v2_service.frontend.name
  }
}

# 6.2 Static External IP for Load Balancer
resource "google_compute_global_address" "lb_ip" {
  name = "secure-3tier-lb-ip"
}

# 6.3 Load Balancer Backend Service (Routing strictly to TIER 1 Frontend NEG)
resource "google_compute_backend_service" "frontend_lb_backend" {
  name                  = "frontend-backend-service"
  provider              = google-beta
  protocol              = "HTTP"
  port_name             = "http"
  load_balancing_scheme = "EXTERNAL_MANAGED"
  security_policy       = google_compute_security_policy.security_policy.id # Attach Cloud Armor
  # Note: Cloud CDN (`enable_cdn`) works on global Application Load Balancers (`google_compute_backend_service`).
  # If swapping to a regional Application Load Balancer (`google_compute_region_backend_service`) for regional sovereignty:
  # 1. Cloud CDN is unsupported and `enable_cdn` MUST be omitted or commented out to guarantee data residency.
  # 2. You must provision an additional regional proxy-only subnet (`google_compute_subnetwork` with `purpose = "REGIONAL_MANAGED_PROXY"` and `role = "ACTIVE"`).
  # 3. The regional forwarding rule (`google_compute_forwarding_rule`) must explicitly specify `network = google_compute_network.vpc_network.id`.
  enable_cdn            = var.enable_cdn

  backend {
    group = google_compute_region_network_endpoint_group.frontend_neg.id
  }

  # Optional Load Balancer Access Logs (toggled via enable_monitoring)
  dynamic "log_config" {
    for_each = var.enable_monitoring ? [1] : []
    content {
      enable      = true
      sample_rate = 1.0 # Log 100% of requests (adjust for high-volume prod cost control)
    }
  }
}

# 6.4a Self-Signed SSL Certificate (For immediate sandbox/dev testing without a registered domain)
resource "tls_private_key" "dev_key" {
  count     = var.use_self_signed_cert ? 1 : 0
  algorithm = "RSA"
  rsa_bits  = 2048
}

resource "tls_self_signed_cert" "dev_cert" {
  count           = var.use_self_signed_cert ? 1 : 0
  private_key_pem = tls_private_key.dev_key[0].private_key_pem

  subject {
    common_name  = var.domain_name
    organization = "Sandbox Dev"
  }

  validity_period_hours = 8760

  allowed_uses = [
    "key_encipherment",
    "digital_signature",
    "server_auth",
  ]
}

resource "google_compute_ssl_certificate" "self_signed" {
  count       = var.use_self_signed_cert ? 1 : 0
  name_prefix = "self-signed-cert-"
  private_key = tls_private_key.dev_key[0].private_key_pem
  certificate = tls_self_signed_cert.dev_cert[0].cert_pem

  lifecycle {
    create_before_destroy = true
  }
}

# 6.4b Google-managed SSL Certificate (For production with registered domain)
resource "google_compute_managed_ssl_certificate" "default" {
  count = var.use_self_signed_cert ? 0 : 1
  name  = "secure-3tier-ssl-cert"
  managed {
    domains = [var.domain_name]
  }
}

# 6.5 URL Map (Routes all traffic /* to Frontend)
resource "google_compute_url_map" "default" {
  name            = "secure-3tier-url-map"
  default_service = google_compute_backend_service.frontend_lb_backend.id
}

# 6.6 Target HTTPS Proxy (Dynamically binds self-signed or Google-managed cert)
resource "google_compute_target_https_proxy" "default" {
  name             = "secure-3tier-https-proxy"
  url_map          = google_compute_url_map.default.id
  ssl_certificates = concat(
    google_compute_ssl_certificate.self_signed[*].id,
    google_compute_managed_ssl_certificate.default[*].id
  )
}

# 6.7 Global Forwarding Rule
# Note: If migrating to a regional Application Load Balancer (`google_compute_forwarding_rule`), set `load_balancing_scheme = "EXTERNAL_MANAGED"`
# and explicitly require `network = google_compute_network.vpc_network.id` so the load balancer binds to the proxy-only subnet.
resource "google_compute_global_forwarding_rule" "https" {
  name                  = "secure-3tier-forwarding-rule"
  ip_address            = google_compute_global_address.lb_ip.address
  ip_protocol           = "TCP"
  port_range            = "443"
  target                = google_compute_target_https_proxy.default.id
  load_balancing_scheme = "EXTERNAL_MANAGED"
}

# ==========================================
# 7. Observability (Optional Cloud Monitoring)
# ==========================================

# Proactive Alerting Policy for Frontend HTTP 5xx errors
resource "google_monitoring_alert_policy" "high_error_rate" {
  count        = var.enable_monitoring ? 1 : 0
  display_name = "frontend-high-error-rate-alert"
  combiner     = "OR"
  conditions {
    display_name = "HTTP 5xx Error Rate > 5%"
    condition_threshold {
      # Filter for Frontend Cloud Run request count metric where response code is 5xx
      filter          = "resource.type=\"cloud_run_revision\" AND resource.labels.service_name=\"${google_cloud_run_v2_service.frontend.name}\" AND metric.type=\"run.googleapis.com/request_count\" AND metric.labels.response_code_class=\"5xx\""
      duration        = "60s"
      comparison      = "COMPARISON_GT"
      threshold_value = 5 # Triggers if 5xx count exceeds 5 (scale as needed)
      trigger {
        count = 1
      }
      aggregations {
        alignment_period   = "60s"
        per_series_aligner = "ALIGN_RATE"
      }
    }
  }
}

# ==========================================
# Outputs
# ==========================================

output "load_balancer_ip" {
  value       = google_compute_global_address.lb_ip.address
  description = "Point your DNS A record for var.domain_name to this IP address."
}

output "frontend_cloud_run_url" {
  value       = google_cloud_run_v2_service.frontend.uri
  description = "The internal/direct URL of the Frontend Cloud Run service (access blocked except via LB)."
}

output "backend_cloud_run_url" {
  value       = google_cloud_run_v2_service.backend_application.uri
  description = "The internal private URL of the Backend Application Cloud Run service (completely unreachable from public internet)."
}

output "ssl_verification_instructions" {
  value = var.use_self_signed_cert ? (
    "Self-signed certificate deployed. Test immediately via: curl -k https://${google_compute_global_address.lb_ip.address}/"
  ) : (
    "Google-managed certificate deployed for ${var.domain_name}. Create a DNS A record pointing ${var.domain_name} -> ${google_compute_global_address.lb_ip.address}, then monitor status: gcloud compute ssl-certificates describe secure-3tier-ssl-cert --global"
  )
  description = "Immediate verification instructions for the configured SSL mode."
}

output "vpc_sc_enabled" {
  value       = var.enable_vpc_sc
  description = "Indicates whether VPC Service Controls guidance and perimeter enforcement are requested for this project."
}

# ==========================================
# 7. VPC Service Controls (VPC-SC) Perimeter Guidance
# ==========================================
# When var.enable_vpc_sc is set to true, administrators MUST wrap the deployment project
# in an Organization-level VPC Service Controls (VPC-SC) service perimeter to enforce zero-trust
# API boundaries and mitigate data exfiltration risks.
#
# Protected APIs required in the VPC-SC perimeter:
# - Cloud Run Admin API (run.googleapis.com)
# - Cloud SQL Admin API (sqladmin.googleapis.com)
# - Secret Manager API (secretmanager.googleapis.com)
# - Service Networking API (servicenetworking.googleapis.com)
#
# Example Google Cloud CLI command to add the project and restricted services to a perimeter:
# gcloud access-context-manager perimeters update [PERIMETER_NAME] \
#   --add-resources="projects/${var.project_id}" \
#   --restricted-services="run.googleapis.com,sqladmin.googleapis.com,secretmanager.googleapis.com"

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs network access, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/google-cloud-solution-n-tier-serverless-web-app · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download google-cloud-solution-n-tier-serverless-web-app.zip