Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-solution-n-tier-serverless-web-app@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cloud-solution-n-tier-serverless-web-app v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cloud-solution-n-tier-serverless-web-app Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cloud-solution-n-tier-serverless-web-app/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-solution-n-tier-serverless-web-app for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 21.6 KB
---
name: google-cloud-solution-n-tier-serverless-web-app
metadata:
version: "1.0.1"
category: MultiProductSolutions
description: >-
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.
---
<!-- 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](references/attribution.md).
## 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 Path | Purpose & Usage |
| :--- | :--- |
| `assets/main.tf` | **Single 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.md` | Standardized Solution Architecture report markdown structure. |
| `references/non-negotiable-architectural-rules.md` | Non-negotiable security rules, audit checklist, and product mappings. |
| `references/related-guidance.md` | Supplemental 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](https://developers.google.com/knowledge/mcp) (`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.
main.tf 30.2 KB
# 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"
output-template.md 15.8 KB
<!-- Use this template to compile the solution architecture and code generated
based on the instructions in SKILL.md. -->
<!-- disableFinding(all) -->
<!-- mdlint off -->
# Google Cloud solution architecture: [Workload Name]
Note: Standalone text or instructions enclosed between [ and ] (e.g., [Workload Name] or [Paste code here]) represent placeholder instructions or sample text that are replaced by the agent when populating this template.
## 1. Executive summary and workload overview
[A brief description of the workload, its business goals, and the high-level
N-Tier (multi-tier) serverless solution architecture proposed across your
compute and data tiers.]
## 2. Requirements and current state
### 2.1. Functional requirements
* **Business processes**: [Details of the business processes supported]
* **Activities and use cases**: [Details of the key activities and use cases]
### 2.2. Non-functional requirements
* **Security & Zero-Trust**: [Details of security requirements including
single-domain reverse proxy, WAF mitigation, VPC-internal ingress
isolation (`INGRESS_TRAFFIC_INTERNAL_ONLY`), and optional VPC Service
Controls]
* **Reliability & Availability**: [Details of reliability constraints, SLA
targets, auto-scaling concurrency, and multi-zone regional high
availability]
* **Cost**: [Details of cost constraints, serverless $0 idle cost preferences
(`ALL_TRAFFIC` + PGA), and pricing models]
* **Operations & Observability**: [Details of monitoring, structured logging,
database Query Insights, and continuous deployment requirements]
* **Performance**: [Details of latency, connection pooling, Cloud CDN caching,
and Memorystore Redis caching requirements]
* **Sustainability**: [Details of serverless resource optimization and carbon
footprint reduction strategies]
### 2.3. Current state
[If applicable, describe the current on-premises, legacy v1 Cloud Run, or
other-cloud architecture.]
* **Current infrastructure**: [Details of existing setup]
* **Pain points and drivers for migration/redesign**: [Details of drivers for
migration/redesign]
### 2.4. Dependencies
* **Internal dependencies**: [Details of internal dependencies including
existing VPCs, domain names, and downstream APIs]
* **External dependencies**: [Details of third-party SaaS products and
on-premises tools]
## 3. Technical decomposition of the workload
[Decompose the workload into distinct logical tiers across the request
lifecycle, ensuring strict security boundary segregation:]
* **Tier 1 presentation tier (frontend / reverse proxy)**: Public-facing UI
rendering and gateway proxy service
(`google_cloud_run_v2_service.frontend`). Ingress restricted strictly to
Application Load Balancer (`INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER`).
* **Tier 2..N application tier (internal microservices / business logic)**:
1 to N internal business logic services
(`google_cloud_run_v2_service.backend_application`, `orders_service`, etc.). Ingress
restricted strictly to VPC-internal (`INGRESS_TRAFFIC_INTERNAL_ONLY`).
* **Data tier (persistent database and in-memory cache)**: Private relational
database (`Cloud SQL PostgreSQL 18 Enterprise Edition` with `database_version = "POSTGRES_18"`, Regional HA `availability_type = "REGIONAL"`, and `Private Service Connect` configuration `psc_enabled = true, ipv4_enabled = false`) and cache
(`Memorystore Redis` via `Private Services Access`).
* **Shared security and lifecycle tiers**: Container image management
(`Artifact Registry`), secret credentials (`Secret Manager`), private internal DNS resolution (`Cloud DNS Managed Private Zone` for `run.app.`), and zero-trust
Cloud NGFW network firewall policies (`google_compute_network_firewall_policy`, `google_compute_network_firewall_policy_association`, and `google_compute_network_firewall_policy_rule`).
## 4. Proposed solution architecture
### 4.1. Google Cloud products and features mapping
[Map your confirmed decomposition directly to Google Cloud products based on the
mandatory product mapping specifications in `SKILL.md`. Justify every selection and note
trade-offs:]
[Populate the following table with the appropriate content at runtime.]
| Component | Recommended Google Cloud product/feature | Justification and citations | Alternatives considered | Pros and cons of alternatives |
| :--- | :--- | :--- | :--- | :--- |
### 4.2. Architecture diagram
[Mermaid architecture flowchart illustrating the request and data flow across public and private tiers:]
[The following diagram is a sample and must be updated to reflect actual recommendation if necessary.]
```mermaid
flowchart TD
User["User (Browser)"] --> LB["Application Load Balancer (Cloud Armor WAF)"]
LB --> Frontend["Presentation tier (Cloud Run - Load Balancer Ingress)"]
Frontend --> Backend["Application tier (Cloud Run - VPC-Internal Ingress)"]
Backend --> Data["Data tier (Cloud SQL & Memorystore Redis via PSC/PSA)"]
```
### 4.3. Architecture description
* **Data flow**: [Describe the secure request and data payload lifecycle from
edge entry point `https://domain.com` through tier 1 reverse proxying,
internal microservice processing, and persistent database/cache storage.]
* **Tasks/control flow**: [Describe container startup authentication,
least-privilege IAM service account execution (`roles/run.invoker`,
`roles/cloudsql.client`), and Cloud SQL sidecar socket connections.]
## 5. Design and configuration recommendations
[Populate the following subsections with clear, parameter-dense recommendations adhering to Google Cloud Architecture Framework pillars. The included text is a sample and must be updated to reflect actual recommendation if necessary.]
### 5.1. Security, privacy, and compliance
* **Edge WAF & Ingress Filtering**: Attach Cloud Armor security policy (`google_compute_security_policy` with `sqli-v33-stable` preconfigured rule) to Application Load Balancer backend service. Tier 1 Frontend ingress is restricted to `INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER` to prevent direct `*.run.app` URL bypass.
* **VPC-Internal Compute Ingress & Cloud DNS**: Intermediate/backend microservices (T2..TN) are restricted strictly to `INGRESS_TRAFFIC_INTERNAL_ONLY`. Deploy a Cloud DNS Managed Private Zone (`google_dns_managed_zone`) for `run.app.` bound to `vpc_network` with `google_dns_record_set` mapping `*.run.app` to Private Google Access VIPs (`199.36.153.4/30 / 199.36.153.8/30`) so `egress = "ALL_TRAFFIC"` requests resolve internally without hitting default-deny firewalls or public IP routing.
* **Cloud NGFW Egress Firewalls & Sidecar Cert Exchange (`443`)**: Enforce zero-trust Cloud NGFW network firewall policies (`google_compute_network_firewall_policy_rule`) with default-deny outbound (`0.0.0.0/0`, priority 65534). Allow frontend egress to backend / PGA VIPs (`80, 443`), and backend egress (`allow_backend_db_egress`) to Cloud SQL PSC IP (TCP 5432) and PGA VIPs (TCP 443 on `199.36.153.4/30, 199.36.153.8/30`) so the Cloud SQL Auth Proxy sidecar can query `sqladmin.googleapis.com` on startup for IAM certificate exchange.
* **Cloud SQL Auth Proxy & IAM Database Auth (`DB_SOCKET_PATH`)**: Mount Cloud SQL Auth Proxy sidecar via `cloud_sql_instance` volume (`/cloudsql/project:region:instance` Unix socket). Configure IAM DB authentication (`cloudsql.iam_authentication = on`, `roles/cloudsql.client` via `google_sql_user`). Recommend `DB_SOCKET_PATH` (`/cloudsql/...` Unix socket) as the primary/default path over direct TCP (`DB_PSC_ENDPOINT`).
* **VPC Service Controls Perimeter**: Document/support wrapping `run.googleapis.com`, `sqladmin.googleapis.com`, and `secretmanager.googleapis.com` in an Org-level VPC-SC perimeter when `enable_vpc_sc = true`.
* **Regional Sovereignty (if applicable)**: For EU/regional data residency compliance, deploy Regional External ALB (`google_compute_region_backend_service`), omit Cloud CDN, provision a regional proxy-only subnet (`purpose = "REGIONAL_MANAGED_PROXY"`), and specify `network` on the regional forwarding rule (`google_compute_forwarding_rule`).
### 5.2. Reliability
* **Cloud SQL PostgreSQL Regional HA & PSC**: Provision Cloud SQL for PostgreSQL (`POSTGRES_18`) Enterprise Edition with Regional High Availability (`availability_type = "REGIONAL"`, point-in-time recovery enabled), and connect via Private Service Connect (`psc_enabled = true, ipv4_enabled = false`, `google_compute_forwarding_rule`).
* **Redundant Serverless Deployment**: Cloud Run v2 automatically distributes instances across physical zones in `var.region`. Configure `scaling.min_instance_count` and `max_instance_count` to eliminate cold-start latency and protect downstream tiers.
### 5.3. Operational excellence
* **Structured Logging & Error Reporting**: Emit structured JSON logs (`severity`, `message`, `trace`) for automated ingestion in Logs Explorer and unhandled exception grouping in Cloud Error Reporting.
* **VPC Flow Logs & Firewall Policy Logging**: Enable VPC Flow Logs (`flow_sampling = 0.1`, `aggregation_interval = "INTERVAL_1_MIN"`) on Cloud Run subnet and firewall logging (`enable_logging = var.enable_monitoring`) for network access auditing.
* **Database Insights & Synthetic Probes**: Enable Cloud SQL Query Insights (`query_insights_enabled = true`) for query execution and contention auditing. Configure Cloud Monitoring Uptime Checks (`/healthz`) and threshold alerts for Frontend HTTP 5xx error rates.
* **Infrastructure as Code (IaC)**: Manage all infrastructure using modular Terraform (`assets/main.tf`) with stateful deletion protection (`deletion_protection = true`).
### 5.4. Cost optimization
* **Serverless Idle Efficiency ($0 Baseline)**: Internal routing via Direct VPC Egress (`ALL_TRAFFIC`) + Private Google Access + Cloud DNS private zone operates at $0 idle cost without intermediate internal load balancers.
* **Edge Caching**: Enable Cloud CDN (`enable_cdn = true`) on Global ALB to cache static assets and reduce Cloud Run container activations and egress fees.
### 5.5. Performance efficiency
* **In-Memory Caching**: Deploy Memorystore for Redis via Private Services Access (`connect_mode = "PRIVATE_SERVICE_ACCESS"`) to cache session state and frequent database read queries.
* **Connection Pooling**: Implement database connection pooling inside application containers to prevent PostgreSQL connection saturation during traffic spikes.
### 5.6. Sustainability
* **Scale-to-Zero Compute**: Fully serverless Cloud Run architecture scales compute instances to zero during idle periods, optimizing datacenter utilization and carbon efficiency.
## 6. Deployment guidance
[The following steps are samples only. Provide complete, actionable deployment instructions, your generated modular
Terraform code, and your generated cross-platform verification scripts below.]
### 6.1. Step-by-step deployment instructions
* **Zero-Install Environment Recommendation**: For immediate deployment
without local SDK installations, run all steps below inside **Google Cloud
Shell** (`https://shell.cloud.google.com`), where `terraform`, `python3`,
`gcloud`, and `git` are 100% pre-installed and authenticated out of the box.
1. **Select Google Cloud Project and Enable APIs**:
```bash
gcloud config set project [YOUR_PROJECT_ID]
gcloud services enable run.googleapis.com sqladmin.googleapis.com redis.googleapis.com \
servicenetworking.googleapis.com secretmanager.googleapis.com monitoring.googleapis.com \
dns.googleapis.com
```
2. **Initialize and Apply Modular Terraform Configuration**:
```bash
terraform init
# For production with a custom domain:
terraform apply -var="domain_name=app.mycompany.com"
# For sandbox/dev testing over IP with a self-signed certificate:
terraform apply -var="use_self_signed_cert=true"
```
3. **DNS Cutover & SSL Validation**: If using a Google-managed certificate (`use_self_signed_cert = false`), create a DNS `A` record at your registrar pointing `var.domain_name` to the outputted `load_balancer_ip`. If using self-signed mode (`use_self_signed_cert = true`), you can test immediately over HTTPS via `curl -k https://[LOAD_BALANCER_IP]/`.
4. **Optional VPC Service Controls (`enable_vpc_sc`) Configuration**: If
deploying with `enable_vpc_sc = true`, ensure your active identity is an
Organization Access Context Manager Admin and update your service perimeter
to include the newly deployed project and required APIs before starting
containers.
### 6.2. Modular infrastructure as code (`main.tf`)
[Embed your complete, deploy-ready Terraform (`main.tf`) code generated from
`assets/main.tf` below, containing Section 5.1 ("Tier 1 presentation tier: frontend reverse proxy") and
replicated Section 5.2 ("Tier 2 application tier: private backend API") building blocks inside `assets/main.tf`
tailored to the user's workload, ensuring `database_version = "POSTGRES_18"` is strictly preserved:]
```hcl
# [Paste complete deploy-ready generated main.tf HCL code here]
```
### 6.3. Step-by-step `gcloud` CLI deployment commands
[Replace the following sample code with the complete sequence of `gcloud` CLI commands required to deploy this exact three-tier architecture manually from the terminal. Ensure the sequence executes in strict **bottom-up deployment order** (`internal data tier -> internal microservices -> public presentation gateway -> external Application Load Balancer`), enforces `--database-version=POSTGRES_18` for Cloud SQL, and captures dynamic downstream URLs into shell variables to automatically pass them inside `--update-env-vars`:]
```bash
# 1. Create VPC network and private subnet with Private Google Access enabled
[gcloud command to create a VPC network]
[gcloud command to create a subnet]
# 2. Provision data tier (Private Cloud SQL instance with Public IP disabled & Private Redis)
[gcloud command to create a Cloud SQL instance with --database-version=POSTGRES_18 --no-assign-ip --enable-private-service-connect ...]
[gcloud command to create a Redis instance]
# 3. Deploy internal application tier service (strictly VPC-internal ingress & Direct VPC Egress)
[gcloud command to create an application tier service]
# 4. Extract generated internal application tier URL into shell variable for service wiring
[shell command to extract an application tier URL]
# 5. Deploy presentation tier frontend service with load balancer-only ingress, injecting BACKEND_URL right into environment variables
[gcloud command to deploy the presentation tier service]
# 6. Create Serverless NEG and attach to external Application Load Balancer with Cloud Armor WAF
[gcloud command to create a serverless NEG]
# [Paste remaining gcloud compute backend-services / url-maps / target-https-proxies commands here]
```
### 6.4. Solution verification guide and custom automated validation script
[Embed your custom automated validation script (e.g., self-contained
cross-platform Python script using standard `urllib` / `subprocess` or
cross-platform shell script) generated per Phase 4 validation steps across SSL
provisioning, Tier 1 ingress blocking, Tier 2..N internal VPC ingress blocking,
Application Load Balancer reachability, and Cloud Armor WAF SQLi interception:]
```python
# [Paste custom generated verification script code here]
```
* **Execution Commands**:
```bash
python3 validate.py <custom_domain> <ssl_cert_name> <frontend_run_url> [internal_run_url_1 ...]
```
## 7. References
* [Google Cloud Architecture Framework](https://docs.cloud.google.com/architecture/framework.md.txt)
* [Cloud Run Direct VPC Egress](https://docs.cloud.google.com/run/docs/configuring/vpc-direct-vpc.md.txt)
* [Private Service Connect for Cloud SQL](https://docs.cloud.google.com/sql/docs/postgres/configure-private-service-connect.md.txt)
* [Google Cloud Terraform Best Practices](https://docs.cloud.google.com/docs/terraform/best-practices/general-style-structure.md.txt) attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-solution-n-tier-serverless-web-app)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:google-cloud-solution-n-tier-serverless-web-app)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-solution-n-tier-serverless-web-app)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
non-negotiable-architectural-rules.md 8.3 KB
<!-- disableFinding(all) -->
<!-- mdlint off -->
# Architectural Rules and Report Audit Checklist
To ensure secure, resilient, and cost-effective multi-tier cloud deployments, enforce the following 9 architectural guards across solution design reports (`assets/output-template.md`) and Infrastructure as Code (`assets/main.tf`). Understanding the engineering rationale behind each rule enables accurate architectural decisions across diverse workloads:
1. **Ingress Bypass Defense (`internal-and-cloud-load-balancing`)**:
* **Rule**: Configure Tier 1 Frontend ingress to `INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER`.
* **Why**: If a public Cloud Run service uses default unrestricted ingress (`all`), external clients can send HTTP requests directly to the default `*.run.app` URL, completely bypassing the external Application Load Balancer, SSL termination policies, and Cloud Armor WAF screening rules. Restricting ingress to `internal-and-cloud-load-balancing` ensures public traffic can only reach the container after passing through edge inspection.
2. **VPC-Internal Backend Ingress (`INGRESS_TRAFFIC_INTERNAL_ONLY`)**:
* **Rule**: Configure internal application microservice tiers (T2..TN, e.g., `backend_application`) strictly to `INGRESS_TRAFFIC_INTERNAL_ONLY`.
* **Why**: Internal business logic, data processing, and backend microservices should never be directly reachable from the public internet. Restricting ingress to `VPC-internal` ensures that these services reject any traffic originating outside the private network boundary, eliminating external attack surface.
3. **Direct VPC Egress (`vpc_access`) & Cloud DNS (`google_dns_managed_zone`)**:
* **Rule**: Attach `vpc_access` across compute tiers (`egress = "ALL_TRAFFIC"` when calling internal `*.run.app` URLs). When Tier 1 uses `ALL_TRAFFIC` egress, deploy a `google_dns_managed_zone` for `run.app.` bound to `vpc_network` with `google_dns_record_set` mapping `*.run.app` directly to Private Google Access VIPs (`199.36.153.4/30 / 199.36.153.8/30`).
* **Why**: By default, public Google DNS resolves `*.run.app` hostnames to public IPv4 virtual IP addresses (`216.58.x.x`). Under `ALL_TRAFFIC` egress, packets sent from containers targeting `216.58.x.x` traverse the VPC and hit default-deny (`0.0.0.0/0`) egress firewalls. Even when allowed outside the VPC, requests arriving from public VIPs are rejected by downstream `VPC-internal` (`INGRESS_TRAFFIC_INTERNAL_ONLY`) ingress guards with HTTP 403 or 404 errors. Implementing a private Cloud DNS zone maps these hostnames inside the VPC to internal Private Google Access endpoints (`199.36.153.x`), allowing traffic to cleanly traverse the private backbone and preserve internal VPC sender identity.
4. **Least-Privilege Cloud NGFW Egress Firewalls & Sidecar Cert Exchange (`443`)**:
* **Rule**: Enforce explicit Cloud NGFW global or regional network firewall policies (`google_compute_network_firewall_policy`, `google_compute_network_firewall_policy_association`, and `google_compute_network_firewall_policy_rule`) restricting outbound traffic precisely between tiers (`deny 0.0.0.0/0`, `Frontend -> Backend 443/8080`, and `Backend -> Data Tier 5432/6379`). For database egress (`allow_backend_db_egress`), permit TCP port `443` to Private Google Access VIPs (`199.36.153.4/30, 199.36.153.8/30`) in addition to TCP port `5432` (`Cloud SQL PSC IP`).
* **Why**: Least-privilege egress policies prevent compromised containers from scanning internal networks or exfiltrating data to arbitrary external destinations. Authorizing TCP port `443` to PGA VIPs alongside port `5432` is essential because when Cloud Run initializes `cloud_sql_instance` volumes (`IAM Auth`), the sidecar container queries `sqladmin.googleapis.com` (port `443`) and OAuth metadata endpoints across startup to exchange short-lived tokens for ephemeral client certificates; blocking this handshake under default-deny (`deny 0.0.0.0/0`) causes container initialization to crash.
5. **Firewall Policy Logging for Network Auditing**:
* **Rule**: Enable `enable_logging = var.enable_monitoring` on Cloud NGFW network firewall policy rules.
* **Why**: Capturing connection metadata (source/destination IP, port, protocol, and allow/deny decisions) produces verifiable audit trails for security operations, SIEM integration, and troubleshooting zero-trust network policies during incident response.
6. **Cloud CDN Edge Caching (`enable_cdn`)**:
* **Rule**: Enable `enable_cdn = true` on the global Application Load Balancer backend service (`google_compute_backend_service`). For European or regional data residency compliance using a regional Application Load Balancer (`google_compute_region_backend_service`), omit CDN, provision an explicit regional proxy-only subnet (`purpose = "REGIONAL_MANAGED_PROXY"`), specify `network` on the regional forwarding rule (`google_compute_forwarding_rule`), and explain the residency trade-off.
* **Why**: Caching static assets at Google's edge points-of-presence (`PoPs`) significantly reduces latency for end users, lowers serverless container invocation frequency, and replaces higher Cloud Run data egress costs with lower Cloud CDN edge delivery rates.
7. **Private Service Connect (`psc_enabled = true`) & Private Redis (`PSA`)**:
* **Rule**: Disable public IPs (`ipv4_enabled = false`) on Cloud SQL instances and connect via Private Service Connect (`psc_enabled = true`, `google_compute_forwarding_rule`). Connect Memorystore for Redis via Private Services Access (`connect_mode = "PRIVATE_SERVICE_ACCESS"` over `authorized_network`).
* **Why**: Exposing relational databases or in-memory caches on public IPv4 addresses introduces unnecessary vulnerability to brute-force and DDoS attacks. Private Service Connect provisions localized endpoints directly inside the consumer VPC without `/16` CIDR peering requirements or transitive routing risks, ensuring data storage remains 100% private.
8. **Cloud SQL Auth Proxy & IAM Database Auth (`DB_SOCKET_PATH`)**:
* **Rule**: Mount the built-in Cloud SQL Auth Proxy sidecar via `cloud_sql_instance` volumes (`/cloudsql/project:region:instance` Unix domain socket) and enable IAM-based database authentication (`cloudsql.iam_authentication = on`, `roles/cloudsql.client`). When configuring database connection strings in application drivers, advise using `DB_SOCKET_PATH` (`/cloudsql/...` Unix socket) over direct TCP (`DB_PSC_ENDPOINT`).
* **Why**: Hardcoded database passwords risk credential leakage, require operational maintenance for frequent password rotation, and lack granular identity auditing. The built-in Auth Proxy sidecar handles transparent short-lived OAuth token exchange (`cloudsql.iam_authentication`), automatic rotation, and mutual TLS encryption natively over Unix sockets without adding rotation logic or custom token handlers inside application code.
9. **Organization API Perimeter (`enable_vpc_sc`)**:
* **Rule**: Provide configuration variables (`enable_vpc_sc = true`) and documentation for wrapping `run.googleapis.com`, `sqladmin.googleapis.com`, and `secretmanager.googleapis.com` within an Organization-level VPC Service Controls (`VPC-SC`) service perimeter.
* **Why**: While network firewalls secure data-plane traffic (`TCP 5432`), they do not restrict API management planes (`sqladmin.googleapis.com`). A VPC-SC service perimeter prevents cross-project data exfiltration—such as an attacker exporting database backups (`sqladmin.instances.export`) to an unauthorized external Cloud Storage bucket—even if legitimate IAM administrative credentials are used.
### Modular IaC Alignment and Best Practices
* **Building Block Modules (`assets/main.tf`)**: Base Tier 1 parameters precisely on `Section 5.1` ("Tier 1 presentation tier: frontend reverse proxy") in `assets/main.tf` and Tiers 2..N on `Section 5.2` ("Tier 2 application tier: private backend application") in `assets/main.tf`, ensuring appropriate `roles/run.invoker` bindings are granted directly between calling service account identities.
* **Terraform Best Practices (`general-style-structure`)**: Adhere to Google Cloud HCL style guidelines including typed variables (`type`, `description`), unit-named numbers (`memory_size_gb`), positive boolean switches (`enable_cdn`), explicit outputs, and stateful deletion protection (`deletion_protection = true`).
related-guidance.md 27.9 KB
<!-- disableFinding(all) -->
<!-- mdlint off -->
# Architectural reference: secure serverless three-tier web application
This document provides deep technical guidance and architectural best practices for deploying a secure, highly available, n-tier (multi-tier) serverless web application on Google Cloud.
The architecture enforces strict physical and network isolation between the tiers:
1. **Presentation tier**: Public-facing UI rendering and reverse-proxy service (Cloud Run).
2. **Application tiers**: Private business logic service (Cloud Run), reachable only from the VPC.
3. **Data tier (database and cache)**: Private persistent storage (Cloud SQL) and in-memory caching (Memorystore Redis), reachable only from the application tier.
---
## Table of Contents
* **[1. Strict three-tier architecture overview](#1-strict-three-tier-architecture-overview)** *(Lines 49–82)*
* **[2. Ingress and routing: external vs. internal](#2-ingress-and-routing-external-vs-internal)** *(Lines 84–100)*
* [Presentation tier ingress](#presentation-tier-ingress) *(Lines 86–90)*
* [Application tier ingress](#application-tier-ingress) *(Lines 91–99)*
* **[3. Least-privilege network egress and Cloud NGFW firewall policies](#3-least-privilege-network-egress-and-cloud-ngfw-firewall-policies)** *(Lines 102–111)*
* **[4. Caching tier: Memorystore for Redis (optional)](#4-caching-tier-memorystore-for-redis-optional)** *(Lines 113–128)*
* [Redis deployment and security](#redis-deployment-and-security) *(Lines 119–127)*
* **[5. Secure database access: Private Service Connect and Cloud SQL Auth Proxy](#5-secure-database-access-private-service-connect-and-cloud-sql-auth-proxy)** *(Lines 130–138)*
* **[6. Security and operational best practices](#6-security-and-operational-best-practices)** *(Lines 140–157)*
* [Presentation tier as a reverse proxy](#presentation-tier-as-a-reverse-proxy) *(Lines 142–147)*
* [Secrets management](#secrets-management) *(Lines 148–150)*
* [Optional VPC Service Controls perimeter](#optional-vpc-service-controls-perimeter) *(Lines 151–156)*
* **[7. Content delivery network (Cloud CDN) (optional)](#7-content-delivery-network-cloud-cdn-optional)** *(Lines 159–169)*
* [How it works and trade-offs](#how-it-works-and-trade-offs) *(Lines 163–168)*
* **[8. Load balancer topology: global vs. regional](#8-load-balancer-topology-global-vs-regional)** *(Lines 171–210)*
* [Comparison and trade-offs](#comparison-and-trade-offs) *(Lines 175–185)*
* [Why choose a regional Application Load Balancer? (compliance and data residency)](#why-choose-a-regional-application-load-balancer-compliance-and-data-residency) *(Lines 186–190)*
* [Regional proxy-only subnet and network parameter requirements](#regional-proxy-only-subnet-and-network-parameter-requirements) *(Lines 191–195)*
* [Terraform resource mapping (global to regional)](#terraform-resource-mapping-global-to-regional) *(Lines 196–209)*
* **[9. Observability and monitoring (optional)](#9-observability-and-monitoring-optional)** *(Lines 212–252)*
* [9.1 VPC Flow Logs (Network Auditing)](#91-vpc-flow-logs-network-auditing) *(Lines 218–223)*
* [9.2 Firewall Policy Logging (Network Access Auditing)](#92-firewall-policy-logging-network-access-auditing) *(Lines 224–230)*
* [9.3 Load Balancer Access Logs (Application Ingress Auditing)](#93-load-balancer-access-logs-application-ingress-auditing) *(Lines 231–236)*
* [9.4 Cloud Monitoring Alerting Policies (Proactive Operations)](#94-cloud-monitoring-alerting-policies-proactive-operations) *(Lines 237–241)*
* [9.5 Advanced industry observability checklist (production best practices)](#95-advanced-industry-observability-checklist-production-best-practices) *(Lines 242–251)*
* **[10. Container image storage and deployment strategy (Artifact Registry)](#10-container-image-storage-and-deployment-strategy-artifact-registry)** *(Lines 254–283)*
* [Recommended storage: Artifact Registry](#recommended-storage-artifact-registry) *(Lines 258–263)*
* [Deployment strategy: pre-existing images vs. initial bootstrapping](#deployment-strategy-pre-existing-images-vs-initial-bootstrapping) *(Lines 264–279)*
* [Other service patterns](#other-service-patterns) *(Lines 280–283)*
---
## 1. Strict three-tier architecture overview
In this strict model, the **Application Tier** is completely private and has no public internet presence. The Presentation tier acts as the gatekeeper. The user's browser only communicates with the Presentation tier, which in turn communicates with the Application tier over the private VPC network.
```mermaid
flowchart TD
User["User Browser"] -->|HTTPS| APP_LB["Global external Application Load Balancer + Cloud Armor"]
subgraph GoogleCloud["Google Cloud Project"]
APP_LB --> FE_NEG["Serverless NEG - Presentation Tier"]
FE_NEG --> FE_Run["Cloud Run - Presentation Tier"]
subgraph VPC["VPC Network"]
subgraph PUB_SUB["Public/Private Subnet"]
FE_VPC_Interface["Frontend VPC interfaces - IPs in Subnet"]
end
subgraph PRIV_SUB["Private Subnet"]
BE_VPC_Interface["Backend VPC interfaces - IPs in Subnet"]
CloudSQL[(Cloud SQL PostgreSQL)]
Redis[(Memorystore Redis)]
end
end
FE_Run -->|Direct VPC Egress| FE_VPC_Interface
FE_VPC_Interface -->|Private API Call via VPC Routing| BE_Run["Cloud Run - Application Tier - Application Tier (Ingress - VPC-internal)"]
BE_Run -->|Direct VPC Egress| BE_VPC_Interface
BE_VPC_Interface -->|Private Service Connect| CloudSQL
BE_VPC_Interface -->|Private Services Access| Redis
end
```
---
## 2. Ingress and routing: external vs. internal
### Presentation tier ingress
* **External Entry Point**: Exposed via a **global external Application Load Balancer** or **regional external Application Load Balancer** with **Cloud Armor** WAF protection.
* **CDN Caching**: **Cloud CDN** is enabled on the Application Load Balancer backend service to cache static assets (HTML, JS, CSS, images) at the edge, reducing compute load on the Presentation Tier. Cloud CDN does not support the regional external Application Load Balancer and can't be used with that load balancer.
* **Ingress Bypass Protection**: Ingress is restricted to `internal-and-cloud-load-balancing` to ensure all public traffic must pass through Cloud Armor.
### Application tiers ingress
* **Greater than 3 tiers**: If there are more than 3 tiers in the deployment, then there can be more than one application tier.
* **Zero Public Exposure**: Ingress is set strictly to **VPC-internal** (`INGRESS_TRAFFIC_INTERNAL_ONLY`). The Application Tiers have no public URL and cannot be reached from the internet.
* **Private VPC Routing (`*.run.app`)**: Upstream services calling an internal `*.run.app` URL (e.g., Presentation Tier calling Application Tier) must configure the following:
* **Direct VPC Egress**: Set `egress = "ALL_TRAFFIC"` on the calling Cloud Run service.
* **Private Google Access**: Enable `private_ip_google_access = true` on the Cloud Run subnet.
* **Cloud NGFW Egress Rules**: Configure firewall policy rules (`google_compute_network_firewall_policy_rule`) allowing outbound traffic to Google API VIP ranges (`199.36.153.4/30`, `199.36.153.8/30`).
* **Cloud DNS Managed Private Zone**: Deploy a private zone (`google_dns_managed_zone`) for `run.app.` bound to `vpc_network` that maps `*.run.app` directly to Private Google Access VIPs (`199.36.153.4/30 / 199.36.153.8/30`).
---
## 3. Least-privilege network egress and Cloud NGFW firewall policies
Implement strict network-level isolation using **Direct VPC Egress** combined with zero-trust **Cloud NGFW Global or Regional Network Firewall Policies** (`google_compute_network_firewall_policy` and `google_compute_network_firewall_policy_rule`):
* **Default Egress Deny**: The Cloud Run subnets enforce a default-deny egress network firewall policy rule (`dest_ip_ranges = ["0.0.0.0/0"]`, priority `65534`), ensuring serverless runtimes cannot reach unauthorized internal destinations or leak data to external IPs.
* **Presentation Tier**: Enforces an explicit egress allow rule permitting the Presentation Tier service account to send traffic strictly to the Application Tier (permitting the Cloud Run subnet CIDR alongside Google API VIP ranges `199.36.153.4/30`, `199.36.153.8/30` for `ALL_TRAFFIC` Private Google Access `*.run.app` routing). It is **not** granted access to Data tier subnets or endpoints.
* **Application Tier**: Configured with `egress = "PRIVATE_RANGES_ONLY"`, enforcing an explicit egress allow rule permitting the Backend service account to reach exclusively the local VPC Cloud SQL Private Service Connect endpoint (TCP 5432) and Memorystore Redis instance (TCP 6379).
* **Firewall Policy Logging**: Each network firewall policy rule supports optional logging (`enable_logging = var.enable_monitoring`) to audit allowed and denied connections for security verification and compliance.
---
## 4. Caching tier: Memorystore for Redis (optional)
To reduce database load and improve API response times, the Application tier can **optionally** utilize **Memorystore for Redis** as a private caching tier.
While not a hard requirement for the application to function, it is highly recommended for production workloads.
### Redis deployment and security
* **Optional Optimization**: The architecture can be deployed without Redis. If omitted, the Application Tier simply queries Cloud SQL directly for all requests, reducing infrastructure costs.
* **VPC Bound**: If deployed, Memorystore is provisioned with a private IP address within the VPC network.
* **Authorized Network**: Access is restricted to the VPC. The Application Tier connects to the Redis instance's private IP and port (default `6379`) via its Direct VPC Egress.
* **Use Cases**:
* **Session State**: Storing user sessions so the Application Tier remains stateless.
* **Query Caching**: Caching expensive database query results.
---
## 5. Secure database access: Private Service Connect and Cloud SQL Auth Proxy
The Application tier connects to the private Cloud SQL instance via a local **Private Service Connect** endpoint in the consumer VPC, protected by the **Cloud SQL Auth Proxy** sidecar container in the Application Tier Cloud Run service.
* **Private Service Connect**: Unlike legacy Private Services Access peering, Private Service Connect provisions a single internal IP endpoint directly inside the customer VPC subnet. This eliminates IP CIDR exhaustion (`/16` requirements), avoids transitive peering restrictions across multi-VPC networks, and allows standard VPC egress firewall rules to restrict database connectivity.
* **IAM-based Authorization**: Authorizes connections using the Backend service account's IAM identity, eliminating static passwords.
* **Mutual TLS (mTLS)**: Encrypts all database traffic in transit automatically.
---
## 6. Security and operational best practices
### Presentation tier as a reverse proxy
By routing all API calls through the Presentation Tier server:
1. **Hidden API Structure**: The internal API endpoints, schemas, and routing are completely hidden from the public internet.
2. **Centralized Authentication**: The Presentation Tier can validate session cookies/tokens at the edge before forwarding requests to the Backend, protecting the Backend from unauthorized load.
3. **Simplified Domain/CORS**: The browser only ever talks to one domain (the Presentation Tier). No CORS configuration is required.
### Secrets management
All database credentials, Redis connection strings, and API keys are stored in **Secret Manager** and mounted securely as environment variables in the Application Tier service.
### Optional VPC Service Controls perimeter
While Private Service Connect and VPC Egress Firewalls secure the network data plane (traffic to TCP 5432), **VPC Service Controls** can be optionally enabled to protect the API management plane (`sqladmin.googleapis.com`, `secretmanager.googleapis.com`, `run.googleapis.com`).
* **Preventing API Data Exports**: Blocks API calls like `sqladmin.instances.export` aimed at copying database dumps to external Cloud Storage buckets outside the perimeter.
* **Preventing External Credential Abuse**: Rejects API calls originating from unauthorized networks or untrusted devices even if legitimate IAM credentials are used.
---
## 7. Content delivery network (Cloud CDN) (optional)
For public-facing web applications, enabling **Cloud CDN** on the external Application Load Balancer is a highly effective, optional performance and cost-optimization control.
### How it works and trade-offs
* **Edge Caching**: Cloud CDN caches static content (images, CSS, JS, media) at Google's global network edge.
* **Cost Savings**: Cloud Run charges for CPU allocation and network egress. By serving static assets from the CDN cache, you bypass Cloud Run container activations and replace expensive serverless egress with much cheaper CDN egress fees.
* **Toggling CDN**: The architecture supports turning CDN on or off via the `enable_cdn` boolean variable in Terraform. If disabled (e.g., if you have no static assets or use a third-party CDN like Cloudflare in front of the LB), the Load Balancer forwards all requests directly to the Presentation Tier container.
* **Requirements**: Cloud CDN **requires a global Application Load Balancer**; it is not supported on regional Application Load Balancers.
---
## 8. Load balancer topology: global vs. regional
By default, this architecture recommends a **global external Application Load Balancer**. However, depending on compliance, data residency, and performance requirements, you can choose to deploy a **regional external Application Load Balancer**.
### Comparison and trade-offs
| Feature / Metric | Global external Application Load Balancer (Default) | Regional external Application Load Balancer (Alternative) |
| :--- | :--- | :--- |
| **Routing & Edge** | Anycast IP. Traffic enters Google's network at the nearest edge PoP globally and travels over Google's backbone. | Unicast IP. Traffic enters Google's network at the specific region's ingress point. |
| **SSL Termination** | Terminated at the global edge PoP closest to the user. | Terminated **strictly** within the designated Google Cloud region. |
| **Cloud CDN** | **Supported**. Native edge caching is available to drastically reduce Presentation Tier load and egress costs. | **Not Supported**. Static assets must be served directly from the Presentation Tier container. |
| **Subnet & Network Requirements** | No proxy-only subnet needed (`Google Anycast edge proxies handle routing`). Global forwarding rules (`google_compute_global_forwarding_rule`) do not require `network`. | **Requires an additional regional proxy-only subnet** (`google_compute_subnetwork` with `purpose = "REGIONAL_MANAGED_PROXY"`, `role = "ACTIVE"`) for Envoy proxies, and regional forwarding rules (`google_compute_forwarding_rule`) **must explicitly specify `network`**. |
| **Latency** | Lowest globally (Anycast routing + edge termination). | Higher for users far from the destination region. |
| **Primary Use Cases** | Public-facing websites, global audiences, workloads requiring edge caching (CDN), and standard web apps. | Strict compliance, data residency (e.g., GDPR, sovereign cloud where SSL keys/decryption must not leave a region), or strictly regional architectures. |
### Why choose a regional Application Load Balancer? (compliance and data residency)
The primary driver for choosing a regional Application Load Balancer is **compliance and data sovereignty**:
* **SSL Decryption Boundary**: In a global Application Load Balancer, Google terminates SSL at its global edge locations. If your security policy or local regulations dictate that data must remain encrypted until it physically enters a specific geographic territory (e.g., Germany or the EU), a global Application Load Balancer cannot comply.
* **Regional Isolation**: A regional Application Load Balancer ensures that all traffic processing, WAF (Cloud Armor) evaluation, and SSL decryption occur exclusively within the boundaries of the selected region.
### Regional proxy-only subnet and network parameter requirements
When deploying a regional external Application Load Balancer (`EXTERNAL_MANAGED`), Google runs Envoy proxies internally within your target region and VPC network. Because of this architectural difference from global Anycast routing:
1. **Proxy-Only Subnet Required**: You must provision an additional explicit regional **proxy-only subnet** (`google_compute_subnetwork` with `purpose = "REGIONAL_MANAGED_PROXY"` and `role = "ACTIVE"`, e.g., `10.129.0.0/23`) inside the VPC network (`network = google_compute_network.vpc_network.id`) and region alongside your Cloud Run subnet. Managed Envoy proxies use IP addresses from this proxy-only subnet when establishing connections with target backends (such as Serverless NEGs).
2. **Network Parameter on Forwarding Rule Required**: When creating the regional forwarding rule (`google_compute_forwarding_rule` with `load_balancing_scheme = "EXTERNAL_MANAGED"`), you **must explicitly specify the `network` parameter** (`network = google_compute_network.vpc_network.id`) alongside `region`, `ip_address`, `port_range`, and `target` to bind the load balancer forwarding rule directly to your VPC network and its proxy-only subnet.
### Terraform resource mapping (global to regional)
If a customer requires a regional Application Load Balancer, the Terraform resources must be swapped as follows:
| Global Resource (in `main.tf`) | Regional Equivalent Resource | Key Differences |
| :--- | :--- | :--- |
| *(None - New Resource Required)* | `google_compute_subnetwork` *(Proxy-Only Subnet)* | **Must provision an additional regional proxy-only subnet** (`purpose = "REGIONAL_MANAGED_PROXY"`, `role = "ACTIVE"`, e.g., `ip_cidr_range = "10.129.0.0/23"`) in the target `region` and `network` of your VPC for the regional Envoy proxy pool. |
| `google_compute_global_address` | `google_compute_address` | Add `region` parameter to the regional address. |
| `google_compute_backend_service` | `google_compute_region_backend_service` | Add `region` parameter. Note: `enable_cdn` is not supported on regional. |
| `google_compute_managed_ssl_certificate` | `google_compute_region_ssl_certificate` *(or Certificate Manager)* | Regional certificates must be provisioned in the specific region. |
| `google_compute_url_map` | `google_compute_region_url_map` | Add `region` parameter. |
| `google_compute_target_https_proxy` | `google_compute_region_target_https_proxy` | Add `region` parameter. |
| `google_compute_global_forwarding_rule` | `google_compute_forwarding_rule` | Add `region` parameter, set `load_balancing_scheme = "EXTERNAL_MANAGED"`, and **must explicitly specify `network = google_compute_network.vpc_network.id`** when creating regional managed forwarding rules. |
---
## 9. Observability and monitoring (optional)
To ensure operational excellence and rapid incident response, this architecture supports an optional **observability tier** that can be toggled on or off via a single configuration variable (`enable_monitoring`).
This tier implements the following distinct, high-value observability controls:
### 9.1 VPC Flow Logs (Network Auditing)
VPC Flow Logs record a sample of network flows sent from and received by VM interfaces and serverless VPC egress interfaces.
* **Use Cases**: Network troubleshooting (e.g., verifying if tier-to-tier traffic is blocked), security forensics, and network load monitoring.
* **Default Configuration**: Configured by default (`enable_monitoring = true`) on the Cloud Run subnet (`cloud_run_subnet`) with a cost-optimized capture rate of **`10%` (`flow_sampling = 0.1`)** over a **`1-minute` aggregation interval (`aggregation_interval = "INTERVAL_1_MIN"`)**.
* **Cost Trade-off & Tuning**: Flow logs can generate massive volumes of data in high-traffic environments, leading to significant **Cloud Logging ingestion and storage costs**. You can increase `flow_sampling` up to `1.0` and shorten `aggregation_interval` if your security or diagnostics require more detailed packet flow data. Alternatively, if you do not need flow data or want zero observability ingestion costs during development, you can disable VPC Flow Logs along with other optional logging controls by setting `enable_monitoring = false`.
### 9.2 Firewall Policy Logging (Network Access Auditing)
Firewall Policy Logging records when a Cloud NGFW network firewall policy rule allows or denies traffic.
* **Captured Data**: Connection 5-tuple (source/destination IP, source/destination port, protocol), action taken (ALLOW or DENY), rule name, and instance/service account metadata.
* **Use Cases**: Verifying zero-trust egress policies (e.g., auditing any denied connection attempts from Cloud Run containers or verifying valid traffic to Cloud SQL and Redis), security compliance, and threat hunting.
* **Cost Trade-off**: Like VPC Flow Logs, high-volume firewall logging can increase Cloud Logging ingestion volumes.
* **Toggleable**: Controlled via the `enable_monitoring` variable by setting `enable_logging = var.enable_monitoring` on each network firewall policy rule.
### 9.3 Load Balancer Access Logs (Application Ingress Auditing)
Load Balancer access logs capture detailed metadata for every HTTP request entering your application through the global external Application Load Balancer.
* **Captured Data**: Client IP, request URL, HTTP status codes, latency, Cloud CDN cache hit/miss status, and **Cloud Armor WAF block decisions** (showing which WAF rule triggered a block).
* **Importance**: Critical for security monitoring (SIEM integration) and for verifying that Cloud Armor is correctly blocking malicious payloads.
* **Toggleable**: Can be enabled/disabled on the Load Balancer's backend service.
### 9.4 Cloud Monitoring Alerting Policies (Proactive Operations)
Rather than waiting for users to report outages, the architecture can provision automated **Alerting Policies** in Cloud Monitoring.
* **Default Alert**: Provisions a threshold alert on **Frontend HTTP 5xx Error Rates**. If the rate of server errors exceeds a set threshold (e.g., >5% of total requests over 1 minute), an alert is triggered.
* **Notification**: In a production landing zone, these alerts are linked to Notification Channels (such as email, Slack, or PagerDuty) to wake up on-call engineers.
### 9.5 Advanced industry observability checklist (production best practices)
To establish world-class observability across multi-tier serverless pipelines (`Cloud Run v2 + Cloud SQL PSC + Redis PSA + Application Load Balancer + Cloud Armor WAF`), incorporate the following six practices:
1. **Distributed Tracing (`Cloud Trace` & `OpenTelemetry`)**: Propagate `traceparent` (`X-Cloud-Trace-Context`) HTTP headers across container tiers (T1 -> T2 -> T3 -> DB) to render complete, end-to-end request latency waterfalls inside **Google Cloud Trace**, eliminating guesswork when pinpointing multi-service bottlenecks.
2. **Database Deep Observability (`Cloud SQL Query Insights`)**: Enable **Cloud SQL Query Insights** (`insights_config { query_insights_enabled = true }` in Cloud SQL settings). Query Insights automatically monitors database load metrics, detects N+1 query anomalies, captures slow execution plans (`SELECT * FROM...`), and attributes database contention directly to specific Cloud Run application workloads.
3. **Proactive Synthetic Probing (`Cloud Monitoring Uptime Checks`)**: Configure global **Uptime Checks (`google_monitoring_uptime_check_config`)** to continuously ping your public presentation endpoint (`/healthz` or `/`) from multiple geographical checkpoints every 60 seconds. This triggers immediate incident notifications during zero-traffic windows *before* real users experience failures.
4. **Structured JSON Logging & `Cloud Error Reporting`**: Emit all container logs as **Structured JSON (`{"severity": "ERROR", "message": "...", "trace": "..."}`)** rather than plain text. Cloud Logging native JSON ingestion automatically populates structured fields for instant filtering, while standard exception tracebacks (`Traceback...`) automatically group into **Cloud Error Reporting** for real-time crash tracking across container revisions.
5. **Serverless Concurrency & Cold-Start Saturation Metrics**: Continuously monitor container concurrency (`run.googleapis.com/container/concurrency`), instance counts (`container/instance_count`), and latency percentiles (`p95`, `p99`). High cold-start ratios directly indicate where **Minimum Instances (`scaling.min_instance_count`)** should be provisioned on sensitive intermediate tiers (`API Gateway` or `Auth Service`).
6. **Long-Term Audit & SIEM Archival (`Log Router Sinks`)**: Because standard Cloud Logging buckets retain logs for only 30 days by default, configure an organization or project **Log Router Sink (`google_logging_project_sink`)** to continuously export high-volume audit, load balancer access logs, and VPC egress firewall logs into **BigQuery** (for SQL threat hunting) or **Cloud Storage (`Archive Storage`)** for multi-year regulatory compliance (SOC2, GDPR, PCI-DSS).
---
## 10. Container image storage and deployment strategy (Artifact Registry)
A critical consideration for three-tier serverless applications is where container images are securely stored and how application revisions are deployed to Cloud Run across the development lifecycle.
### Recommended storage: Artifact Registry
* **Repository Type**: Store container images for both the Presentation Tier and Application Tier in Google Cloud **Artifact Registry** standard Docker repositories.
* **Regional Colocation**: Deploy the Artifact Registry repository in the same Google Cloud region (or corresponding multi-region) as the Cloud Run services to minimize latency, eliminate inter-region data egress fees during container pulls, and comply with data residency boundaries.
* **Vulnerability Scanning**: Enable automated vulnerability scanning (via Container Analysis) in Artifact Registry to scan base images and application packages for CVEs prior to deploying revisions to Cloud Run.
* **IAM Access Control**: Ensure that the Cloud Run service agent (`service-[PROJECT_NUMBER]@serverless-robot-prod.iam.gserviceaccount.com`) or the dedicated runtime service account has `roles/artifactregistry.reader` permissions on the repository if images are pulled across project boundaries.
### Deployment strategy: pre-existing images vs. initial bootstrapping
When provisioning core infrastructure via Terraform, choose one of two workflows based on project maturity:
1. **Pre-existing Production Images**:
* If container images have already been built and published to Artifact Registry (e.g., during migration or staging promotion), pass the full image URIs directly into Terraform:
```hcl
frontend_image = "us-central1-docker.pkg.dev/my-project/web-repo/frontend:v1.2.0"
backend_image = "us-central1-docker.pkg.dev/my-project/web-repo/backend-app:v1.2.0"
```
* Terraform deploys the Cloud Run services immediately executing your custom application code.
2. **Decoupled Bootstrapping with Placeholder Images**:
* In new environments, infrastructure provisioning (VPC, Cloud SQL, IAM, Load Balancer) often precedes the initial application build. In this scenario, allow Terraform variables to use lightweight public placeholder images (such as `us-docker.pkg.dev/cloudrun/container/hello`).
* Once Terraform completes initial infrastructure bootstrapping, automated CI/CD pipelines (such as Cloud Build, GitHub Actions, or GitLab CI) build application code, push containers to Artifact Registry, and issue `gcloud run deploy` commands to update container image revisions on Cloud Run.
* **Terraform State Lifecycle**: Because application pipelines update container image revisions out-of-band, configure Terraform's `lifecycle { ignore_changes = [template[0].containers[0].image] }` block if necessary to prevent subsequent Terraform runs from reverting deployed application images back to initial placeholder values.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE