EcoMarket already runs on AWS and on Azure with the same architecture. This lesson deploys it on Google Cloud, and it is the one that will unsettle the mental model you bring from the previous two the most. Not because GCP is harder, but because its design decisions are genuinely different on four points that affect how the code is written: the project is the fundamental unit and there is nothing quite like it in AWS; the virtual network is global and the subnets regional, the reverse of what you have seen twice; the firewall lives on the network and applies by tag, not by a group attached to the machine; and every API has to be enabled before it can be used, which produces the most baffling error of your first day.
As in the previous lessons, each section states the approximate cost and what falls within the free tier, and the lesson closes with a guided destroy and the list of what survives. Fictional identifiers: project ecomarket-dev-471203, domain ecomarket.example.com.
- The equivalence map and the project as the fundamental unit
| Concept | AWS | Azure | GCP | Same? |
|---|---|---|---|---|
| Billing and isolation boundary | Account | Subscription | Project | Conceptually yes, in practice far lighter |
| Higher hierarchy | Organisation + organisational units | Management groups | Organisation + folders | Yes |
| Grouping inside it | Tags only | Resource group | Tags only (the project plays that role) | Like AWS |
| Private network | VPC (regional) | VNet (regional) | VPC (global) | No |
| Subnet | Zonal | Regional | Regional | Like Azure |
| Firewall | Security group (on the instance) | NSG (on a subnet or NIC) | Firewall rule on the VPC, by tag | No |
| Virtual machine | EC2 | Virtual Machine | Compute Engine | Yes |
| Scaling | Auto scaling group | Scale set | Managed instance group | Yes |
| HTTP load balancer | Application Load Balancer | Application Gateway | Global HTTP(S) load balancer (5 resources) | Not in shape |
| PostgreSQL | RDS | Flexible Server | Cloud SQL | Yes |
| Objects | S3 bucket | Account + container | Cloud Storage bucket | Like AWS |
| Secrets | Secrets Manager | Key Vault | Secret Manager | Yes |
| Machine identity | Role + instance profile | Managed identity | Attached service account | Yes |
| Permissions | JSON policies | RBAC: role + scope | IAM: roles/<name> on a resource |
Like Azure |
| Enabling services | Nothing to do | Register resource providers | google_project_service mandatory |
No |
The project is the key piece. It is simultaneously the boundary for billing, permissions, quotas, networking and names. And it has a property that sets it apart from an AWS account: creating one is trivial and free, a matter of seconds and one API call. That changes the isolation strategy:
| Isolation strategy | AWS | Azure | GCP |
|---|---|---|---|
| The usual way to separate environments | One account per environment (high friction) | A subscription or a resource group | One project per environment (minimal friction) |
| Cost of creating the boundary | High: account management, SSO, billing | Medium | Almost nil |
| Consequence | Many teams share an account and use tags | Resource groups per environment | One project per environment and almost per team |
EcoMarket on GCP therefore has four projects: ecomarket-dev-471203, ecomarket-staging-471204, ecomarket-prod-471205 and ecomarket-shared-471206 for the DNS zone, the artefact registry and the state bucket. And local.prefix still exists, even though inside a project it would not be needed, for the same reason as in Azure: cross-cloud consistency and readability in dashboards.
- The
google and google-beta providers
google and google-beta providers# infra/app/versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
google = {
source = "hashicorp/google"
version = "~> 6.0"
}
google-beta = {
source = "hashicorp/google-beta"
version = "~> 6.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}# infra/app/providers.tf
provider "google" {
project = var.project_id # ecomarket-dev-471203
region = var.region # europe-west1
zone = var.zone # europe-west1-b
}
provider "google-beta" {
project = var.project_id
region = var.region
zone = var.zone
}Why there are two providers. Google maintains two parallel APIs: the stable one (v1) and the beta one (v1beta1). The google provider talks to the first and google-beta to the second. It is not an "experimental Terraform provider": it is access to features Google has not yet promoted to general availability.
google |
google-beta |
|
|---|---|---|
| Underlying API | v1 (GA) |
v1beta1 |
| Resource stability | Guaranteed | It can change or disappear |
| When to use it | Whenever you can | Only for features not yet in GA |
| Scope of the choice | Per resource, with provider = google-beta |
The same |
| Mix them? | Yes, that is normal | Yes |
The correct pattern is to use google by default and google-beta only on the resources that need it:
resource "google_compute_instance" "web" {
# Default google provider: nothing to declare.
}
resource "google_compute_region_instance_group_manager" "web" {
provider = google-beta # if a feature still in beta is used
# ...
}One important trap: if a resource is created with google-beta and you then switch it to google, Terraform may want to replace it, because in some cases they are different types as far as state is concerned. Choose and be consistent; each resource's documentation notes whether it requires beta.
project, region and zone on the provider are defaults that each resource can override. They are welcome because they save repeating them a hundred times, and at the same time they hide a risk: a resource with no explicit project is created wherever the provider says, so the pre-flight check matters just as much as in the other clouds.
- Authentication: ADC, service account and impersonation
The rule does not change: no secrets in a .tf, and in GCP there is an extra reason to insist. Service account keys are JSON files holding a private key that never expires; Google actively recommends not creating them.
| Method | How | When | Risk |
|---|---|---|---|
| Application Default Credentials (ADC) | gcloud auth application-default login |
Local development. Recommended for this course | Nothing relevant: a user session |
| Attached service account | Terraform runs on a VM or Cloud Build with its own account | Automation inside GCP | The machine inherits the permissions |
| Workload identity federation | An external pipeline exchanges an OIDC token | Production. Detailed in module 8 | Misconfiguring the trust condition |
| Service account impersonation | impersonate_service_account on top of ADC |
Teams: the person has no permissions, the account does | Whoever can impersonate has its permissions |
| Downloaded JSON key | GOOGLE_APPLICATION_CREDENTIALS=/path/key.json |
Avoid | An everlasting private key in a file |
Impersonation is the pattern EcoMarket adopts, and it deserves an explanation because it has no exact equivalent in AWS or Azure:
provider "google" {
project = var.project_id
region = var.region
# Whoever runs it (your user, via ADC) impersonates this service account.
# Your user does NOT need permissions on the infrastructure: only
# roles/iam.serviceAccountTokenCreator on this account.
impersonate_service_account = "terraform-${var.environment}@${var.project_id}.iam.gserviceaccount.com"
}Advantages over handing permissions directly to people:
- People do not accumulate permissions. They are given the ability to impersonate, not the permissions themselves, and it is revoked in one place.
- Audit logs are precise. Cloud Audit Logs records who impersonated the account, not just what the account did.
- There are no keys. Impersonation produces a short-lived token.
- It is reversible instantly: removing the
serviceAccountTokenCreatorrole cuts access without touching anything else.
Pre-flight check, the equivalent of aws sts get-caller-identity:
# 1. Authenticate (twice: for gcloud and for the libraries/ADC)
gcloud auth login
gcloud auth application-default login
# 2. Who am I and in which project?
gcloud config list --format="value(core.account, core.project)"
gcloud projects describe ecomarket-dev-471203 \
--format="table(projectId, name, projectNumber, lifecycleState)"
# 3. Can I impersonate the Terraform account?
gcloud auth print-access-token \
--impersonate-service-account=terraform-dev@ecomarket-dev-471203.iam.gserviceaccount.com \
>/dev/null && echo "Impersonation OK"
# 4. Quotas for the region
gcloud compute regions describe europe-west1 \
--format="table(quotas.metric, quotas.limit, quotas.usage)"That gcloud auth application-default login in step two is forgotten constantly: gcloud auth login authenticates the CLI, not the libraries. Terraform uses the latter. The symptom is a credentials error right after signing in successfully.
And the data source for the check:
data "google_client_config" "current" {}
data "google_project" "current" {}
check "correct_project" {
assert {
condition = data.google_project.current.project_id == var.expected_project
error_message = "Active project: ${data.google_project.current.project_id}. Expected ${var.expected_project}."
}
}
- Enabling APIs with
google_project_service and the classic error
google_project_service and the classic errorThis is the GCP quirk that wastes the most time on day one. In a new project, almost no API is enabled. It is not that permissions are missing: the service is, literally, not active.
╷ │ Error: Error creating Network: googleapi: Error 403: Compute Engine API has not │ been used in project ecomarket-dev-471203 before or it is disabled. Enable it by │ visiting https://console.developers.google.com/apis/api/compute.googleapis.com/overview?project=ecomarket-dev-471203 │ then retry. If you enabled this API recently, wait a few minutes for the action │ to propagate to our systems and retry. │ accessNotConfigured ╵
The message is one of the best any cloud gives: it says exactly what is happening and what to do. And the last sentence is the key: "wait a few minutes for the action to propagate". Enabling an API is not instantaneous.
The declarative way:
locals {
apis = [
"compute.googleapis.com", # Compute Engine: VPC, VMs, load balancers
"sqladmin.googleapis.com", # Cloud SQL
"servicenetworking.googleapis.com", # private service access (Cloud SQL private IP)
"secretmanager.googleapis.com", # Secret Manager
"storage.googleapis.com", # Cloud Storage
"iam.googleapis.com", # service accounts
"cloudresourcemanager.googleapis.com", # project management
"monitoring.googleapis.com",
"logging.googleapis.com",
]
}
resource "google_project_service" "apis" {
for_each = toset(local.apis)
project = var.project_id
service = each.value
# If false, a destroy DISABLES the API in the project.
# That affects EVERYTHING in the project, whether Terraform manages it or not.
disable_on_destroy = false
# If true, disabling drags dependent services with it. Very dangerous.
disable_dependent_services = false
}
# Wait for propagation: without this, the first apply on a new project fails.
resource "time_sleep" "api_propagation" {
depends_on = [google_project_service.apis]
create_duration = "60s"
}disable_on_destroy = false is the right setting in almost every case, and the reason deserves the warning:
Warning. With
disable_on_destroy = true(the default), aterraform destroydisables the Compute Engine API across the whole project. If that project contains anything else — created by another team, by another Terraform configuration, or by hand — it stops working. Withdisable_dependent_services = truethe damage spreads to services that depend on the disabled one. It is one of the fastest ways to cause a wide incident with a command that looked local.
And the depends_on needed on the resources that use each API:
resource "google_compute_network" "main" {
name = "${local.prefix}-vpc"
auto_create_subnetworks = false
depends_on = [time_sleep.api_propagation]
}Two practical nuances:
- Once enabled, the API stays enabled. The
time_sleeponly hurts on the firstapplyof a new project. In a project already in use, none of this is noticeable. - The alternative to managing them with Terraform is to enable them once with
gcloud services enableas part of provisioning the project, and not declare them in the code. That is defensible: they are a prerequisite of the project, not part of the application's infrastructure. EcoMarket declares them in the project configuration (infra/project/), separate frominfra/app/, on the same rate-of-change criterion as 04-05.
- Networking: the global VPC and regional subnets
Here is the most important conceptual difference in this lesson.
flowchart TB
subgraph AWSB["AWS / Azure"]
V1["VPC / VNet<br/><b>regional</b><br/>eu-west-1"]
V2["VPC / VNet<br/><b>regional</b><br/>us-east-1"]
V1 -.->|"peering<br/>required"| V2
end
subgraph GCPB["GCP"]
G["<b>GLOBAL</b> VPC<br/>just one"]
S1["Subnet<br/>europe-west1<br/>10.20.0.0/24"]
S2["Subnet<br/>us-east1<br/>10.21.0.0/24"]
S3["Subnet<br/>asia-east1<br/>10.22.0.0/24"]
G --> S1
G --> S2
G --> S3
S1 <-.->|"they see each other<br/><b>with nothing configured</b>"| S2
S2 <-.-> S3
end
style G fill:#dcfce7,stroke:#16a34a
style V1 fill:#fef3c7,stroke:#d97706
style V2 fill:#fef3c7,stroke:#d97706
In AWS and Azure, a private network belongs to a region: to connect two regions you need peering, route tables and, very often, cross-region DNS resolution. In GCP, the VPC is a global resource and subnets in different regions talk to each other natively over private IP, with nothing peered. The consequences:
| Consequence | Detail |
|---|---|
| Multi-region is far simpler | Adding a region is adding a subnet |
| The address space is a single one | It has to be planned globally: a 10.20.0.0/24 subnet takes that range for the whole VPC |
| The firewall is global | One rule applies across the whole VPC, in every region |
| The blast radius is larger | A badly written rule affects every region at once |
| Routes are global | A route you create affects the whole VPC |
resource "google_compute_network" "main" {
name = "${local.prefix}-vpc"
# CRITICAL: without this, GCP automatically creates a subnet in EVERY region
# (more than 40), with ranges you do not control. Always false.
auto_create_subnetworks = false
routing_mode = "REGIONAL" # or GLOBAL: see below
mtu = 1460
delete_default_routes_on_create = false
depends_on = [time_sleep.api_propagation]
}auto_create_subnetworks = false is non-negotiable. With true (the default if you omit the field in some contexts), GCP creates a subnet in each of its 40-plus regions with predetermined ranges that will almost certainly clash with your corporate network and that you cannot change without recreating the VPC.
routing_mode deserves the table:
| Mode | What it does | When |
|---|---|---|
REGIONAL (default) |
Routes learned by a Cloud Router are advertised only in its region | The usual choice. Smaller blast radius |
GLOBAL |
Routes are advertised to every region in the VPC | Hybrid networks with a link to a data centre that must reach every region |
resource "google_compute_subnetwork" "web" {
name = "${local.prefix}-snet-web"
network = google_compute_network.main.id
region = var.region
ip_cidr_range = cidrsubnet(var.cidr, 8, 0) # 10.20.0.0/24
# Private Google access: VMs with no public IP can reach Google's APIs
# (Cloud Storage, Secret Manager) WITHOUT going through Cloud NAT.
# It is FREE and saves NAT money. Always turn it on.
private_ip_google_access = true
log_config {
aggregation_interval = "INTERVAL_10_MIN"
flow_sampling = 0.5
metadata = "INCLUDE_ALL_METADATA"
}
}private_ip_google_access = true is the free equivalent of AWS's VPC endpoints, and it is better: it covers all of Google's APIs at once. With it enabled, an instance with no public IP can read from the images bucket and from Secret Manager without needing Cloud NAT, which is exactly EcoMarket's case. It is one of the reasons GCP's dev can come out cheaper than AWS's.
Cost warning. Flow logs (
log_config) are useful for security and debugging, and they cost by ingested volume (~$0.50/GB after the project's first 50 GB). In an environment with real traffic they can be a significant line item.flow_sampling = 0.5samples half; indev, consider turning them off entirely. A joint security and FinOps decision.
- Secondary ranges and what they are really for
A GCP subnet can have additional named address ranges, something that does not exist in AWS or Azure:
resource "google_compute_subnetwork" "web" {
name = "${local.prefix}-snet-web"
network = google_compute_network.main.id
region = var.region
ip_cidr_range = "10.20.0.0/24" # primary range: the VMs
private_ip_google_access = true
secondary_ip_range {
range_name = "pods"
ip_cidr_range = "10.30.0.0/16" # 65,536 addresses for pods
}
secondary_ip_range {
range_name = "services"
ip_cidr_range = "10.31.0.0/20" # 4,096 for services
}
}Their dominant use case is Kubernetes, and it is worth understanding why even though GKE is not this lesson's topic: in GKE with VPC-native networking, each pod gets a real VPC IP address from a secondary range. That makes pods addressable from the rest of the network with no encapsulation or translation, which enormously simplifies routing and debugging, at the price of consuming a lot of addresses.
Two rules that save you a migration:
- Size the secondary ranges very generously. Expanding them later is possible but painful, and undersizing them caps the cluster's pod count forever.
- Reserve the ranges even if you are not going to use GKE yet. They cost nothing and they stop the address space becoming fragmented.
Deploying GKE itself is Project 3 in module 10; here it is enough to leave the network ready.
- Firewall: rules on the network and the tag model
The third big conceptual difference. In AWS you attach a security group to an instance; in Azure, a network security group to a subnet or an interface. In GCP, rules live on the VPC and apply to the instances carrying certain network tags.
resource "google_compute_firewall" "allow_load_balancer" {
name = "${local.prefix}-fw-lb-to-web"
network = google_compute_network.main.name
direction = "INGRESS"
priority = 1000 # 0-65535, the lowest number wins
# SOURCE: the ranges from which Google's health checkers
# and load balancers send traffic. They are fixed and public.
source_ranges = ["130.211.0.0/22", "35.191.0.0/16"]
# TARGET: the instances carrying THIS network tag.
target_tags = ["ecomarket-web"]
allow {
protocol = "tcp"
ports = ["8080"]
}
log_config {
metadata = "INCLUDE_ALL_METADATA"
}
}
resource "google_compute_firewall" "deny_all_ingress" {
name = "${local.prefix}-fw-deny-ingress"
network = google_compute_network.main.name
direction = "INGRESS"
priority = 65000 # very high: evaluated last
source_ranges = ["0.0.0.0/0"]
deny {
protocol = "all"
}
}The model's rules, in a table:
| Aspect | How it works in GCP |
|---|---|
| Where the rule lives | On the VPC, which is global: it applies in every region |
| Who it applies to | The instances with the given target_tags, or those in a target_service_accounts, or all of them if nothing is stated |
| Priority | 0 to 65535, the lowest number wins. Like Azure |
| Allow and deny | Both exist (allow and deny). Like Azure |
| Implicit rules | Deny all ingress (priority 65535) and allow all egress (65535) |
| Source | source_ranges (CIDR), source_tags (tags on other instances) or source_service_accounts |
| Stateful or not | Stateful, like AWS: the reply to an allowed connection comes back without an explicit rule |
Network tags or service accounts: the two ways of pointing at instances.
target_tags / source_tags |
target_service_accounts / source_service_accounts |
|
|---|---|---|
| What they are | Free-form strings set on the instance | The instance's identity |
| Who can change them | Anybody with permission to edit the instance | Only whoever can change the attached service account (a more restricted permission) |
| Readability | High: ecomarket-web is self-explanatory |
Medium: a long email address |
| Security | Lower: adding a tag to your VM grants you access | Higher |
| Mixable | Tags and service accounts cannot be combined in the same rule |
Security warning. The network tag model has one specific and little-known weak point: anybody with permission to edit an instance can add a tag to it and thereby grant themselves whatever access that tag confers. If the
ecomarket-datarule allows reaching PostgreSQL, tagging any VM that way is enough. In environments where several people can create instances, usetarget_service_accounts, which requires a far more restricted permission. It is a decision to review with the security team.
And the tag on the instance:
resource "google_compute_instance" "web" {
# ...
tags = ["ecomarket-web"] # careful: in GCP "tags" are NETWORK TAGS
labels = { # and "labels" are the metadata/cost tags
project = "ecomarket"
environment = var.environment
managed_by = "terraform"
}
}This is the number one confusion when arriving from AWS to GCP: tags in GCP are not cost tags, they are network tags for the firewall. Cost allocation tags are labels, and they have their own rules: lower case, digits, hyphens and underscores only, maximum 63 characters. Project = "EcoMarket" is invalid; project = "ecomarket" is fine.
- Internet egress: router and Cloud NAT
resource "google_compute_router" "main" {
count = var.create_nat ? 1 : 0
name = "${local.prefix}-router"
network = google_compute_network.main.id
region = var.region
}
resource "google_compute_router_nat" "egress" {
count = var.create_nat ? 1 : 0
name = "${local.prefix}-nat"
router = google_compute_router.main[0].name
region = var.region
nat_ip_allocate_option = "AUTO_ONLY"
source_subnetwork_ip_ranges_to_nat = "LIST_OF_SUBNETWORKS"
subnetwork {
name = google_compute_subnetwork.web.id
source_ip_ranges_to_nat = ["PRIMARY_IP_RANGE"]
}
log_config {
enable = true
filter = "ERRORS_ONLY" # ALL generates a lot of volume and cost
}
}Cost warning. Cloud NAT costs ~$0.044/hour per gateway (~$32/month) plus ~$0.045/GB processed, the same as its equivalents. But in GCP it is often unnecessary: if all the instances need is to reach Google's APIs (Cloud Storage, Secret Manager, Artifact Registry),
private_ip_google_access = truehandles it for free. Cloud NAT is only needed to reach the general Internet: Debian package repositories, third-party APIs. A common alternative in production is to build the image with Packer so no packages are needed at boot, and do without NAT.
Two structural advantages of Cloud NAT over the other clouds:
- It is not a resource in the traffic path: it is a distributed configuration of Google's network plane. There is no per-gateway bandwidth bottleneck.
- It is regional and covers every zone, as in Azure, so one per region is enough.
- Compute (I): the instance and its service account
# The machine's identity, the equivalent of AWS's instance role.
resource "google_service_account" "web" {
account_id = "${local.prefix}-web" # 6-30 characters, lower case
display_name = "Service account for the EcoMarket web tier ${var.environment}"
}
data "google_compute_image" "base" {
family = "ubuntu-2404-lts-amd64"
project = "ubuntu-os-cloud"
}
resource "google_compute_instance" "web" {
count = var.fixed_instances
name = "${local.prefix}-web-${count.index}"
machine_type = var.machine_type # e2-micro: free tier in some regions
zone = var.zones[count.index % length(var.zones)]
# NETWORK tags: which firewall rules it answers to.
tags = ["ecomarket-web"]
# COST AND METADATA labels: lower case is mandatory.
labels = local.labels
boot_disk {
initialize_params {
image = data.google_compute_image.base.self_link
size = 20
type = "pd-balanced" # pd-standard is cheaper and much slower
labels = local.labels
}
auto_delete = true # the disk dies with the VM
}
network_interface {
subnetwork = google_compute_subnetwork.web.id
# NO access_config block: the instance has NO public IP.
# With private_ip_google_access it can still reach Google's APIs.
}
service_account {
email = google_service_account.web.email
# "Scopes" are an OLD mechanism predating IAM. The current
# recommendation is cloud-platform and controlling real access with IAM roles.
scopes = ["cloud-platform"]
}
metadata = {
# Blocks project-wide SSH keys: only this instance's, or none.
block-project-ssh-keys = "TRUE"
enable-oslogin = "TRUE" # access by Google identity, no keys
}
# Startup script. Covered in depth in 05-05.
metadata_startup_script = templatefile("${path.module}/templates/startup.sh.tftpl", {
db_endpoint = var.db_endpoint
bucket = var.bucket_name
environment = var.environment
})
shielded_instance_config {
enable_secure_boot = true
enable_vtpm = true
enable_integrity_monitoring = true
}
allow_stopping_for_update = true # allows changes requiring a stop rather than a recreate
lifecycle {
ignore_changes = [
boot_disk[0].initialize_params[0].image, # the family moves on by itself
metadata_startup_script,
]
}
}Five decisions with explanations:
data "google_compute_image"withfamilyinstead of a specific identifier. GCP image families always point at the latest version, and unlike AWS AMIs, the same family name works in every region. It is the most convenient model of the three clouds. The moving-image trap is the same, and so is the fix:ignore_changesor pinning the version.- With no
access_configthere is no public IP, and withprivate_ip_google_accessthe instance can still read from Cloud Storage and Secret Manager. This combination is the correct default design. scopes = ["cloud-platform"]baffles arrivals from AWS. Scopes are an access control predating IAM that still exists and acts as an additional filter: even if the service account has a role, if the instance's scope does not cover it, access fails. The current official recommendation is to setcloud-platform(which filters nothing) and do all the control with IAM roles on the service account.enable-oslogin = "TRUE"replaces SSH key handling with Google identities and IAM permissions. It is markedly better than managing public keys by hand, and it is what EcoMarket uses instead of opening SSH.allow_stopping_for_update = truelets Terraform stop the instance to apply changes that require it (changing the machine type, for instance) rather than recreating it. Without it, those changes produce a replacement.
- Compute (II): template and regional managed instance group
resource "google_compute_instance_template" "web" {
name_prefix = "${local.prefix}-web-"
machine_type = var.machine_type
region = var.region
tags = ["ecomarket-web"]
labels = local.labels
disk {
source_image = data.google_compute_image.base.self_link
auto_delete = true
boot = true
disk_size_gb = 20
disk_type = "pd-balanced"
}
network_interface {
subnetwork = google_compute_subnetwork.web.id
}
service_account {
email = google_service_account.web.email
scopes = ["cloud-platform"]
}
metadata = {
enable-oslogin = "TRUE"
block-project-ssh-keys = "TRUE"
startup-script = templatefile("${path.module}/templates/startup.sh.tftpl", {
db_endpoint = var.db_endpoint
bucket = var.bucket_name
environment = var.environment
})
}
shielded_instance_config {
enable_secure_boot = true
enable_vtpm = true
enable_integrity_monitoring = true
}
# MANDATORY: templates are IMMUTABLE. Any change requires creating
# a new one before destroying the old one, which is still in use.
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_health_check" "web" {
name = "${local.prefix}-hc-web"
check_interval_sec = 10
timeout_sec = 5
healthy_threshold = 2
unhealthy_threshold = 3
http_health_check {
port = 8080
request_path = "/health"
}
log_config {
enable = true
}
}
resource "google_compute_region_instance_group_manager" "web" {
name = "${local.prefix}-mig-web"
region = var.region
base_instance_name = "${local.prefix}-web"
# Spread across the region's zones: automatic high availability.
distribution_policy_zones = var.zones
version {
instance_template = google_compute_instance_template.web.self_link
}
named_port {
name = "http"
port = 8080
}
auto_healing_policies {
health_check = google_compute_health_check.web.id
initial_delay_sec = 180 # time for cloud-init to finish
}
update_policy {
type = "PROACTIVE"
minimal_action = "REPLACE"
max_surge_fixed = 3 # must be >= the number of zones
max_unavailable_fixed = 0
replacement_method = "SUBSTITUTE"
instance_redistribution_type = "PROACTIVE"
}
}
resource "google_compute_region_autoscaler" "web" {
name = "${local.prefix}-autoscaler-web"
region = var.region
target = google_compute_region_instance_group_manager.web.id
autoscaling_policy {
min_replicas = var.instances.min
max_replicas = var.instances.max
cooldown_period = 120
cpu_utilization {
target = 0.6
}
}
}Three points that set this apart from its equivalents:
- Auto-healing (
auto_healing_policies) is an explicit concept and separate from load balancing. GCP replaces instances that fail the health check whether or not there is a load balancer.initial_delay_secis critical: if it is shorter than cloud-init's boot time, the group enters a loop of killing instances that were still starting up. It is a baffling and fairly common failure. update_policywithtype = "PROACTIVE"makes a template change apply to existing instances, just like AWS'sinstance_refresh. WithOPPORTUNISTIC, the change only affects new instances and theapplylooks as though it did nothing.- The regional group spreads across zones automatically. There is no need to create one group per zone:
distribution_policy_zoneshandles it. It is the equivalent of AWS'svpc_zone_identifier, and simpler.
- Load balancing: why a global load balancer is five resources
This is where GCP looks more complicated than the other two clouds, and it is worth understanding that the complexity has a reason: GCP's HTTP(S) load balancer is global, with a single anycast IP address served from Google's point of presence nearest the user anywhere in the world. That is not a regional load balancer under another name: it is a different capability, and that is why its model is broken into pieces.
flowchart LR
C(("User<br/>anywhere<br/>in the world")) --> IP["google_compute_global_address<br/><b>single anycast IP</b>"]
IP --> FR["global_forwarding_rule<br/><i>IP + port</i>"]
FR --> PX["target_https_proxy<br/><i>terminates TLS</i>"]
PX --> UM["url_map<br/><i>which path goes to which backend?</i>"]
UM --> BS["backend_service<br/><i>groups + health + CDN</i>"]
BS --> MIG1["MIG europe-west1"]
BS --> MIG2["MIG us-east1"]
style IP fill:#dcfce7,stroke:#16a34a
style UM fill:#dbeafe,stroke:#2563eb
Each resource answers a different question, which is why there are five:
| Resource | Question it answers | Why it is separate |
|---|---|---|
google_compute_global_address |
Which IP do I listen on? | The IP is reserved and outlives changes to the load balancer |
google_compute_global_forwarding_rule |
Which IP and port? | One proxy can serve several combinations |
google_compute_target_https_proxy |
How is TLS terminated and with which certificate? | Certificates are managed separately and reused |
google_compute_url_map |
Which path or domain goes to which backend? | This is the routing, and it is what changes most |
google_compute_backend_service |
Which groups serve, how is their health checked, is there a CDN? | One backend serves several URL maps |
Seen this way, the decomposition stops looking arbitrary: AWS puts the routing inside the listener rules and GCP pulls it out into a resource of its own, so changing the routing does not touch the load balancer.
resource "google_compute_global_address" "web" {
name = "${local.prefix}-ip-web"
}
resource "google_compute_managed_ssl_certificate" "web" {
name = "${local.prefix}-cert"
managed {
domains = ["${var.environment}.ecomarket.example.com"]
}
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_backend_service" "web" {
name = "${local.prefix}-backend-web"
protocol = "HTTP"
port_name = "http" # matches the MIG's named_port
load_balancing_scheme = "EXTERNAL_MANAGED"
timeout_sec = 30
health_checks = [google_compute_health_check.web.id]
backend {
group = google_compute_region_instance_group_manager.web.instance_group
balancing_mode = "UTILIZATION"
capacity_scaler = 1.0
max_utilization = 0.8
}
# CDN included: in GCP it is a checkbox on the backend, not a separate service.
enable_cdn = var.environment == "prod"
dynamic "cdn_policy" {
for_each = var.environment == "prod" ? [1] : []
content {
cache_mode = "CACHE_ALL_STATIC"
default_ttl = 3600
client_ttl = 3600
max_ttl = 86400
negative_caching = true
}
}
log_config {
enable = true
sample_rate = 1.0
}
}
resource "google_compute_url_map" "web" {
name = "${local.prefix}-urlmap"
default_service = google_compute_backend_service.web.id
# Example of path-based routing: /images/* straight to the bucket.
host_rule {
hosts = ["${var.environment}.ecomarket.example.com"]
path_matcher = "main"
}
path_matcher {
name = "main"
default_service = google_compute_backend_service.web.id
path_rule {
paths = ["/images/*"]
service = google_compute_backend_bucket.images.id
}
}
}
resource "google_compute_target_https_proxy" "web" {
name = "${local.prefix}-proxy-https"
url_map = google_compute_url_map.web.id
ssl_certificates = [google_compute_managed_ssl_certificate.web.id]
ssl_policy = google_compute_ssl_policy.modern.id
}
resource "google_compute_global_forwarding_rule" "https" {
name = "${local.prefix}-fr-https"
target = google_compute_target_https_proxy.web.id
port_range = "443"
ip_address = google_compute_global_address.web.address
load_balancing_scheme = "EXTERNAL_MANAGED"
}Two gifts of this model worth highlighting:
- The managed certificate is free and renews itself, with nothing like ACM's DNS validation. The only condition: the domain's DNS record must already point at the global IP, or the certificate stays in
PROVISIONINGindefinitely. It is a frequent failure and the diagnosis is ingcloud compute ssl-certificates describe. - The CDN is a checkbox on the backend. In AWS, putting CloudFront in front is a separate service and a separate configuration; here it is
enable_cdn = true.
Cost warning. The global HTTP(S) load balancer costs ~$0.025/hour per forwarding rule (~$18/month) plus ~$0.008/GB processed, plus egress traffic (~$0.12/GB to the Internet from Europe). It has no free tier. For practice, exposing an instance with an ephemeral public IP or using
gcloud compute sshwith port forwarding is free and works just as well to check the application runs.
- Data: Cloud SQL with a private IP and service access
Cloud SQL with a private IP requires a concept that does not exist in the other clouds: private service access. Google hosts your Cloud SQL instance in a project of its own and connects that network to yours through managed peering. For it to work, you have to reserve a range of your address space and hand it over.
# 1. Reserve a range for Google's managed services.
resource "google_compute_global_address" "services_range" {
name = "${local.prefix}-services-range"
purpose = "VPC_PEERING"
address_type = "INTERNAL"
prefix_length = 16 # /16: generous, and it is what is recommended
address = "10.100.0.0"
network = google_compute_network.main.id
}
# 2. Create the peering. This resource has quirks: see below.
resource "google_service_networking_connection" "private" {
network = google_compute_network.main.id
service = "servicenetworking.googleapis.com"
reserved_peering_ranges = [google_compute_global_address.services_range.name]
# Needed for the destroy to work on 5.x/6.x providers.
deletion_policy = "ABANDON"
}
# 3. And now, the Cloud SQL instance.
resource "google_sql_database_instance" "main" {
name = "${local.prefix}-psql-${var.suffix}"
database_version = "POSTGRES_16"
region = var.region
# Barrier against an accidental destroy, ON GOOGLE'S SIDE.
deletion_protection = var.protect_deletion
settings {
tier = var.db_tier # db-f1-micro: the cheapest one
availability_type = var.high_availability ? "REGIONAL" : "ZONAL"
disk_type = "PD_SSD"
disk_size = var.disk_gb
disk_autoresize = true
ip_configuration {
ipv4_enabled = false # NO public IP
private_network = google_compute_network.main.id
ssl_mode = "ENCRYPTED_ONLY"
}
backup_configuration {
enabled = var.retention_days > 0
start_time = "02:00"
point_in_time_recovery_enabled = var.environment == "prod"
transaction_log_retention_days = 7
backup_retention_settings {
retained_backups = var.retention_days
retention_unit = "COUNT"
}
}
maintenance_window {
day = 7 # Sunday
hour = 3
update_track = "stable"
}
database_flags {
name = "log_min_duration_statement"
value = "1000"
}
insights_config {
query_insights_enabled = true
query_string_length = 1024
record_application_tags = true
}
user_labels = local.labels
}
depends_on = [google_service_networking_connection.private]
}
resource "google_sql_database" "ecomarket" {
name = "ecomarket"
instance = google_sql_database_instance.main.name
}
resource "google_sql_user" "app" {
name = var.db_user
instance = google_sql_database_instance.main.name
password = random_password.db.result
}The four Cloud SQL quirks you need to know before your first attempt:
- The
depends_onon the network connection is not optional. Without it, creation fails intermittently with a network error that says nothing useful. deletion_policy = "ABANDON"on the network connection. Without it,terraform destroyhangs or fails, because Google does not allow deleting the peering while instances are using it, and the ordering does not always work out.ABANDONleaves the peering in place, which is harmless and costs nothing.- A Cloud SQL instance name cannot be reused for a week after it is deleted. Not even from another project. Hence the random suffix, again the same
random_petfrom module 4: without it, recreating the environment the same day is impossible. deletion_protectionon Cloud SQL defaults totruein the provider. That surprises you in the opposite direction from AWS: your firstterraform destroyin a lab will fail until you set it tofalseand apply.
Cost and data warning.
db-f1-microwith 10 GB runs at around $9-12/month;db-g1-small, around $27;availability_type = "REGIONAL"doubles the price. GCP's free tier does not include Cloud SQL, although the initial $300 of credit covers it comfortably while learning. On the data: deleting a Cloud SQL instance removes its automatic backups; only backups exported to Cloud Storage survive. Before destroying anything with real data, export.
Security warning.
ipv4_enabled = falseandssl_mode = "ENCRYPTED_ONLY"are the minimum. If for some reason you need a public IP in development, use the Cloud SQL Auth Proxy instead of opening ranges: it authenticates with IAM and encrypts, without exposing the port. Never useauthorized_networkswith0.0.0.0/0.
- Storage: bucket, uniform access and lifecycle
resource "google_storage_bucket" "images" {
# GLOBALLY unique, like S3.
name = "${local.prefix}-images-${var.suffix}"
location = var.bucket_location # "EU" (multi-region) or "europe-west1"
storage_class = "STANDARD"
# THE MOST IMPORTANT ONE: disables per-object ACLs and uses IAM ONLY.
uniform_bucket_level_access = true
# Prevents public access at organisation/project level.
public_access_prevention = "enforced"
versioning {
enabled = true
}
lifecycle_rule {
condition {
age = 90
}
action {
type = "SetStorageClass"
storage_class = "NEARLINE" # ~50 % cheaper, 30-day minimum
}
}
lifecycle_rule {
condition {
age = 365
}
action {
type = "SetStorageClass"
storage_class = "COLDLINE"
}
}
lifecycle_rule {
condition {
num_newer_versions = 3
with_state = "ARCHIVED"
}
action {
type = "Delete"
}
}
# Cleans up aborted multipart uploads: invisible cost, same as in S3.
lifecycle_rule {
condition {
days_since_noncurrent_time = 30
}
action {
type = "Delete"
}
}
# Encryption with a customer-managed key (optional; it already encrypts by default).
dynamic "encryption" {
for_each = var.kms_key_name != null ? [1] : []
content {
default_kms_key_name = var.kms_key_name
}
}
# Stops a bucket with contents being destroyed, except in dev.
force_destroy = var.environment == "dev"
labels = local.labels
}
# Permissions: the web's service account can read and write objects.
resource "google_storage_bucket_iam_member" "web_objects" {
bucket = google_storage_bucket.images.name
role = "roles/storage.objectAdmin"
member = "serviceAccount:${google_service_account.web.email}"
}uniform_bucket_level_access = true deserves emphasis. Google Cloud Storage carries two permission systems: per-object ACLs (inherited from the original design, as in S3) and IAM. Having both active at once makes effective permissions hard to reason about and is a common source of accidental exposure. Enabling uniform access disables ACLs entirely and leaves only IAM. It is Google's recommended setting and it should be your unvarying default.
google_storage_bucket_iam_member versus its relatives, because this distinction destroys real people's permissions:
| Resource | What it does | Risk |
|---|---|---|
_iam_member |
Adds a member to a role. It does not touch the others | None. Always use this one |
_iam_binding |
Replaces the complete list of members for that role | It removes anybody not on your list |
_iam_policy |
Replaces the bucket's entire policy, every role | It can lock you out yourself |
This trio (_member, _binding, _policy) exists for every GCP resource with IAM: projects, buckets, secrets, service accounts. The rule is simple and saves incidents: _member unless you know exactly why you need something else.
Cost warning. Cloud Storage Standard in
europe-west1costs ~$0.020/GB/month, plus ~$0.05 per 10,000 class A operations. GCP's permanent free tier includes 5 GB/month in US regions (not in Europe). Egress to the Internet is around $0.12/GB. As in the other clouds, an empty bucket is free. And a warning specific to GCP: the Nearline, Coldline and Archive classes have a minimum storage duration (30, 90 and 365 days); deleting earlier is still charged for the full period, so aggressive lifecycle rules can increase the bill.
- Secrets: Secret Manager and the service account
resource "random_password" "db" {
length = 32
special = true
override_special = "!#$%&*()-_=+"
}
resource "google_secret_manager_secret" "db_password" {
secret_id = "${local.prefix}-db-password"
replication {
# Option 1: automatic, replicated by Google wherever it likes.
# auto {}
# Option 2 (chosen): location control, for data residency.
user_managed {
replicas {
location = var.region
}
replicas {
location = var.secondary_region
}
}
}
labels = local.labels
depends_on = [time_sleep.api_propagation]
}
resource "google_secret_manager_secret_version" "db_password" {
secret = google_secret_manager_secret.db_password.id
secret_data = random_password.db.result
# Disables the previous version when a new one is created, rather than leaving it active.
deletion_policy = "DISABLE"
}
# The web's service account can READ this secret. Nothing more.
resource "google_secret_manager_secret_iam_member" "web_reads" {
secret_id = google_secret_manager_secret.db_password.secret_id
role = "roles/secretmanager.secretAccessor"
member = "serviceAccount:${google_service_account.web.email}"
}Scope matters a great deal. google_secret_manager_secret_iam_member grants access to one specific secret. The lazy alternative would be:
# DO NOT DO THIS.
resource "google_project_iam_member" "web_reads_everything" {
project = var.project_id
role = "roles/secretmanager.secretAccessor"
member = "serviceAccount:${google_service_account.web.email}"
}That grants access to every secret in the project, present and future, including the ones another team creates tomorrow. In GCP permissions are inherited downwards through the organisation → folder → project → resource hierarchy, so a role granted at project level reaches everything inside it.
And from the instance, this is how the secret is read with no credentials at all:
# Inside the VM, thanks to the attached service account:
gcloud secrets versions access latest --secret=ecomarket-dev-db-passwordThe built-in roles that appear in this lesson, with their appropriate scope:
| Role | What it allows | Appropriate scope |
|---|---|---|
roles/secretmanager.secretAccessor |
Reading a secret's value | The secret, never the project |
roles/storage.objectAdmin |
Reading, writing and deleting objects | The bucket |
roles/storage.objectViewer |
Reading objects only | The bucket |
roles/cloudsql.client |
Connecting via the Cloud SQL proxy | The project (there is no narrower scope) |
roles/logging.logWriter |
Writing logs | The project |
roles/monitoring.metricWriter |
Writing metrics | The project |
roles/iam.serviceAccountTokenCreator |
Impersonating a service account | The specific service account |
Security warning. The last row is the most delicate:
serviceAccountTokenCreatoron an account with broad permissions is equivalent to having those permissions. It is the mechanism that makes section 3's impersonation possible, and also an escalation path if it is granted at a broad scope. Always grant it on the specific service account, never at project level, and audit it periodically. Security team review is mandatory.
Cost warning. Secret Manager costs $0.06 per active version per month (versus AWS's $0.40) plus $0.03 per 10,000 accesses. The first 6 secrets and 10,000 accesses per month are free. It is the cheapest option of the three clouds.
- Global, regional and zonal resources, costs and
destroy
destroyGCP classifies every resource into one of three scopes, and that classification decides where it lives, which failure takes it down and how much traffic towards it costs.
| Scope | Examples | Survives | Implication |
|---|---|---|---|
| Global | VPC, firewall rules, global IPs, HTTP(S) load balancer, images, snapshots, URL maps | The loss of any region | Changing it affects everything at once |
| Regional | Subnets, regional instance groups, Cloud SQL, regional IP addresses, Cloud NAT, regional buckets | The loss of a zone | The usual level of resilience |
| Zonal | Instances, persistent disks, zonal instance groups | Nothing: it goes down with its zone | Never put anything critical in just one |
EcoMarket's practical rule: nothing zonal without a replica. Instances are zonal, but they live inside a regional group that spreads them; disks are zonal, so state lives in Cloud SQL or in Cloud Storage, never on the machine's disk.
Monthly cost estimate for dev in europe-west1. Indicative figures.
| Resource | Approx. monthly cost | Free tier? |
|---|---|---|
| VPC, subnets, firewall rules, routes | $0 | Always free |
private_ip_google_access |
$0 | Always free. Avoids needing NAT |
| Enabling APIs | $0 | Always free |
| Cloud NAT + router | ~$32 + data | No. Often unnecessary |
| Global HTTP(S) load balancer | ~$18 + data | No |
| Managed SSL certificate | $0 | Free and auto-renewed |
e2-micro instance |
~$7 | Yes in us-*: 1 instance always free. In Europe, no |
20 GB pd-balanced disk |
~$2.2 | Yes: 30 GB of pd-standard in us-* |
Cloud SQL db-f1-micro 10 GB |
~$9-12 | No. Covered by the $300 credit |
| Bucket (2 GB) | ~$0.04 | Yes: 5 GB, only in us-* |
| Secret Manager (1 secret) | $0 | Yes: 6 secrets free |
| VPC flow logs | ~$0.50/GB after 50 GB | Partial |
dev TOTAL with NAT and load balancer |
~$70-80/month | |
dev TOTAL without NAT or load balancer |
~$10-15/month | Covered by the initial credit |
Three quirks of GCP's pricing model worth knowing:
- The $300 credit for new accounts (90 days) covers this entire module comfortably. It is the most generous starting point of the three clouds.
- Sustained use discounts are automatic: an instance left on all month is charged up to 30 % cheaper with no action on your part. Nothing like it exists in AWS or Azure without a prior commitment.
- The permanent free tier is in US regions (
us-west1,us-central1,us-east1), not in Europe. If the goal is to practise at zero cost and latency does not matter,us-central1is the choice; if you want consistency with the rest of the course,europe-west1with the credit.
A guided destroy and what survives:
# 1. See what is going to be destroyed
terraform plan -destroy -var-file=dev.tfvars -out=destroy.tfplan
# 2. If Cloud SQL has deletion_protection, it has to be removed first
# (remember: in GCP it is true BY DEFAULT)
terraform apply -var="protect_deletion=false" -var-file=dev.tfvars
# 3. Destroy (10-20 min; Cloud SQL dominates)
terraform destroy -var-file=dev.tfvars
# 4. Check what is left
gcloud compute instances list
gcloud compute disks list --filter="-users:*" # orphaned disks
gcloud compute addresses list --filter="status!=IN_USE" # reserved unused IPs
gcloud sql instances list
gcloud storage buckets list
gcloud compute snapshots list
gcloud compute images list --no-standard-images
gcloud secrets listSurvives the destroy |
Why | Cost |
|---|---|---|
| Reserved static IP addresses that are unused | They are reserved separately from the resource using them | ~$7.3/month each: the most expensive thing to forget |
| Orphaned persistent disks | If auto_delete = false |
~$2.2/month per 20 GB |
| Snapshots and custom images | Never managed if they were created by hand | ~$0.026/GB/month |
| Buckets with contents | destroy fails without force_destroy |
~$0.020/GB/month |
| Old object versions | Versioning keeps them | The same as the object |
| The service networking peering | Left on purpose with deletion_policy = "ABANDON" |
$0 |
| The Cloud SQL instance name | Blocked for a week | $0, but it stops you recreating |
| Cloud Logging logs | They outlive their source | ~$0.50/GB after 50 GB |
The first row is GCP's surprise: a static IP that is reserved and unused costs more than one in use (~$0.010/hour versus free when associated). It is the opposite of intuitive and it is deliberate: Google discourages hoarding addresses. Always check for them after destroying.
Common Mistakes and Tips
Forgetting gcloud auth application-default login. gcloud auth login authenticates the CLI, not the libraries Terraform uses. Both commands, always.
Not enabling the APIs, or not waiting for them to propagate. The 403 accessNotConfigured error says exactly what is missing. Declare the APIs with google_project_service and add a 60-second time_sleep on new projects.
Leaving disable_on_destroy = true on google_project_service. A destroy disables the API across the whole project, affecting everything else inside it. Set it to false.
Forgetting auto_create_subnetworks = false. GCP creates a subnet in more than 40 regions with ranges you did not choose and that will probably clash with your corporate network.
Confusing tags with labels. In GCP, tags are network tags for the firewall; labels are the cost and metadata ones, and they only accept lower case, digits, hyphens and underscores.
Using target_tags where target_service_accounts belongs. Anybody who can edit an instance can add a tag to it and grant themselves that access.
Using _iam_binding or _iam_policy instead of _iam_member. The first two replace the existing list and remove other people's permissions. _member adds without destroying.
Granting roles at project level out of convenience. Permissions are inherited downwards: secretAccessor on the project grants access to every secret, including ones that do not exist yet.
Forgetting the depends_on from google_sql_database_instance to the network connection. Intermittent failures with uninformative messages.
Not setting deletion_policy = "ABANDON" on google_service_networking_connection. The destroy hangs or fails.
Being surprised that the Cloud SQL destroy fails. deletion_protection is true by default in GCP, unlike AWS. It has to be turned off with a prior apply.
Trying to recreate a Cloud SQL instance with the same name on the same day. The name is blocked for a week. Use the random suffix.
An initial_delay_sec that is too low in auto-healing. The group kills instances that were still starting up, in a loop. Give it at least twice cloud-init's boot time.
Using OPPORTUNISTIC in update_policy and expecting the instances to change. It only affects new ones. To apply to existing ones, PROACTIVE.
Leaving reserved static IPs unused. They cost ~$7.3/month each, more than when associated. It is GCP's most expensive phantom spend.
Applying aggressive lifecycle rules towards Nearline/Coldline. They have minimum durations of 30/90/365 days: deleting earlier is charged anyway, and the rule can raise the bill.
Tip: use private_ip_google_access and skip Cloud NAT. If your instances only talk to Google APIs, it is free and makes $32/month unnecessary.
Tip: one project per environment. Creating projects in GCP is trivial, and the isolation they give (quotas, permissions, billing, networking) is far stronger than any naming convention.
Tip: enable Organization Policy for the non-negotiables. Forbidding public IPs on VMs, requiring uniform access on buckets, restricting regions. It works even when somebody deploys from the console. It connects with 07-04.
Tip: any change to IAM roles, firewall rules or Cloud SQL's network mode is reviewed with security; any hourly-cost resource, with FinOps. In GCP, with permission inheritance, a misplaced role has a larger blast radius than in the other clouds.
Exercises
Exercise 1: EcoMarket's network on GCP (cost ~$0)
Deploy only the network, with no NAT and no load balancer:
- Write
versions.tfwithgoogle ~> 6.0andproviders.tfwithproject,regionandzone. - Enable the Compute Engine, Cloud SQL, Service Networking, Secret Manager and Storage APIs with
google_project_service, withdisable_on_destroy = false, and add the propagationtime_sleep. - Create the VPC with
auto_create_subnetworks = falseand a subnet ineurope-west1withprivate_ip_google_access = trueand two secondary ranges (podsandservices). - Create two firewall rules: allow 8080 from Google's health check ranges towards
target_tags = ["ecomarket-web"], and allow 5432 fromsource_tags = ["ecomarket-web"]towardstarget_tags = ["ecomarket-data"]. - Add a
checkblock that verifies the project. - Apply, verify with
gcloud compute networks subnets describe, and destroy.
Note the timings and compare them with the equivalent AWS and Azure exercises.
Exercise 2: dissecting the global load balancer
Without deploying anything, answer with reasoning:
- Draw (in text or mermaid) the chain of the global HTTP(S) load balancer's five resources and state which question each one answers.
- EcoMarket wants to serve
/images/*straight from the bucket and everything else from the instances. Which of the five resources has to be modified and which ones are not touched? Write the snippet. - EcoMarket opens a second region (
us-east1) with its own managed instance group. Which resources have to be added and which are reused as they are? Compare with what would have to be done in AWS. - Explain why the IP is a separate resource and what problem that would solve if the entire load balancer had to be rebuilt.
- Write the cost table for this load balancer at 100 GB of monthly egress traffic to the Internet, and compare it with the AWS application load balancer from 05-02.
Exercise 3: least privilege for the web
The application needs to: read and write objects in the images bucket, read the PostgreSQL password from Secret Manager, connect to Cloud SQL, and write logs and metrics. Write, without deploying:
- The service account, with a name that respects GCP's constraints.
- Each permission grant with the correct IAM resource and at the narrowest possible scope. Justify each scope.
- Explain what would happen if you used
google_project_iam_bindinginstead of_memberon one of them. - The instance configuration that attaches that account, with no public IP, with OS Login and with secure boot.
- A table comparing this model with AWS's instance role and Azure's managed identity, on four axes: number of resources, scope granularity, inheritance and main risk.
Solution 1
# versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
google = { source = "hashicorp/google", version = "~> 6.0" }
time = { source = "hashicorp/time", version = "~> 0.11" }
}
}
# providers.tf
provider "google" {
project = var.project_id
region = "europe-west1"
zone = "europe-west1-b"
}
data "google_project" "current" {}
check "correct_project" {
assert {
condition = data.google_project.current.project_id == var.project_id
error_message = "Active project: ${data.google_project.current.project_id}."
}
}# main.tf
locals {
prefix = "ecomarket-${var.environment}"
labels = {
project = "ecomarket"
environment = var.environment
managed_by = "terraform"
}
apis = [
"compute.googleapis.com",
"sqladmin.googleapis.com",
"servicenetworking.googleapis.com",
"secretmanager.googleapis.com",
"storage.googleapis.com",
]
}
resource "google_project_service" "apis" {
for_each = toset(local.apis)
project = var.project_id
service = each.value
disable_on_destroy = false
disable_dependent_services = false
}
resource "time_sleep" "api_propagation" {
depends_on = [google_project_service.apis]
create_duration = "60s"
}
resource "google_compute_network" "main" {
name = "${local.prefix}-vpc"
auto_create_subnetworks = false
routing_mode = "REGIONAL"
depends_on = [time_sleep.api_propagation]
}
resource "google_compute_subnetwork" "web" {
name = "${local.prefix}-snet-web"
network = google_compute_network.main.id
region = "europe-west1"
ip_cidr_range = "10.20.0.0/24"
private_ip_google_access = true
secondary_ip_range {
range_name = "pods"
ip_cidr_range = "10.30.0.0/16"
}
secondary_ip_range {
range_name = "services"
ip_cidr_range = "10.31.0.0/20"
}
}
resource "google_compute_firewall" "health_to_web" {
name = "${local.prefix}-fw-health-web"
network = google_compute_network.main.name
direction = "INGRESS"
priority = 1000
source_ranges = ["130.211.0.0/22", "35.191.0.0/16"]
target_tags = ["ecomarket-web"]
allow {
protocol = "tcp"
ports = ["8080"]
}
}
resource "google_compute_firewall" "web_to_data" {
name = "${local.prefix}-fw-web-data"
network = google_compute_network.main.name
direction = "INGRESS"
priority = 1000
source_tags = ["ecomarket-web"]
target_tags = ["ecomarket-data"]
allow {
protocol = "tcp"
ports = ["5432"]
}
}Verification and cleanup:
terraform init && terraform apply -auto-approve
gcloud compute networks subnets describe ecomarket-dev-snet-web \
--region=europe-west1 \
--format="yaml(name, ipCidrRange, privateIpGoogleAccess, secondaryIpRanges)"
gcloud compute firewall-rules list \
--filter="network:ecomarket-dev-vpc" \
--format="table(name, direction, priority, sourceRanges.list(), targetTags.list(), allowed[].map().firewall_rule().list())"
terraform destroy -auto-approveExpected timings: the first apply on a new project takes 2-3 minutes, almost all of it waiting for the APIs to be enabled and propagate. Subsequent applies, 20-40 seconds: GCP's network is the fastest of the three to create. The destroy is around 60-90 seconds.
Comparing the three equivalent exercises is instructive:
| AWS | Azure | GCP | |
|---|---|---|---|
apply (first time) |
30-60 s | 60-120 s | 2-3 min (APIs) |
apply (subsequent) |
30-60 s | 60-120 s | 20-40 s |
destroy |
40-90 s | 90-180 s | 60-90 s |
| Declared resources | ~12 | ~10 | ~8 |
| Cost | $0 | $0 | $0 |
GCP needs fewer resources because the VPC is global (there are no route tables to declare, no associations, no subnet per zone) and because firewall rules need no explicit association. The price is the initial API overhead.
Solution 2
1. The chain of five resources:
flowchart LR
A["google_compute_global_address<br/><b>Which IP do I listen on?</b>"]
B["global_forwarding_rule<br/><b>IP + which port?</b>"]
C["target_https_proxy<br/><b>How do I terminate TLS?</b>"]
D["url_map<br/><b>Which path to which backend?</b>"]
E["backend_service<br/><b>Who serves and is it healthy?</b>"]
A --> B --> C --> D --> E
2. Serving /images/* from the bucket. You modify only the url_map, and add a google_compute_backend_bucket. The IP, the forwarding rule, the proxy and the instances' backend_service are not touched:
resource "google_compute_backend_bucket" "images" {
name = "${local.prefix}-backend-images"
bucket_name = google_storage_bucket.images.name
enable_cdn = true
}
resource "google_compute_url_map" "web" {
name = "${local.prefix}-urlmap"
default_service = google_compute_backend_service.web.id
host_rule {
hosts = ["${var.environment}.ecomarket.example.com"]
path_matcher = "main"
}
path_matcher {
name = "main"
default_service = google_compute_backend_service.web.id
path_rule {
paths = ["/images/*"]
service = google_compute_backend_bucket.images.id # ← to the bucket
}
}
}The fact that only one resource changes is exactly the advantage of the decomposition: routing is what changes most, and it is isolated from the IP, the certificate and the backends.
3. Adding us-east1. You add one regional managed instance group in that region and one more backend block inside the existing backend_service:
resource "google_compute_backend_service" "web" {
# ...
backend {
group = google_compute_region_instance_group_manager.web_eu.instance_group
}
backend {
group = google_compute_region_instance_group_manager.web_us.instance_group
}
}Nothing else is touched. The same global IP, the same certificate, the same URL map, and Google routes each user to the nearest backend with spare capacity.
In AWS you would have to: create a VPC in us-east-1, a regional application load balancer of its own with its own certificate, and on top of that a CloudFront or a Route 53 with latency-based routing and health checks to split traffic between the two load balancers. That is between six and ten additional resources and one more architectural layer. This is the most notable practical difference in GCP's favour in the whole lesson.
4. Why the IP is a separate resource. Because the public IP address is the only part of the whole chain that is published outside: in DNS records, in customers' allow-lists, in integration documentation. Being a resource of its own, you can destroy and rebuild the proxy, the URL map and the backend service entirely — a migration, a certificate change, a routing reorganisation — keeping the same IP, without touching DNS and without waiting for propagation. If the IP were an attribute of the load balancer, rebuilding it would mean a new IP and a DNS propagation window for every client.
5. Cost table for 100 GB/month of egress to the Internet:
| Item | GCP (global load balancer) | AWS (application load balancer) |
|---|---|---|
| Fixed cost | ~$18 (1 forwarding rule) | ~$18 |
| Processing | ~$0.008/GB → $0.80 | LCU, ~$2-8 at low traffic |
| Egress to the Internet (Europe) | ~$0.12/GB → $12 | ~$0.09/GB → $9 |
| TLS certificate | $0 (managed, auto-renewed) | $0 (ACM) |
| CDN | A checkbox on the backend, ~$0.08/GB served from cache | CloudFront separately, with its own pricing |
| Multi-region | Included: same IP, one more backend | Requires CloudFront or Route 53 with latency-based routing |
| Approximate total | ~$31/month | ~$29-35/month |
The totals are very close. The real difference is not in the monthly price but in what it includes: GCP's load balancer is already global and has an integrated CDN, whereas the functional equivalent in AWS demands additional services.
Solution 3
1. The service account (6-30 characters, lower case, digits and hyphens):
resource "google_service_account" "web" {
account_id = "ecomarket-${var.environment}-web"
display_name = "EcoMarket web (${var.environment})"
description = "Identity for the ecomarket-web instances. Managed by Terraform."
}2. Each permission at its narrowest scope:
# a) Objects in the images bucket → SCOPE: THE BUCKET.
# A narrower scope is not possible (there is no per-prefix IAM in GCS), so
# if separation were needed, different buckets would be used.
resource "google_storage_bucket_iam_member" "web_objects" {
bucket = google_storage_bucket.images.name
role = "roles/storage.objectAdmin"
member = "serviceAccount:${google_service_account.web.email}"
}
# b) The DB password → SCOPE: THE SPECIFIC SECRET.
# Never at project level: that would grant access to every secret, present
# and future, including other teams'.
resource "google_secret_manager_secret_iam_member" "web_password" {
secret_id = google_secret_manager_secret.db_password.secret_id
role = "roles/secretmanager.secretAccessor"
member = "serviceAccount:${google_service_account.web.email}"
}
# c) Connecting to Cloud SQL → SCOPE: THE PROJECT.
# roles/cloudsql.client admits no narrower scope. It is accepted because the
# role only allows CONNECTING: database authentication still requires
# a username and password, which are in (b).
resource "google_project_iam_member" "web_sql" {
project = var.project_id
role = "roles/cloudsql.client"
member = "serviceAccount:${google_service_account.web.email}"
}
# d) Writing logs → SCOPE: THE PROJECT. There is no narrower one.
resource "google_project_iam_member" "web_logs" {
project = var.project_id
role = "roles/logging.logWriter"
member = "serviceAccount:${google_service_account.web.email}"
}
# e) Writing metrics → SCOPE: THE PROJECT. There is no narrower one.
resource "google_project_iam_member" "web_metrics" {
project = var.project_id
role = "roles/monitoring.metricWriter"
member = "serviceAccount:${google_service_account.web.email}"
}Justifying the scopes is the point of the exercise: (a) and (b) are granted on the specific resource because it is possible; (c), (d) and (e) go at project level because those roles admit no narrower scope, and they are accepted knowingly because they are roles with bounded write access (writing logs and metrics) or that are not sufficient on their own (connecting to Cloud SQL still requires database credentials). Documenting why a permission is broader than ideal is part of the job.
3. What would happen with _binding instead of _member. If in (c) you wrote:
resource "google_project_iam_binding" "web_sql" {
project = var.project_id
role = "roles/cloudsql.client"
members = ["serviceAccount:${google_service_account.web.email}"]
}Terraform would replace the complete list of members holding the roles/cloudsql.client role in the project, removing everybody else: the reporting service's account, the data team's, the development proxy's. And it would do so silently, because the plan only shows one resource changing. The damage appears when another system starts failing for no apparent reason and nobody connects the two events.
The genuinely dangerous variant is google_project_iam_policy, which replaces the project's entire policy, every role at once. One apply can lock you out of your own project and require the organisation administrator to intervene to get it back. Never use _policy on a project.
4. The instance:
resource "google_compute_instance" "web" {
name = "${local.prefix}-web-0"
machine_type = "e2-micro"
zone = "europe-west1-b"
tags = ["ecomarket-web"]
labels = local.labels
boot_disk {
initialize_params {
image = data.google_compute_image.base.self_link
size = 20
type = "pd-balanced"
}
auto_delete = true
}
network_interface {
subnetwork = google_compute_subnetwork.web.id
# No access_config: NO public IP.
}
service_account {
email = google_service_account.web.email
scopes = ["cloud-platform"]
}
metadata = {
enable-oslogin = "TRUE"
block-project-ssh-keys = "TRUE"
}
shielded_instance_config {
enable_secure_boot = true
enable_vtpm = true
enable_integrity_monitoring = true
}
}5. Comparison of the three machine identity models:
| Axis | AWS (role + profile) | Azure (managed identity) | GCP (service account) |
|---|---|---|---|
| Resources needed | 4-5: role, policy document, policy, attachment, instance profile | 1-2: identity {} on the VM + one role assignment per permission |
2 + one grant per permission: the service account and its attachment |
| Scope granularity | The finest: ARNs with wildcards and conditions (s3:prefix, kms:ViaService) |
Hierarchical: subscription → resource group → resource | Hierarchical: organisation → folder → project → resource |
| Inheritance | None: every policy is explicit | Yes, downwards | Yes, downwards |
| Main risk | An over-broad policy (Resource: "*") out of convenience |
Assigning Contributor on the subscription |
Granting a role at project level when a resource scope existed, and using _binding/_policy instead of _member |
One closing note that sums up all three: AWS's model is the most verbose and the most expressive (fine-grained conditions on specific resources); Azure's is the most concise; GCP's sits in the middle, with the peculiarity of the _member/_binding/_policy trio, which is its characteristic trap. In all three, the common mistake is the same and it is called convenience: widening the scope until it stops failing, instead of working out which specific permission was missing.
Conclusion
With this lesson, EcoMarket is deployed across the three major clouds with the same architecture and the same modules, and GCP has contributed the module's deepest conceptual differences:
- The project is the fundamental unit, and creating one is so cheap that the natural strategy is one project per environment, with isolation (quotas, permissions, billing, networking) stronger than any naming convention.
- There are two providers,
googleandgoogle-beta, talking to two parallel APIs. Use the stable one by default and the beta one only on the resources that require it, without mixing them casually on the same resource. - The recommended authentication is ADC plus service account impersonation: people do not accumulate permissions, audit logs are precise and there are no everlasting JSON keys to guard. And
gcloud auth loginis not enough: you needgcloud auth application-default login. - Every API has to be enabled with
google_project_service, you have to wait for it to propagate and — very importantly — leavedisable_on_destroy = false, because adestroywould disable the service for the whole project. - The VPC is global and the subnets regional. Regions talk over private IP with nothing peered, the address space is planned once, and multi-region goes from being a project to being one more subnet.
auto_create_subnetworks = false, always. private_ip_google_accessis GCP's free gift: instances with no public IP that reach Cloud Storage and Secret Manager without needing Cloud NAT. In many designs it removes $32/month.- The firewall lives on the network and targets by tag, with the caveat that anybody who can edit an instance can tag it and grant themselves access: where that matters,
target_service_accounts. tagsare notlabels. The former are network tags; the latter are for cost and metadata, and only accept lower case.- The global load balancer is five resources because it is a different capability, not a regional load balancer under another name: a worldwide anycast IP, a free managed certificate, an integrated CDN and routing isolated in a
url_mapthat you change without touching anything else. Adding a region is adding abackendblock. - Private Cloud SQL requires a reserved range and a service networking connection, with an explicit
depends_on,deletion_policy = "ABANDON"so thedestroyworks,deletion_protectionthat comes enabled by default, and a name that stays blocked for a week after deletion. uniform_bucket_level_access = truedisables ACLs and leaves only IAM, which is what you always want. And the_member/_binding/_policytrio is GCP's characteristic trap:_memberadds, the other two replace and destroy other people's permissions.- Permissions are inherited downwards, so a role granted at project level reaches everything inside it, including resources that do not exist yet. Always the narrowest scope the role allows, and documented when it cannot be narrow.
- Global, regional or zonal classifies every resource and decides its resilience. Nothing zonal without a replica.
- Costs follow the pattern of the other clouds — the network free, egress and load balancing almost the entire bill — with three quirks of their own: $300 of initial credit, automatic sustained use discounts, and a permanent free tier that only exists in US regions. The expensive
destroysurprise is reserved static IPs left unused, at ~$7.3/month each.
One piece remains, and it is the one that makes everything above worth something. Across all three clouds you have created instances that boot, register with a load balancer and wait… with no EcoMarket application installed. Configuring Servers: user_data, cloud-init and Provisioners closes that gap and, above all, draws the boundary between provisioning — what Terraform does — and configuring — what cloud-init, Packer or Ansible do: why HashiCorp considers provisioners a last resort, how to write a #cloud-config that works equally in user_data, custom_data and metadata_startup_script, how those scripts are generated with templatefile() passing them the PostgreSQL endpoint and the bucket name, and why a secret never travels that way but is instead read by the instance using the identity you have just given it in all three clouds.
