<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bikram Singh on Medium]]></title>
        <description><![CDATA[Stories by Bikram Singh on Medium]]></description>
        <link>https://medium.com/@bikram23march?source=rss-e8ab82576afb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZjybJLVn6W81f1de.</url>
            <title>Stories by Bikram Singh on Medium</title>
            <link>https://medium.com/@bikram23march?source=rss-e8ab82576afb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:52:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bikram23march/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ansible Ops Platform on GCP]]></title>
            <link>https://medium.com/@bikram23march/ansible-ops-platform-on-gcp-67d04193ef01?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d04193ef01</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 15:14:19 GMT</pubDate>
            <atom:updated>2026-10-22T15:14:19.497Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>GCP · Terraform · GitHub Actions · AWX · Ansible · GKE · Pub/Sub · Self-healing · DevOps · SRE</strong></p><p><em>Terraform provisions it, GitHub Actions delivers it with no stored keys, and AWX runs patching, hardening, self-healing and alerts. Built and proved end to end on Google Cloud.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0noJGnfJFAcAjxBF.png" /></figure><h3>📖 Introduction</h3><p>Building servers is the easy part. The hard part starts the next morning: patching, hardening, health checks, snapshots, and the 3 a.m. “why is that VM stopped?” I lead infrastructure and DevOps for GCP at work, and I wanted one project that shows how I think about that operational work, end to end. So I built it.</p><p>The result is a platform where Terraform provisions everything, GitHub Actions delivers it without a single stored key, and AWX (the open-source upstream of Ansible Tower) runs the operations: scheduled, approved, audited, tested, and in two cases, fully event-driven.</p><p>Most teams are good at building infrastructure. Infrastructure as code creates networks, clusters and VMs, and a pipeline applies it. Then the daily running of it begins, and the discipline quietly disappears:</p><ul><li><strong>Snowflake servers.</strong> Patching and hardening done by hand means no two machines are quite the same.</li><li><strong>Slow, manual change.</strong> A patch window is a person with a runbook and a terminal. It is slow and easy to get wrong.</li><li><strong>No audit trail.</strong> Who patched production last Tuesday, and what exactly changed? Often nobody can say.</li><li><strong>Shared credentials.</strong> The SSH key travels between engineers, chat messages and laptops.</li><li><strong>Slow incident response.</strong> A stopped VM or a new VM nobody configured waits until somebody notices.</li></ul><p>I wanted to answer a simple question: what would the <em>operations plane</em> look like if it were built with the same care as the infrastructure itself? Everything created from code, nothing clicked into existence, every action approved or audited, and the routine incidents fixed by the platform before a human gets paged.</p><p>So I built <strong>Ansible Ops Platform on GCP</strong>: a private GKE cluster running AWX, a Cloud SQL database on a private IP, a fleet of private VMs, a keyless GitHub Actions pipeline, and an event path that heals and onboards machines on its own. It ran end to end on a real project, gcp-awx-ops, and every claim in this article has a screenshot behind it.</p><h3>🧭 What you will learn</h3><ul><li>How to deploy <strong>AWX on a private GKE cluster</strong> with Terraform and the AWX Operator, backed by Cloud SQL on a private IP</li><li>How to give GitHub Actions access to GCP with <strong>Workload Identity Federation</strong>, and AWX access to the inventory with <strong>Workload Identity</strong>, so no key exists anywhere</li><li>How to keep the <strong>whole AWX configuration in Git</strong> and re-apply it on every merge</li><li>How to build <strong>staged patching</strong> with snapshots, a dev-first order and a human approval gate</li><li>How to <strong>heal a stopped VM and onboard a new VM</strong> from Cloud Audit Logs through Pub/Sub, with no inbound path into the cluster</li><li>How to <strong>lint, test and harden</strong> with ansible-lint, Molecule and a CIS-style role, and how to prove idempotence</li><li>How to send <strong>useful chat alerts</strong>, and why the AWX Test button misleads you</li><li>What broke along the way, and how I fixed it</li></ul><h3>👥 Who this is for</h3><p>Platform, DevOps and SRE engineers who already run Terraform and want the operational side of the fleet to be as repeatable as the build side. A working knowledge of GCP, Kubernetes basics and Ansible will help, but each concept is explained before it is used.</p><h3>🎯 Goals and non-goals</h3><p><strong>Goals:</strong> provision the whole platform as code with no console clicks; run all routine operations through one control plane with RBAC, audit and credential isolation; make operations self-service, scheduled or event-driven; use keyless authentication from CI to cloud; manage the automation platform itself as code; gate every change with automated quality checks.</p><p><strong>Non-goals:</strong> application CI/CD for business apps, multi-region high availability of AWX (single region and a single replica in the lab), and Windows fleet management.</p><p>This article is that build, phase by phase, including what broke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a6wlTeQnjUUV5_SM.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XaQL9J-rd6O3L9jT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JkDheIlkGp06I81V.png" /></figure><h3>🏛️ Architecture</h3><ul><li><strong>Terraform</strong>, five stacks: platform (VPC, private GKE, Cloud SQL, image registry), awx (the operator and AWX), fleet (labelled VMs), selfheal (Pub/Sub, log sinks, bridge) and an optional ingress.</li><li><strong>GitHub Actions</strong>: plan on pull request, apply on merge behind an approval, authenticated with Workload Identity Federation. No JSON keys. Separate pipelines for lint, the execution-environment image and AWX configuration.</li><li><strong>AWX</strong>: job templates, a staged patching workflow, schedules, RBAC and notifications, all created from a YAML file in the repo.</li></ul><p>A one-glance picture of how the pieces connect:</p><pre>GitHub Repo --&gt; GitHub Actions --(OIDC)--&gt; GCP<br>                 |- terraform plan/apply (platform, awx, fleet, selfheal, ingress)<br>                 |- ansible-lint / molecule, execution-environment build<br>                 `- AWX config-as-code sync + job trigger<br>GKE (private) : AWX Operator -&gt; AWX  --&gt; Cloud SQL (PostgreSQL, private IP)<br>AWX --(IAP / SSH)--&gt; managed VM fleet (labelled web/app/db, dev/prod)<br>Audit log --&gt; Pub/Sub --&gt; in-cluster bridge --&gt; AWX (heal a stopped VM, onboard a new VM)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKA74DVzRqTug0-n.png" /></figure><h3>🧠 The concepts you need</h3><p><strong>AWX.</strong> The open-source upstream of Ansible Tower and Red Hat Automation Controller. It adds what a plain ansible-playbook command lacks: an inventory, credentials the operators never see, RBAC, schedules, approvals, job history and a REST API. Actions is the delivery pipeline; AWX is the operations plane.</p><p><strong>Workload Identity Federation.</strong> Lets an outside identity, here a GitHub Actions run, act as a GCP service account without a key. Trust is limited to this repository by an attribute condition.</p><p><strong>Workload Identity.</strong> The same idea for pods: AWX reads the Compute API as a read-only service account with no key file.</p><p><strong>Config as code.</strong> AWX settings kept in Git and applied by a playbook using the awx.awx collection, so the whole control plane is reproducible and reviewable.</p><p><strong>Dynamic inventory.</strong> Hosts and groups are built from VM labels ( env, role, patch_group), so the inventory is never edited by hand.</p><p><strong>Audit-log sink and Pub/Sub.</strong> A sink routes selected audit-log entries (a VM stopped, a VM created) to a Pub/Sub topic, which is the event bus.</p><p><strong>A pull bridge.</strong> A small pod in the cluster pulls events from Pub/Sub and calls the AWX API. Because it <em>pulls</em>, AWX needs no public URL.</p><p><strong>Execution environment.</strong> The container image every job runs in. Mine is built with ansible-builder, so jobs install nothing at run time.</p><p><strong>Idempotence.</strong> A second run changes nothing. It is how you prove a hardening role is safe to repeat.</p><p>And the plan I wrote down before touching anything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kAzJ1Ftl-mBLUhNy.png" /></figure><h3>🔄 Build order</h3><pre> bootstrap.sh ──► platform ──► awx ──► fleet ──► AWX config (awx-config)<br> (state bucket,    (VPC, GKE,   (operator,  (labelled   (credential, project,<br>  WIF, deployer)    Cloud SQL)   AWX)        VMs)        inventory, templates)<br>                                                │<br>                                                ▼<br>              selfheal ──► sinks + Pub/Sub + bridge ──► heal / onboard automatically<br>                                                │<br>                                                ▼<br>        lint + Molecule ──► CIS hardening ──► ee-build ──► ingress (optional) ──► alerts ✅</pre><p>Each phase needs the one before it, and each ended with a visible proof. Here is the whole build in one table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*guw1_nL6H17P_ufp.png" /></figure><h3>🔹 Phase 1: The platform foundation</h3><p>One bootstrap script, run once, creates the Terraform state bucket, a deployer service account and the Workload Identity Federation pool and provider. It prints four values that go into GitHub as repository variables: GCP_PROJECT_ID, GCP_WIF_PROVIDER, GCP_DEPLOYER_SA and TF_STATE_BUCKET. From that moment, GitHub Actions can apply Terraform with no secret stored anywhere.</p><p>The platform stack builds a VPC with Cloud NAT, firewall rules that allow only IAP and internal traffic, a <strong>private GKE cluster</strong> with Workload Identity, and <strong>Cloud SQL PostgreSQL 15 on a private IP only</strong>. The database password is generated by Terraform straight into Secret Manager. The awx stack then installs the AWX Operator with Helm and creates the AWX resource against the external database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Csljovze6-qP3xe.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VBVFtuxWdl9RjjQj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BSIOW5he6zk0PpVt.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AZ4C1YzIVTkM4PHi.png" /></figure><p>The pipeline that delivers all of this: validate, plan on every pull request, and apply on merge <strong>behind the </strong><strong>production environment approval</strong>, one matrix job per stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IDynuhCCcphFeg9.png" /></figure><p><strong>🔍 Key behaviors I found</strong></p><p><strong>Private cluster, public pipeline.</strong> Hosted GitHub runners must reach the cluster API, so the control-plane endpoint is public but locked to master_authorized_cidrs. In production I would use a self-hosted runner or the Connect Gateway and a fully private endpoint. I note this honestly as a lab trade-off.</p><p><strong>AWX never needs a public address.</strong> The pipeline gets cluster credentials, port-forwards to the AWX service, and talks to it locally.</p><h3>🔹 Phase 2: A fleet to manage, and AWX set up</h3><p>An operations platform with nothing to operate proves nothing, so the fleet stack creates six private Debian 12 VMs ( web-dev-01/02, app-dev-01, db-dev-01, web-prod-01, app-prod-01) with <strong>no public IP</strong>. Labels ( env, role, patch_group, ansible_managed) drive everything that follows. A startup script creates the ansible user.</p><p>The inventory needed a decision. My organisation policy blocked service account keys, so the usual “upload a JSON key to AWX” route was closed. I used Workload Identity instead: AWX’s service accounts impersonate a read-only awx-inventory account, and the google.cloud.gcp_compute inventory plugin builds groups from labels with no key file anywhere.</p><p>In AWX I created the machine credential fleet-ssh (stored encrypted), the project awx-ops-playbooks from Git, and the inventory gcp-fleet with a dynamic GCE source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*813boK9mpPA5-KUJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JsCoyIDfroG9lXF_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KdTwMH20aszZnyNd.png" /></figure><p>Then the first templates: 00 Connectivity check, 10 Health check and 20 Patch Linux (rolling).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISyhwQPfaS4_zCLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5rt6MazetsMlLBjX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CL_yK0RISJH3SFFk.png" /></figure><p><strong>🔍 Key behaviors I found</strong></p><p><strong>Only labelled VMs are managed.</strong> A VM without ansible_managed=true never enters the inventory and is never touched by self-healing. The GKE nodes are safe by construction.</p><p><strong>“Playbook not found.”</strong> The first template was created before the project had synced. The fix is an explicit project update that waits, before templates.</p><h3>🔹 Phase 4: Nothing is clicked into existence</h3><p>AWX is configured by a playbook using the awx.awx collection. Credentials, project, inventory, execution environment, templates, workflow, schedule, teams and notifications all live in awx_config.yml. A workflow called awx-config applies it on every merge and adopts anything I had built by hand, by name. If someone edits AWX in the UI, the next run puts it back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N3gTGbDYp4gIran9.png" /></figure><h3>🔹 Principle 2: keyless, private by default</h3><p>GitHub authenticates to GCP through OIDC. The AWX API is not on the internet, so the workflow gets cluster credentials, port-forwards to the AWX service, and talks to it locally. The VMs have no public IPs.</p><h3>🔹 Daily operations in practice</h3><p><strong>Self-service operations.</strong> A GitHub workflow, ops-trigger, lets me launch a template by name, with a limit and extra variables, and waits for the result. Jobs 29 and 35 were the first correct runs, after a bug I describe below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CJUA_45Wi4RqrRcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HT_eKBUjR8nAoFC8.png" /></figure><p><strong>Staged patching.</strong> Workflow 50 runs: pre-check, snapshot dev disks, patch dev, verify, then a human approval, then the same for prod. If dev breaks, prod is never touched. Patching is rolling, one host at a time, with a failure threshold of zero. The approval is a real AWX approval node, gated by an RBAC role that operators do not have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EMhPFDHdBYkwrqRk.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHx8zAwWI9sNtcJN.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HcMX3-KHahk_xRY-.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8WG34T-LMieSLek_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_UhJd_XVmrgEjMQU.png" /></figure><p>Note that there are two approvals: GitHub’s production environment decides whether the job may be launched, and AWX&#39;s approval node decides whether the workflow may continue to prod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x4M_WLazGw8PrGcI.png" /></figure><p><strong>Self-healing.</strong> I stop web-dev-02 on purpose. The Admin Activity audit log records it, a log sink forwards it to Pub/Sub, a small bridge running in the cluster pulls the message and calls the AWX API, and job 138 starts the VM again. About a minute, no human.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vgWXh3jromA44cdA.png" /></figure><p>Here is the event path in seven steps, so you can see where each safety check sits:</p><ol><li>Someone (or something) runs compute.instances.stop on a VM.</li><li>Cloud Audit Logs records an <strong>Admin Activity</strong> entry. These are on by default and free.</li><li>A <strong>log sink</strong> with a filter on compute.instances.stop and the fleet name regex routes the entry to a Pub/Sub topic. A second sink does the same for compute.instances.insert.</li><li>The <strong>bridge</strong>, a small Python pod using only the standard library, <strong>pulls</strong> the message from a subscription. It authenticates to Pub/Sub with Workload Identity.</li><li>The bridge reads the event type and the VM name, and checks the VM name against the fleet pattern.</li><li>It calls the AWX REST API as a user that can run only two templates: 40 Heal for a stop, 45 Onboard new VM for an insert, with the limit set to that single host.</li><li>Only after AWX accepts the launch does the bridge <strong>acknowledge</strong> the message. Server errors are retried and bad events are skipped.</li></ol><p>Pulling instead of pushing is the key design decision. A push-style webhook would need a public URL for AWX, a load balancer and a certificate. A pull bridge needs none of those, and it costs almost nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ctZtzlsgaQQVwvBF.png" /></figure><p>The design keeps this safe. The event scope is Admin Activity stop events on VMs matching the fleet name regex, one fixed template, a selfheal=off label to opt out, and an idempotent heal playbook (a running VM is a no-op). The bridge&#39;s AWX user can run only two templates, so compromising the bridge cannot reach production patching.</p><p><strong>New VMs configure themselves.</strong> I wanted a provisioning callback, the usual answer being an internal load balancer so a booting VM can call AWX. That is about $18 a month for a lab. Instead I added a second log sink for completed VM creations into the same topic. The bridge looks at the event type: a stop launches the heal job, a create launches “45 Onboard new VM”. I added one line for app-dev-02 to the Terraform fleet and merged it. About a minute after Terraform created the VM, job 146 started with the limit set to that single host, waited for SSH, applied the baseline and ran the connectivity and health checks. 16 tasks ok, none failed. The VM was 0.0 hours old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03-BccxZy5G50S7y.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jTpLIHFF55ToY7li.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*glvF-r61slIc5YiG.png" /></figure><p><strong>Separation of duties.</strong> Viewers look, operators run, approvers approve production. The auditor role is on the organization, execute rights are per template, and the approval role is only on the workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1MpcmOL78D52kVBY.png" /></figure><h3>🛡️ Quality gates and hardening</h3><p>Config as code is only as good as its checks, so every change to playbooks or roles runs through a lint workflow: ansible-lint on the strictest profile, then a Molecule test of each role in a real Debian 12 container with systemd. Molecule converges the role, runs it again to prove it changes nothing, and verifies the result.</p><p>The first role is a CIS-aligned baseline: an SSH drop-in (no root login, no passwords, limited tries, idle timeout), kernel network settings, blocked unused filesystems, permissions on sensitive files and a login banner. The SSH file is validated with sshd -t before it is installed, so a typo can never lock a host out. I ran the dry-run template first (job 153, check mode, four dev hosts, 6 changes each, no failures), then applied it, then ran the connectivity check to prove AWX could still log in, then applied it to prod (job 177). A final run across the whole fleet showed changed=0 on all six VMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NI0LVu7V66mGbtDd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UMU7K0lAx7xeHwhl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qeUR_2R9Ke70L_ti.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VZp-r9vWF_qm9iGL.png" /></figure><p>I also built a custom execution environment, the image every AWX job runs in: the AWX base image plus the Google libraries and collections, built by ansible-builder in its own workflow and pushed to a private Artifact Registry repository. The GKE nodes already have read access, so AWX pulls it with no stored credential. A small check template proves which image a job really runs in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pJwed1ARnlq6jO2G.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pyulTMDRVe-zAPBB.png" /></figure><h3>🔔 Alerts when something fails</h3><p>AWX notification templates send job failures, “approval needed” requests and, for chosen templates, successes to a chat webhook. They are only created when a secret is set, so the repository works without them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umxJoe9aDIJq4juE.png" /></figure><p>I tested it with a free Discord server, using its Slack-compatible webhook (add /slack to the URL). Two things surprised me:</p><ul><li><strong>The Test button lies.</strong> AWX’s test button sends a generic payload with no text field, so Discord rejects it and the badge says Failed. The real alerts carry text and work. The only honest test is a real job.</li><li><strong>Forcing a failure takes care.</strong> I launched the onboarding template for a VM that does not exist, and it still succeeded, twice. The check lives in a play on localhost, and my limit excluded it. A limit of localhost:web-dev-01 made it fail properly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z7647r61Q5lc5IvY.png" /></figure><p>After that, a red alert for the failed job and a green one for a connectivity check landed in the channel. The links said towerhost until I set AWX&#39;s URL base from the same domain variable the HTTPS entry uses. I deleted the webhook afterwards, because the URL had been in screenshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TBnJI398c2yFqngC.png" /></figure><h3>🚪 An optional front door</h3><p>By default I reach AWX through a port-forward. For demos I added an optional Terraform stack: a global load balancer, a Google-managed certificate and a Cloud Armor allowlist. It does nothing until you set a domain <em>and</em> at least one allowed address. A domain without an allowlist is refused, and 0.0.0.0/0 is refused. AWX can start and stop every server in the fleet, so its login page should not be open to the internet. Pipelines keep using the private tunnel.</p><p>I pointed awx.gcpcloudhub.in at the load balancer address in my DNS host, and about 80 minutes later the certificate went ACTIVE. The AWX login worked on the first try over HTTPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tlnkchpkZeeqN4Eo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cadUSnIbNYNTwjgL.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXbP3_Gzb8zMXnFm.png" /></figure><h3>🔬 Under the hood: four details worth showing</h3><p><strong>1. A conditional IAM binding, so AWX can start only fleet VMs.</strong> IAM conditions cannot use regex or contains, so the Terraform builds one endsWith clause per VM from the fleet map:</p><p>Add a VM to the fleet map and the condition grows with it. The GKE nodes can never match.</p><p><strong>2. The log sink filter.</strong> The sink only forwards the events the bridge cares about:</p><pre>protoPayload.serviceName=&quot;compute.googleapis.com&quot;<br>protoPayload.methodName:&quot;compute.instances.stop&quot;<br>protoPayload.resourceName=~&quot;/instances/&lt;fleet-name-regex&gt;$&quot;</pre><p><strong>3. Passing arguments to AWX safely.</strong> My first ops-trigger passed -e key=value, which Ansible splits on spaces. The fix builds JSON with jq:</p><pre>ARGS=&quot;$(jq -nc --arg t &quot;$TEMPLATE&quot; --arg l &quot;$LIMIT&quot; --arg e &quot;$EXTRA_VARS&quot; \<br>  &#39;{template: $t, limit: $l, launch_extra_vars: $e}&#39;)&quot;<br>ansible-playbook ansible/awx-config/launch.yml -e &quot;$ARGS&quot;</pre><p><strong>4. A hardening file that cannot lock you out.</strong> The cis role validates the SSH drop-in with sshd -t before Ansible installs it:</p><pre>- name: SSH daemon hardening drop-in (checked with sshd -t before it is installed)<br>  ansible.builtin.copy:<br>    dest: /etc/ssh/sshd_config.d/50-cis-hardening.conf<br>    content: |<br>      PermitRootLogin no<br>      PasswordAuthentication no<br>      MaxAuthTries {{ cis_ssh_max_auth_tries }}<br>    validate: /usr/sbin/sshd -t -f %s</pre><p>If the file is invalid, Ansible refuses to copy it. Add a dry-run template and a connectivity check after the real run, and hardening becomes a boring operation, which is exactly what you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iavqOnaLxcLv59sj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qpyTt3uaAHLU6OWI.png" /></figure><h3>🔧 What broke</h3><ol><li><strong>Launched the wrong template.</strong> My trigger passed -e template=10 Health check and Ansible split on the space, then treated a numeric-looking name as an AWX ID. It quietly ran job 23, a connectivity check. Fix: pass JSON arguments built with jq, and assert that the name is not numeric.</li><li><strong>“Playbook not found”.</strong> The template was created before the project had synced. Fix: an explicit project update that waits, before templates.</li><li><strong>A skipped task erased a variable.</strong> In the heal playbook, registering a result on a skipped task overwrote the earlier value. I found it with a mock server before it cost anything.</li><li><strong>IAM conditions are not a general language.</strong> I wanted “only these VMs” with matches, then contains. Neither is supported. Only ==, startsWith, endsWith and extract are. I generated endsWith clauses from the fleet variable instead.</li><li><strong>403s for a minute after a deploy.</strong> Pub/Sub IAM propagation. The bridge retried and recovered without duplicate launches.</li><li><strong>The linter died with “Could not determine home directory”.</strong> Not a lint problem: Microsoft Word’s temporary files (~$SS.docx) had been committed, and a file name starting with ~ breaks Python&#39;s path expansion. Fix: remove them and ignore ~*.</li><li><strong>Molecule failed on </strong><strong>sshd -t.</strong> Inside a test container sshd has never started, so its runtime directory does not exist. The role was fine; the test setup needed to create /run/sshd.</li><li><strong>A template that did not accept a limit.</strong> My launcher always passes one, and AWX refuses a limit on a template that does not allow it. A one-line change.</li></ol><p>The same list as a table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a_YUFXUg4vFwGIR6.png" /></figure><h3>🔐 Security recap</h3><ul><li><strong>No keys anywhere:</strong> Workload Identity Federation for CI, Workload Identity for pods.</li><li><strong>Nothing public by default:</strong> private GKE and database, VMs without public IPs, AWX through a tunnel.</li><li><strong>Least privilege:</strong> the bridge user runs two templates; conditional IAM lets AWX start and snapshot only fleet VMs.</li><li><strong>Separate duties:</strong> look, operate and approve are different teams.</li><li><strong>Secrets stay secret:</strong> a webhook URL is a password. Keep it as a GitHub secret, and delete test webhooks. I also checked every screenshot before publishing and removed a password, a private key and a personal IP.</li></ul><h3>🔭 What I would do next</h3><p>A self-hosted runner or Connect Gateway for a fully private control plane, identity-aware access instead of an IP allowlist, and more roles (user management, certificate checks) on the same pattern.</p><p>GKE nodes and Cloud SQL are the bill. The whole thing destroys in a handful of steps, in reverse order, and I wrote that down so it is a habit, not a hope.</p><h4><a href="https://github.com/bikram-singh/gcp-awx-ops-automation/tree/main/docs/snapshots">📸 Snapshots</a></h4><p>All screenshots from this build, sorted by phase, are in the repository under <a href="https://github.com/bikram-singh/gcp-awx-ops-automation/tree/main/docs/snapshots">docs/snapshots/</a>, with a caption for each in docs/SNAPSHOTS.md.</p><h3>🎬 The demo, minute by minute</h3><p>When I present this, the story is one sentence: <em>servers are easy to build and hard to operate, so I built the platform that runs the operations. Terraform builds it, GitHub Actions delivers it with no stored keys, and AWX runs patching, health checks, snapshots and self-healing with approvals and audit.</em> The run of show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJF0Uo4a4Jn05yQv.png" /></figure><p>For a ten-minute slot I skip the live provisioning merge and the HTTPS page. The strongest moment is always the self-healing one: stop a VM on purpose, watch the AWX Jobs page, and see it running again in about a minute with nobody touching anything.</p><h3>🎯 Wrapping up</h3><p>The mental model is simple: Terraform builds, Actions delivers, AWX operates, and events let the platform fix the boring incidents itself. In practice the hard part was never one tool; it was the <strong>seams</strong> between them: keyless identity, an AWX nobody can reach from the internet, an event path with no inbound hole, and tests that prove each safety claim. Once those held, adding a new operation is just one more template in a YAML file.</p><p>If you run servers, try building the operations plane the way you build the servers. Do it in a throwaway project first.</p><h3>🔗 Repository</h3><p>🌐 <strong>gcp-awx-ops-automation</strong>: <a href="https://github.com/bikram-singh/gcp-awx-ops-automation">https://github.com/bikram-singh/gcp-awx-ops-automation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d04193ef01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCP Cloud KMS Explained With Real Demos]]></title>
            <link>https://medium.com/@bikram23march/gcp-cloud-kms-explained-with-real-demos-af4d20aa5168?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/af4d20aa5168</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 11:53:37 GMT</pubDate>
            <atom:updated>2026-10-21T11:53:37.593Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>GCP · Cloud KMS · Encryption · CMEK · Digital Signatures · MAC · Cloud Security</strong></p><p>A practical walkthrough of Google Cloud KMS, built from scratch and proved with real commands: symmetric encryption, key rotation and key versions, a Cloud Storage bucket protected with a customer-managed key, what happens when you disable that key, asymmetric encryption, digital signatures and MAC signatures. Every step is backed by screenshots from the GCP Console and Cloud Shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mrGnODhqT6sDKwoB.png" /></figure><h3>📖 Introduction</h3><p>Google already encrypts your data at rest by default, and you never touch those keys. That is enough for many workloads. Sooner or later, though, a security review asks the same question: <em>who controls the encryption keys?</em></p><p>Cloud KMS is the answer. It lets you create and manage your own keys, decide who can use them, rotate them on a schedule, and switch them off. It powers customer-managed encryption keys (CMEK) for Cloud Storage, BigQuery, Cloud SQL and more. You can also call it directly to encrypt data, sign files and verify integrity.</p><p>KMS keys come in four flavours, and the docs describe them separately. I wanted to see them side by side, so I built one lab that uses all four, including the failures: the wrong key version, a disabled key, a tampered file. This article is that build, step by step.</p><h4>🔑 Key Facts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7QwHLPyj152Hiwlk.png" /></figure><h4>✨ What Makes This Different</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3JrR0V_imx4PzHk4.png" /></figure><h4>💡 Why customer-managed keys: the benefits, mapped to what I built</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FR_Iqrgq8tms0Jlp.png" /></figure><h4>🏛️ Architecture</h4><pre>                   Project (Cloud KMS API enabled) · us-central1<br>  ┌────────────────────────────────────────────────────────────────────────┐<br>  │ Key ring: test-ring                                                    │<br>  │                                                                        │<br>  │  🔑 symmetric-key           Symmetric encrypt/decrypt · 90-day rotation │<br>  │       ├── gcloud kms encrypt / decrypt   (Cloud Shell)                 │<br>  │       └── CMEK ──► Cloud Storage bucket: cloud-kms-demo-bucket         │<br>  │                                                                        │<br>  │  🔐 asymmetric-key-decrypt  RSA 3072 · OAEP · SHA-256                  │<br>  │       ├── public key ──► openssl encrypt  (local, no KMS call)         │<br>  │       └── private key stays in KMS ──► gcloud kms asymmetric-decrypt   │<br>  │                                                                        │<br>  │  ✍️ asymmetric-sign         EC P-256 · SHA-256                         │<br>  │       ├── gcloud kms asymmetric-sign    (private key, in KMS)          │<br>  │       └── public key ──► openssl dgst -verify  (anyone can verify)     │<br>  │                                                                        │<br>  │  🧾 mac-key                 HMAC · SHA-256  (symmetric, no public key) │<br>  │       └── gcloud kms mac-sign / mac-verify                             │<br>  └────────────────────────────────────────────────────────────────────────┘</pre><p>Four keys, four different jobs. Here is how they compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXJfUSGdWf7GEuXp.png" /></figure><h4>🧠 The concepts you need (five minutes of theory)</h4><p><strong>Key ring.</strong> A group of keys in one location. It cannot be deleted, so name it deliberately.</p><p><strong>Key and key version.</strong> A key is a named object with a purpose and one or more versions. The version holds the actual key material, and is enabled, disabled, scheduled for destruction or destroyed.</p><p><strong>Purpose.</strong> Chosen when you create the key and never changed. It decides which operations the key supports: symmetric encrypt/decrypt, asymmetric decrypt, asymmetric sign or MAC.</p><p><strong>Primary version.</strong> A symmetric key has one primary version, which is used for new encryption. <strong>Asymmetric keys have no primary version</strong>, so every operation must name the version.</p><p><strong>CMEK.</strong> Customer-managed encryption keys: your KMS key used by a Google Cloud service to protect your data. The service reaches the key through its own service agent, which needs permission.</p><p><strong>Rotation.</strong> Creates a new version for new data. It does <strong>not</strong> re-encrypt old data.</p><p><strong>Symmetric vs asymmetric.</strong> Symmetric uses one shared secret for both directions. Asymmetric uses a public/private pair: the public key can be shared freely, and the private key never leaves KMS. A MAC is symmetric too, which becomes important in Part 9.</p><p><strong>Protection levels.</strong> Software (what I used), HSM for FIPS 140–2 Level 3 hardware, and External for keys held in your own external key manager.</p><h3>🔄 Build order</h3><pre>Enable API ──► Key ring ──► Symmetric key ──► Encrypt / Decrypt ──► Rotate<br>                                  │<br>                                  ▼<br>                 CMEK bucket (same location + service-agent role)<br>                                  │<br>                                  ▼<br>                   Disable key ──► data unreadable ──► re-enable<br>                                  │<br>                                  ▼<br> Asymmetric key ──► public key ──► openssl encrypt ──► KMS decrypt (by version)<br>                                  │<br>                                  ▼<br>     Signing key ──► sign in KMS ──► verify with openssl ──► tamper ──► fails<br>                                  │<br>                                  ▼<br>                MAC key ──► mac-sign ──► mac-verify ──► alter ──► fails ✅</pre><h4>🔹 Part 1: Enable the API and create the key ring</h4><p>I used a free-trial project and Cloud Shell for every command. First, enable the Cloud KMS API, either from the Marketplace page or with gcloud services enable cloudkms.googleapis.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U6jQDWbUcoG7q_cg.png" /></figure><p>Then, under <strong>Security → Key Management</strong>, create the key ring test-ring in us-central1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cntg0OuRe1JBS-ZK.png" /></figure><p>🔍 <strong>Key behavior I found.</strong> The key ring is tied to its location and cannot be deleted later. Pick the name and the location on purpose.</p><h4>🔹 Part 2: The symmetric key</h4><p>Inside test-ring, I created a key with these settings:</p><ul><li>Name: symmetric-key</li><li>Protection level: Software (HSM and External are the other choices)</li><li>Key material: Generated</li><li>Purpose: Symmetric encrypt/decrypt</li><li>Rotation: every 90 days</li><li>Scheduled destruction: 10 days</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJ9CR64p2eooPYln.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OK9MBC7l4lUmRcNa.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ChC-Esugyh_mKRNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Keg7TI2Pzti07kIn.png" /></figure><p>The result is a key that shows as <strong>Available</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h1AEmDWjzPDMLV25.png" /></figure><p>Equivalent CLI, for reference (I used the console for the build, so check the flags against --help before relying on them):</p><pre>gcloud kms keyrings create test-ring --location us-central1<br><br>gcloud kms keys create symmetric-key \<br>  --keyring test-ring --location us-central1 \<br>  --purpose encryption \<br>  --rotation-period 90d \<br>  --next-rotation-time &quot;$(date -u -d &#39;+90 days&#39; +%Y-%m-%dT%H:%M:%SZ)&quot; \<br>  --destroy-scheduled-duration 10d</pre><h4>🔍 Key behaviors I found</h4><p><strong>The destruction delay is your safety net</strong>. When a key version is destroyed it waits in <em>scheduled for destruction</em> for that many days, and you can still restore it. I shortened it to 10 days for the demo. Think twice before doing that in production.</p><p><strong>Choosing External changes the form.</strong> Picking External as the protection level asks for an EKM connection type (via internet or via VPC), because the key lives in a key manager you run. That needs setup I did not do here.</p><h4>🔹 Part 3: Encrypt and decrypt</h4><p>In Cloud Shell, I created a test file and encrypted it:</p><pre>mkdir -p ~/KMS-demo &amp;&amp; cd ~/KMS-demo<br>echo &quot;Welcome to Cloud KMS Demo&quot; &gt; test.txt<br><br>gcloud kms encrypt \<br>  --key symmetric-key --keyring test-ring --location us-central1 \<br>  --plaintext-file test.txt --ciphertext-file encrypt.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B7oYrKiZaB2ls8xY.png" /></figure><p>Decrypting returns the original text:</p><pre>gcloud kms decrypt \<br>  --key symmetric-key --keyring test-ring --location us-central1 \<br>  --ciphertext-file encrypt.txt --plaintext-file decrypt.txt<br><br>cat decrypt.txt<br># Welcome to Cloud KMS Demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*psQ00jZR6IBnlMsZ.png" /></figure><p>🔍 <strong>Key behavior I found.</strong> I never passed a key version. KMS reads it from the ciphertext when decrypting, and uses the primary version when encrypting. That matters in the next part.</p><p>Rotation creates a new key version and makes it primary, so new data uses fresh key material. On the key’s <strong>Versions</strong> tab, click <strong>Rotate key</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wggRe7sHN2j52Cd4.png" /></figure><p>After rotating, version 2 is <strong>Enabled &amp; primary</strong> and version 1 stays <strong>Enabled</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*00uh2Js-nkj91zBU.png" /></figure><p>Now the real test. encrypt.txt was created with version 1. I decrypted it again after rotation:</p><pre>gcloud kms decrypt \<br>  --key symmetric-key --keyring test-ring --location us-central1 \<br>  --ciphertext-file encrypt.txt --plaintext-file decrypt-2.txt<br><br>cat decrypt-2.txt<br># Welcome to Cloud KMS Demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*CqjAsBma_mrNUcs8.png" /></figure><p>🔍 <strong>Key behaviors I found</strong></p><p><strong>Rotation does not re-encrypt old data.</strong> The dialog says it plainly: older versions can still decrypt, and data encrypted with them is not re-encrypted unless you do it yourself. Rotation is about what <em>new</em> data uses.</p><p><strong>Primary only controls new encryption.</strong> You can open any enabled version’s menu and choose <em>Make primary version</em>. It changes which version new encryption uses, and nothing else.</p><h4>🔹 Part 5: CMEK on a Cloud Storage bucket</h4><p>This is the real use case. I created cloud-kms-demo-bucket and, under <strong>Data encryption</strong>, chose <strong>Cloud KMS key</strong>, then picked symmetric-key.</p><p><strong>Gotcha 1: location.</strong> My key is in us-central1. When I first tried a bucket in us-east1, the key picker said <em>No valid keys found</em>, with the filter showing the purpose and the location. A CMEK key must be in the same location as the resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ViKEZ_W3GBSphEO_.png" /></figure><p><strong>Gotcha 2: the service agent.</strong> With the right region and key selected, the console warned that the Cloud Storage service agent did not have the cloudkms.cryptoKeyEncrypterDecrypter role on the key. I clicked <strong>Grant</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7PQUE9mx4xe2-x3U.png" /></figure><p>Once the bucket was created, the <strong>Protection</strong> section showed <em>Customer-managed</em>, with a link to the key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*srpRmL86GXzwQ0XC.png" /></figure><p>I uploaded two objects, and each one reported its own key version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJiAEv6oUgKChXP1.png" /></figure><p>🔍 <strong>Key behaviors I found</strong></p><p><strong>A missing service-agent grant is the most common CMEK failure.</strong> The console flags it with a <strong>Grant</strong> button, so read that warning before you click Create.</p><p><strong>Object details show the exact key version.</strong> The object was encrypted with cryptoKeyVersions/2, the primary version at upload time. So the version you rotate to is the version your data actually uses.</p><h4>🔹 Part 6: The kill switch</h4><p>This is why people choose CMEK. I disabled both key versions on the <strong>Versions</strong> tab, and the key status flipped to <strong>Not available</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41DanhlvAkS93QLU.png" /></figure><p>Encrypting from the CLI now failed with FAILED_PRECONDITION, because the key version is DISABLED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nm4IntHW3CIdpELS.png" /></figure><p>And opening the object in the bucket returned this:</p><blockquote><em>Cloud KMS key is disabled, destroyed, or scheduled to be destroyed.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7FR01VRLK96lan_H.png" /></figure><p>🔍 <strong>Key behavior I found.</strong> Disabling is reversible: enable the versions again and access returns. Destroying is not, once the scheduled delay passes. Treat key disable and destroy events as alert-worthy.</p><h4>🔹 Part 7: Asymmetric encryption</h4><p>With asymmetric keys there is a <strong>key pair</strong>. The public key encrypts and can be shared with anyone. The private key decrypts and never leaves KMS.</p><p>I created asymmetric-key-decrypt with purpose <strong>Asymmetric decrypt</strong> and algorithm <strong>3072 bit RSA - OAEP Padding - SHA256 Digest</strong>. The console states that automatic rotation is not available for asymmetric keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dbQ-w8oGBQ3QqsiQ.png" /></figure><p>To encrypt, you first need the public key. On the <strong>Versions</strong> tab, open the action menu and choose <strong>Get public key</strong>, then download it. The CLI does the same:</p><pre>gcloud kms keys versions get-public-key 1 \<br>  --key asymmetric-key-decrypt --keyring test-ring --location us-central1 \<br>  --output-file test-ring-asymmetric-key-decrypt-1.pub</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pYoVrTFmD7ha4H8c.png" /></figure><p>Encryption happens locally with OpenSSL. KMS is not involved at all, which is the point:</p><pre>openssl pkeyutl -in test.txt -encrypt -pubin \<br>  -inkey test-ring-asymmetric-key-decrypt-1.pub \<br>  -pkeyopt rsa_padding_mode:oaep \<br>  -pkeyopt rsa_oaep_md:sha256 \<br>  -pkeyopt rsa_mgf1_md:sha256 \<br>  &gt; encrypt.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S4wzbscfCFp9d4sZ.png" /></figure><p>Decryption has to go through KMS. Because there is no primary version, I must say which one:</p><pre>gcloud kms asymmetric-decrypt \<br>  --version 1 \<br>  --key asymmetric-key-decrypt --keyring test-ring --location us-central1 \<br>  --ciphertext-file encrypt.txt --plaintext-file decrypt.txt</pre><p>To see why that matters, I created a second version of the key. Both versions are enabled, and neither is labelled primary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x6oa4FCakERvW6RD.png" /></figure><p>encrypt.txt was encrypted with the version 1 public key. Decrypting with --version 2 failed:</p><pre>ERROR: (gcloud.kms.asymmetric-decrypt) INVALID_ARGUMENT: Decryption failed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9EtVWkniOUZrpj4e.png" /></figure><p>Switching back to --version 1 worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7i24TXdvcdmD07sS.png" /></figure><p>🔍 <strong>Key behaviors I found</strong></p><p><strong>Asymmetric ciphertext is bound to a version.</strong> It only decrypts with the key pair whose public key encrypted it. Store the key version next to the ciphertext.</p><p><strong>The OpenSSL options must match the key.</strong> OAEP with SHA-256 for both the digest and the MGF1 function, to match the algorithm I chose when creating the key.</p><h4>🔹 Part 8: Digital signatures</h4><p>A digital signature answers two questions: <em>who produced this?</em> and <em>was it changed?</em> The signer uses the private key inside KMS. Anyone with the public key can verify.</p><p>I created asymmetric-sign with purpose <strong>Asymmetric sign</strong> and algorithm <strong>Elliptic Curve P-256 - SHA256 Digest</strong>, then downloaded its public key the same way as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h-r2f88R2nyloYcL.png" /></figure><p>Sign in KMS, verify anywhere with OpenSSL:</p><pre>gcloud kms asymmetric-sign \<br>  --version 1 \<br>  --key asymmetric-sign --keyring test-ring --location us-central1 \<br>  --digest-algorithm sha256 \<br>  --input-file test.txt --signature-file sign.txt<br><br>openssl dgst -sha256 \<br>  -verify test-ring-asymmetric-sign-1.pub \<br>  -signature sign.txt test.txt</pre><p>The output is Verified OK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9rFloK0V8loACmtr.png" /></figure><p>Then I appended one line to test.txt and ran the same verify command:</p><pre>Verification failure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VW5Faw5WiZ3XwRS2.png" /></figure><p>🔍 <strong>Key behavior I found.</strong> In practice, you publish the file, the signature and your public key. Anyone can then check that the file is yours and unmodified. The same pattern secures binaries, container images and tokens.</p><p>A MAC gives you integrity and authenticity too, but with a <strong>shared secret</strong> instead of a key pair. Both sender and receiver call KMS with the same key.</p><p>I created mac-key with purpose <strong>MAC signing/verification</strong> and algorithm <strong>HMAC - SHA256 Digest</strong>. Then I looked at the version&#39;s action menu: <em>Disable</em>, <em>Destroy</em> and <em>Copy resource name</em>, but no <em>Get public key</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DQgUncjJg7BvhgWH.png" /></figure><p>Signing and verifying:</p><pre>gcloud kms mac-sign \<br>  --version 1 \<br>  --key mac-key --keyring test-ring --location us-central1 \<br>  --input-file mac-sign --signature-file mac.txt<br><br>gcloud kms mac-verify \<br>  --version 1 \<br>  --key mac-key --keyring test-ring --location us-central1 \<br>  --input-file mac-sign --signature-file mac.txt</pre><p>The verify command printed True.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vc5My32ExuNrsVg2.png" /></figure><p>After I edited the file and verified again, the result was no longer True (the CLI printed None), so the change was caught.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gdmoNCFDPrcTr-Wf.png" /></figure><p>🔍 <strong>Key behaviors I found</strong></p><p><strong>A MAC key has no public key.</strong> It is symmetric, so there is nothing to publish. That is the practical difference from a digital signature: only parties who can call KMS with that key can create or verify the tag.</p><p><strong>Two ways to prove a file was not altered.</strong> Share the MAC tag and let the other side verify it, or regenerate the file from the same source and run diff. The second only works when you can reproduce the file.</p><h4>🧭 Which key purpose should you use?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*55mNXAU3q3o21VVZ.png" /></figure><h4>🧾 Cheat sheet: gotchas worth remembering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1N_hweRTLP-L4ZpR.png" /></figure><h4>🕵️ Observations from the build</h4><p>These came up while building it, not from the docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HAD7p8tF8B0Zi601.png" /></figure><h4>🔒 Security habits worth adopting</h4><ul><li>🧑‍⚖️ <strong>Separate duties:</strong> cloudkms.admin manages keys but cannot use them. cloudkms.cryptoKeyEncrypterDecrypter uses them but cannot manage them.</li><li>🏗️ <strong>Use a dedicated KMS project</strong> for key rings, apart from your workloads.</li><li>📜 <strong>Turn on Data Access audit logs</strong> for Cloud KMS to see every encrypt and decrypt call.</li><li>🚨 <strong>Alert on key disable and destroy events.</strong></li><li>⏳ <strong>Keep a destruction delay</strong> long enough to recover from mistakes.</li></ul><h4>💰 Cost and cleanup</h4><p>Keys are not free to leave around. Active key versions are billed, and so are key operations and the bucket. Check the official <a href="https://cloud.google.com/kms/pricing">Cloud KMS pricing page</a> before leaving a lab like this up.</p><p>To clean up:</p><ul><li>Delete the demo bucket and its objects: gsutil rm -r gs://cloud-kms-demo-bucket</li><li>Destroy the key versions you no longer need</li><li>Remove the local files: rm -rf ~/KMS-demo</li></ul><p>Key rings and keys stay in the project afterwards. Only their versions are destroyed.</p><h4>🔐 A note on secrets</h4><p>The screenshots show the demo project, so replace the project ID with your own if you follow along. Use throwaway files such as test.txt, and never commit keys, ciphertext or real secrets. If you publish a build like this, blur anything sensitive in your screenshots, such as project IDs, organization IDs and email addresses.</p><h4><a href="https://github.com/bikram-singh/gcp-cloud-kms-encryption/tree/main/docs/snapshots">📸 Snapshots</a></h4><p>All screenshots from this build, sorted by step, are in the repository under <a href="https://github.com/bikram-singh/gcp-cloud-kms-encryption/tree/main/docs/snapshots">docs/snapshots/</a>.</p><h4>🎯 Wrapping up</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zaHiM6kqTEQN3fsw.png" /></figure><p>The mental model is simple: pick the purpose first, then everything else follows. Symmetric keys encrypt and power CMEK. Asymmetric keys encrypt for outsiders and sign for everyone. MAC keys check integrity between trusted parties. The hard part is rarely a single command. It is the details around them: the key location, the service-agent permission, the key version you must remember, and what disabling a key does to your data.</p><p>Natural next steps:</p><ul><li><strong>Terraform it.</strong> The console is great for learning, and production needs repeatability.</li><li><strong>Enforce CMEK.</strong> Use organization policies to require customer-managed keys for chosen services.</li><li><strong>Try HSM or External keys</strong> if your compliance needs call for hardware or your own key manager.</li><li><strong>Automate key creation</strong> with Cloud KMS Autokey so developers are not waiting on a security team.</li></ul><p>If you are working with Cloud KMS, give this a try in a throwaway project before it goes near production.</p><h3>🔗 Repository</h3><p>🔑 <strong>gcp-cloud-kms-encryption:</strong> <a href="https://github.com/bikram-singh/gcp-cloud-kms-encryption">https://github.com/bikram-singh/gcp-cloud-kms-encryption</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af4d20aa5168" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting GCP and Azure with an Active-Active HA VPN and BGP]]></title>
            <link>https://medium.com/@bikram23march/connecting-gcp-and-azure-with-an-active-active-ha-vpn-and-bgp-f4f662a77f0a?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f662a77f0a</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 08:19:04 GMT</pubDate>
            <atom:updated>2026-10-21T08:19:04.853Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>GCP · Azure · Multicloud · HA VPN · BGP · Cloud Router · VPN Gateway</strong></p><p><em>A practical walkthrough of a highly available site-to-site VPN between Google Cloud and Azure: GCP HA VPN with Cloud Router on one side, an Azure VPN gateway in active-active mode on the other, two IPsec/IKEv2 tunnels, and two BGP sessions over APIPA addresses. Built from scratch and proved with a private-IP ping.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ZRMcO_Qnslyo8TK.png" /></figure><h4>❓ Why HA VPN + BGP?</h4><p>Sooner or later a workload in Google Cloud needs to talk privately to something in Azure: a database, a legacy app, a data platform. The fastest and cheapest way to give them private connectivity is a site-to-site IPsec VPN over the internet.</p><p>A single tunnel works, but it is a single point of failure: one gateway reboot, one maintenance window, one flapping path, and the link is gone. Static routes make it worse, because someone has to edit routes on both clouds every time a network changes.</p><p>The fix has two parts:</p><ul><li><strong>Two of everything.</strong> GCP’s HA VPN gateway has two interfaces. Azure’s VPN gateway can run in active-active mode, with two instances that are both live. Connect them pairwise and you get two independent tunnels.</li><li><strong>BGP instead of static routes.</strong> Each side advertises its networks dynamically. When a tunnel dies, its routes are withdrawn and traffic moves to the surviving tunnel on its own.</li></ul><p>I built this end to end across both clouds, using only the consoles, to see exactly how the pieces fit together, including the order you have to do them in. This article is that build, step by step.</p><h4>🔑 Key Facts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZaFJVgumhUy7KcHJ.png" /></figure><h4>✨ What Makes This Different</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hvp01zZVKg0zQIs-.png" /></figure><h4>💡 Why HA VPN + BGP: the benefits, mapped to what I built</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vzvzs4qlkrcpEfmU.png" /></figure><h4>🏛️ Architecture</h4><pre>            GCP (us-east1)                                  Azure (East US)<br>  ┌─────────────────────────────┐                 ┌──────────────────────────────────────┐<br>  │ VPC: gcp-azure-vpc          │                 │ VNet: gcp_azure_net  192.168.0.0/16  │<br>  │ 10.10.0.0/20                │                 │  ├─ gcp_azure_east-us 192.168.0.0/24 │<br>  │  └─ gcp-vm   10.10.0.2      │                 │  │    └─ azure-vm  192.168.0.4       │<br>  │                             │                 │  └─ GatewaySubnet 192.168.2.0/27     │<br>  │ HA VPN GW: gcp-to-azure-vpn │                 │                                      │<br>  │  if0 34.152.79.70 ──────────┼── Tunnel 1 ─────┼── 4.156.244.86     (VNG instance 1)  │<br>  │  if1 34.177.46.16 ──────────┼── Tunnel 2 ─────┼── 135.234.206.228  (VNG instance 2)  │<br>  │                             │   IPsec/IKEv2   │ VNG: active-active, VpnGw2AZ         │<br>  │ Cloud Router  ASN 65001     │◄──── BGP ──────►│ BGP ASN 65002                        │<br>  │  169.254.21.1 / 169.254.22.1│  (APIPA /30s)   │  169.254.21.2 / 169.254.22.2         │<br>  └─────────────────────────────┘                 └──────────────────────────────────────┘</pre><p>Two tunnels, two BGP sessions, one private ping at the end. Here is the exact mapping I used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sCtUOng1CQjUbFTC.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8lgxL2jHjeAR_U9n.png" /></figure><h4>🧠 The concepts you need (five minutes of theory)</h4><p><strong>Site-to-site IPsec VPN.</strong> An encrypted tunnel over the internet between two networks. Each end needs a public IP, an agreed IKE version (I used <strong>IKEv2</strong>) and a pre-shared key.</p><p><strong>GCP HA VPN.</strong> A regional Cloud VPN gateway with <strong>two interfaces</strong>, each with its own public IP. With two tunnels over the two interfaces you get Google’s 99.99% availability design. HA VPN supports <strong>dynamic routing (BGP) only</strong>, so BGP is not optional.</p><p><strong>Cloud Router.</strong> The BGP speaker on the GCP side. It learns Azure’s prefixes and advertises the VPC subnets. It has its own ASN, 65001 in this build.</p><p><strong>Azure VPN gateway in active-active mode.</strong> A normal Azure VPN gateway is one active instance plus one standby. In active-active mode <strong>both instances are live</strong>, each with its own public IP. That maps one-to-one onto the two HA VPN interfaces: tunnel 1 lands on Azure instance 1, tunnel 2 on instance 2.</p><p><strong>Local Network Gateway (LNG).</strong> Azure’s way of describing the <em>other</em> side: its public IP, its BGP ASN and its BGP peer IP. GCP has two interfaces, so you need <strong>two LNGs</strong>.</p><p><strong>BGP and APIPA.</strong> The two BGP peers talk over link-local <strong>APIPA</strong> addresses ( 169.254.x.x). Azure only accepts 169.254.21.0 to 169.254.22.255 for this, which is why I used 169.254.21.x for tunnel 1 and 169.254.22.x for tunnel 2.</p><p><strong>ASNs.</strong> It is eBGP, so each side needs a <em>different</em> private ASN: 65001 for GCP, 65002 for Azure.</p><p>And the plan I would write down <em>before</em> clicking anything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ye0cO0r8zuWtuL_p.png" /></figure><p>One golden rule: <strong>the private ranges on both sides must not overlap.</strong> Here that is 10.10.0.0/20 against 192.168.0.0/16.</p><h4>🔄 The build order (this matters)</h4><pre> Azure RG / VNet / VM ──► GCP VPC / VM ──► Baseline ping (fails) ──► Azure public IPs<br>        │<br>        ▼<br> GCP HA VPN gateway + Cloud Router + 2 tunnels   (BGP &quot;later&quot;)<br>        │<br>        ▼<br> Azure VNG (active-active, BGP, APIPA) ──► 2 Local Network Gateways ──► 2 Connections<br>        │<br>        ▼<br> GCP BGP sessions (manual APIPA) ──► Tunnels Established ──► Ping succeeds ✅</pre><p>The order exists because of a chicken-and-egg problem: GCP needs Azure’s public IPs, and Azure needs GCP’s public IPs, ASN and BGP addresses. Creating the two Azure public IPs first breaks the loop.</p><h4>🔹 Part 1: The Azure foundation</h4><p>Everything on the Azure side lives in one resource group, gcp_azure, in East US.</p><p>Then the network: a VNet gcp_azure_net with address space 192.168.0.0/16 and a workload subnet gcp_azure_east-us on 192.168.0.0/24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HywGE8uwOWW9IMXK.png" /></figure><p>The VPN gateway needs a subnet of its own, and <strong>it must be named </strong><strong>GatewaySubnet</strong>. In the portal you get the name for free by choosing <em>Virtual Network Gateway</em> as the subnet purpose. I used a /27 ( 192.168.2.0/27), which is the minimum Microsoft recommends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z9J4NB1s60xsRivZ.png" /></figure><p>Last, a small Ubuntu 24.04 VM ( azure-vm, size B1s) in the workload subnet. It got the private IP . That VM is our test target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kCgVtxt4L4V15mUz.png" /></figure><h4>🔹 Part 2: The GCP foundation, and a ping that must fail</h4><p>On GCP I created a custom-mode VPC gcp-azure-vpc with one subnet, subnet-east-us in us-east1 on 10.10.0.0/20, and a VM gcp-vm that got .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3TROjrCvUfXlhXbk.png" /></figure><p>Before building any VPN I tested the “before” state: ping the Azure VM from the GCP VM and the GCP VM from Azure, using private IPs. Both hang with no replies, which is exactly what you would expect, because the two private networks have no path between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qyDELSMgjKxtz_z0.png" /></figure><p>Capturing the failure first makes the success at the end mean something.</p><h4>🔹 Part 3: Two public IPs for the Azure gateway</h4><p>An active-active Azure gateway needs <strong>two</strong> public IPs, both Standard SKU and regional. I created gcp_azure_vpn_ip1 ( 4.156.244.86) and gcp_azure_vpn_ip2 ( 135.234.206.228) up front, so I could hand them to GCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBPtLpg8m4GTnhWn.png" /></figure><h4>🔹 Part 4: The GCP side: HA VPN gateway, Cloud Router and tunnels</h4><p>In <strong>Network Connectivity → VPN → Create VPN connection</strong> you choose between Classic VPN and HA VPN. HA VPN is the one with dynamic routing and the availability SLA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQlrCEhdBscqGz-d.png" /></figure><p>The sequence:</p><ol><li><strong>Create the gateway</strong> gcp-to-azure-vpn in gcp-azure-vpc, us-east1, IPv4. Google allocates two public IPs: 34.152.79.70 (interface 0) and 34.177.46.16 (interface 1).</li><li><strong>Create a peer VPN gateway</strong> gcp-to-azure-vpn-gateway with <strong>two interfaces</strong>, entering the two Azure public IPs.</li><li><strong>Create a Cloud Router</strong> gcp-to-azure-vpn-router with ASN <strong>65001</strong>.</li><li><strong>Create two tunnels</strong> with IKEv2 and the same pre-shared key: interface 0 to Azure IP 1, interface 1 to Azure IP 2.</li><li><strong>Defer BGP.</strong> At the BGP step I chose <em>Configure BGP sessions later</em>, because the Azure APIPA addresses and ASN did not exist yet.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S4j0ryVqX63cxmHE.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m_g5avG9CqwVG3gf.png" /></figure><p>Equivalent CLI, for reference (I used the console for the build, so check the flags against --help before relying on them):</p><pre># HA VPN gateway: two interfaces, two public IPs allocated by Google<br>gcloud compute vpn-gateways create gcp-to-azure-vpn \<br>  --network=gcp-azure-vpc --region=us-east1<br><br># Peer gateway: the two Azure public IPs<br>gcloud compute external-vpn-gateways create gcp-to-azure-vpn-gateway \<br>  --interfaces=0=4.156.244.86,1=135.234.206.228<br><br># Cloud Router with Google&#39;s ASN<br>gcloud compute routers create gcp-to-azure-vpn-router \<br>  --network=gcp-azure-vpc --region=us-east1 --asn=65001<br><br># Tunnel 1 (repeat with interface 1 / peer interface 1 for tunnel 2)<br>gcloud compute vpn-tunnels create gcp-to-azure-vpn-tunnel-1 \<br>  --region=us-east1 --vpn-gateway=gcp-to-azure-vpn --interface=0 \<br>  --peer-external-gateway=gcp-to-azure-vpn-gateway \<br>  --peer-external-gateway-interface=0 \<br>  --ike-version=2 --shared-secret=&quot;$PSK&quot; \<br>  --router=gcp-to-azure-vpn-router</pre><h4>🔍 Key behaviors I found</h4><p><strong>The tunnels cannot finish yet, and that is fine.</strong> Right after creation both tunnels sit in <strong>First handshake</strong>, with BGP showing as not configured. Nothing is wrong: the Azure side does not exist, so there is nobody to complete the handshake with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5S3atC9fFBJj9GNn.png" /></figure><p><strong>The pre-shared key is shown once.</strong> GCP warns that the key can’t be retrieved after the form is closed. Generate a long random key ( openssl rand -base64 32), store it somewhere safe, and use the same value on both Azure connections.</p><h4>🔹 Part 5: The Azure active-active VPN gateway</h4><p>On the Azure side, create a <strong>Virtual network gateway</strong>:</p><ul><li>Type <strong>VPN</strong>, SKU <strong>VpnGw2AZ</strong>, <strong>Generation 2</strong>, in gcp_azure_net (it picks up GatewaySubnet)</li><li><strong>Public IP address:</strong> use existing, gcp_azure_vpn_ip1</li><li><strong>Enable active-active mode:</strong> on, with gcp_azure_vpn_ip2 as the second public IP</li><li><strong>Configure BGP:</strong> enabled, ASN <strong>65002</strong></li><li><strong>Custom Azure APIPA BGP IP addresses:</strong> 169.254.21.2 and 169.254.22.2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*itjaiL0FPxQSDsOh.png" /></figure><p>The review page confirms the settings before you commit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O_LltmGYJkGBfu8y.png" /></figure><h4>🔍 Key behaviors I found</h4><p><strong>BGP needs the right SKU.</strong> The connection page later reminds you: “To enable BGP, the SKU has to be Standard or higher”. VpnGw2AZ clears that bar and gives zone redundancy as well.</p><p><strong>It takes a while.</strong> VPN gateways are slow to provision, often 30 to 45 minutes. Plan the rest of the build around it.</p><p><strong>A detail on the APIPA fields.</strong> On my review page both APIPA addresses appeared together under the first custom-APIPA field, and the second-instance field showed None. The tunnels and BGP sessions still came up. If you are designing this for production, check Microsoft&#39;s documentation on how APIPA addresses map to the two gateway instances.</p><h4>🔹 Part 6: Two Local Network Gateways</h4><p>Azure needs to know what is on the other end of each tunnel, so each GCP interface gets its own <strong>Local Network Gateway</strong>:</p><ul><li><strong>LNG 1</strong> azure-t0-gcp-network-gateway-1: IP 34.152.79.70, address space 169.254.21.1/32, BGP on, ASN 65001, BGP peer IP 169.254.21.1</li><li><strong>LNG 2</strong> azure-t0-gcp-network-gateway-2: IP 34.177.46.16, address space 169.254.22.1/32, BGP on, ASN 65001, BGP peer IP 169.254.22.1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WD4Hp-qr6PmSQiXT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2p3ik4aECku_J9KT.png" /></figure><h4>🔍 Key behaviors I found</h4><p><strong>Both LNGs use the same ASN.</strong> Both GCP interfaces belong to the same Cloud Router, so both LNGs carry Google’s ASN, 65001. What differs per LNG is the public IP and the BGP peer IP.</p><p><strong>The </strong><strong>/32 is the BGP peer address, not your VPC.</strong> The address space on each LNG is just the Cloud Router&#39;s APIPA address ( 169.254.21.1/32). Your actual VPC ranges are learned over BGP, so you never type them in.</p><p><strong>These values must match what you configure on GCP later.</strong> The LNG’s BGP peer IP has to equal the Cloud Router IP you assign in Part 8, exactly.</p><h4>🔹 Part 7: Two Azure connections</h4><p>On the gateway, go to <strong>Settings → Connections → Add</strong>, and create one site-to-site (IPsec) connection per tunnel:</p><ul><li>azure-to-gcp-tunnel-1 with LNG 1</li><li>azure-to-gcp-tunnel-2 with LNG 2</li><li>Authentication: shared key (PSK), <strong>identical</strong> to the one on the GCP tunnels</li><li>IKE protocol: <strong>IKEv2</strong></li><li><strong>Enable BGP:</strong> checked</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*my5RZMmoU9zEC_XB.png" /></figure><h4>🔍 Key behaviors I found</h4><p><strong>BGP has to be on in two places.</strong> It must be enabled on the gateway (Part 5) <em>and</em> on each connection. Missing either one is a classic reason for a tunnel that is up but a BGP session that never forms.</p><p><strong>Naming matters more than you think.</strong> My own note on the connection screenshot says the gateway should have been named azure-to-gcp-vpn; I had created it as gcp_to_azure_vpn, which reads backwards when the gateway belongs to Azure. Name resources by direction from the start.</p><h4>🔹 Part 8: Bringing up BGP on the GCP side</h4><p>Back in GCP, each tunnel now needs its BGP session. For each one, <strong>Configure BGP session</strong>, and instead of letting Google pick addresses, choose <strong>Allocate BGP IPv4 address: Manually</strong>:</p><ul><li><strong>Tunnel 1:</strong> peer ASN 65002, Cloud Router IP 169.254.21.1, BGP peer IP 169.254.21.2</li><li><strong>Tunnel 2:</strong> peer ASN 65002, Cloud Router IP 169.254.22.1, BGP peer IP 169.254.22.2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qwsg_JDsam2eQPsR.png" /></figure><p>Once the Azure side was complete, the first session showed as established:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gb_rsfyoUYSTEoD4.png" /></figure><p>and once the second was configured, both tunnels showed <strong>Established</strong> with <strong>BGP established</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PLVRcBJ3AZXnDegW.png" /></figure><p>Every address on this screen has to line up with something you typed earlier: the Cloud Router IP with the LNG’s BGP peer IP, and the BGP peer IP with the Azure APIPA address. That is why I keep calling it the part where one typo ruins your afternoon.</p><h4>🎯 The moment of truth: a private ping across clouds</h4><p>From gcp-vm, ping the Azure VM&#39;s <strong>private IP</strong>:</p><pre>$ ping 192.168.0.4<br>64 bytes from 192.168.0.4: icmp_seq=1 ttl=63 time=16.3 ms<br>64 bytes from 192.168.0.4: icmp_seq=2 ttl=63 time=14.9 ms<br>64 bytes from 192.168.0.4: icmp_seq=3 ttl=63 time=15.1 ms<br>3 packets transmitted, 3 received, 0% packet loss<br>rtt min/avg/max/mdev = 14.893/15.435/16.291/0.612 ms</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rwbv4T5FwjDvorEE.png" /></figure><p>Private connectivity between two clouds, about 15 ms round trip, no static routes. The same ping that hung in Part 2 now succeeds. Note the ttl=63: one hop was decremented on the way, which fits traffic crossing the VPN gateway.</p><p>Two follow-ups I would do next (I have only captured the GCP-to-Azure direction): ping 10.10.0.2 from azure-vm to confirm the reverse direction, and run a continuous ping while deleting one tunnel to watch BGP shift traffic to the other.</p><h4>🧾 Cheat Sheet: Gotchas Worth Remembering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kmaw4ayktQPNYELe.png" /></figure><h4>🕵️ Observations from the Build</h4><p>These came up during the actual build rather than from the docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bCC5z7B-KewpXRvb.png" /></figure><h4>💰 Cost and cleanup</h4><p>A VPN gateway is not free to leave running. <strong>VpnGw2AZ and the two Standard public IPs are billed hourly while they exist</strong>, and both clouds charge for the tunnels and for data transfer. Check the official pricing pages before leaving a lab like this up.</p><p>To clean up:</p><ol><li><strong>Azure:</strong> delete the resource group gcp_azure. That removes the VNet, VM, gateway, LNGs, connections and public IPs in one go.</li><li><strong>GCP:</strong> delete the two VPN tunnels, the HA VPN gateway, the peer VPN gateway, the Cloud Router, gcp-vm, and finally the VPC gcp-azure-vpc.</li></ol><h4>🔐 A note on secrets</h4><p>The pre-shared key is the only thing protecting the tunnels, and screenshots of the tunnel and connection forms can show it. If you publish a build like this, use a throwaway key, destroy the lab afterwards or rotate the key, and blur anything sensitive (keys, subscription IDs, email addresses) in your screenshots.</p><h4><a href="https://github.com/bikram-singh/gcp-azure-ha-vpn-bgp/tree/main/docs/snapshots">📸 Snapshots</a></h4><p>All screenshots from this build, sorted by step, are in the repository under <a href="https://github.com/bikram-singh/gcp-azure-ha-vpn-bgp/tree/main/docs/snapshots">docs/snapshots/</a>.</p><h4>🎯 Wrapping Up</h4><p>The mental model is simple: two endpoints on each side, two tunnels, BGP on top. In practice the hard part is not any single screen but the <strong>order of operations</strong> and the <strong>exact matching of values</strong> across two consoles: public IPs, ASNs, APIPA addresses and the pre-shared key. Get those lined up on paper first, and the build itself is straightforward.</p><p>Natural next steps:</p><ul><li><strong>Terraform it.</strong> The console is great for learning; production needs repeatability.</li><li><strong>Control what you advertise.</strong> Use custom route advertisements on the Cloud Router instead of advertising every subnet.</li><li><strong>Test failover properly.</strong> Take down one tunnel under a continuous ping and watch BGP converge.</li><li><strong>Outgrow the internet.</strong> When bandwidth or latency demands it, move to Interconnect and ExpressRoute.</li></ul><p>If you are connecting GCP to Azure, give this a try in a throwaway project before it goes near production.</p><h4>🔗 Repository</h4><p>🌐 <strong>gcp-azure-ha-vpn-bgp</strong>: <a href="https://github.com/bikram-singh/gcp-azure-ha-vpn-bgp">https://github.com/bikram-singh/gcp-azure-ha-vpn-bgp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f662a77f0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anthos-GKE Enterprise Fleet]]></title>
            <link>https://medium.com/@bikram23march/anthos-gke-enterprise-fleet-161856c4d3e4?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/161856c4d3e4</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 08:27:39 GMT</pubDate>
            <atom:updated>2026-10-04T08:27:39.669Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Terraform · GKE Fleet · Config Sync · Policy Controller · Cloud Service Mesh · Multi-cluster Gateway · Workload Identity</strong></p><h3>📋 Table of Contents</h3><ul><li>🌟 Introduction</li><li>🔑 Key Facts</li><li>✨ What It Does</li><li>🏗️ What We Are Building</li><li>🏛️ Architecture</li><li>🎯 Capabilities, In the Order They Were Actually Tested</li><li>📖 The Full Build Log</li><li>🧭 Where Anthos Fits: Hybrid, Multi-cloud, and When Plain GKE Is Enough</li><li>⚠️ Prerequisites and Reproduction</li><li>🐛 What Went Wrong</li><li>📊 The Real Numbers</li><li>🚧 Known Limitations</li><li>✅ Conclusion</li><li>📸 Snapshots</li><li>📚 Sources</li><li>🔗 Repository</li></ul><h3>🌟 Introduction</h3><p>Anthos is Google Cloud’s platform for managing many Kubernetes clusters as one fleet. It has since been renamed GKE Enterprise, and much of it now appears in Google’s documentation simply as GKE features. This project is a hands-on lab of that fleet idea.</p><p>We built two private GKE clusters, one in Mumbai and one in Singapore, with Terraform and a GitHub Actions pipeline that holds no stored keys, and registered both to a single fleet. On that fleet we ran Config Sync for GitOps, Policy Controller, Cloud Service Mesh, Multi-cluster Services and a global multi-cluster Gateway, and then added Workload Identity, Binary Authorization and fleet scopes.</p><p>There is no application to ship. The result is the infrastructure and a record of how each feature behaved, including the errors I hit along the way.</p><h3>🔑 Key Facts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*WJFzFYWmas17JH-AVLnhOw.png" /></figure><h3>✨ What It Does</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*jAPoPHmPLPkbmRoWmPo80g.png" /></figure><h3>🏗️ What We Are Building</h3><p>A lab where this:</p><pre>kubectl apply -f privileged-pod.yaml</pre><p>turns into a real, logged, verifiable rejection, not a claim:</p><pre>Error from server (Forbidden): admission webhook &quot;validation.gatekeeper.sh&quot; denied the request:<br>[no-privileged-containers] Privileged container is not allowed: nginx, securityContext: {&quot;privileged&quot;: true}</pre><p>where one request to a global load balancer lands on whichever cluster the URL map says it should:</p><pre>curl -H &quot;host: hello.example.com&quot; http://&lt;gateway-ip&gt;/a<br>hello from cluster-a<br><br>curl -H &quot;host: hello.example.com&quot; http://&lt;gateway-ip&gt;/b<br>hello from cluster-b</pre><p>and where two pods in the same namespace get different answers from Cloud Storage, with no key file anywhere:</p><pre>kubectl exec -n wi-demo reader   -- gcloud storage cat gs://&lt;bucket&gt;/hello.txt<br>hello from a private bucket<br><br>kubectl exec -n wi-demo stranger -- gcloud storage cat gs://&lt;bucket&gt;/hello.txt<br>ERROR: (gcloud.storage.cat) HTTPError 403: Caller does not have storage.objects.get access ...</pre><p>Concretely, this means:</p><ul><li>Two private GKE clusters in two regions, registered to one fleet, built with Terraform and applied by a GitHub Actions workflow that authenticates with Workload Identity Federation</li><li>Config Sync reconciling this Git repository into both clusters, at two scopes: a RootSync for cluster-wide objects and a RepoSync limited to one namespace</li><li>Policy Controller enforcing built-in constraints and one custom constraint written in Rego, all delivered through Git</li><li>A managed Cloud Service Mesh with strict mTLS, a per-identity AuthorizationPolicy and a weighted canary</li><li>Multi-cluster Services making one service name resolve to pods in both regions, and a global external Gateway with path routing, health-based failover and a weighted split</li><li>Keyless Workload Identity, a Binary Authorization dry run, a least-privilege node service account and fleet scopes, each tried once and written down</li><li>A teardown order that avoids orphaned load balancer resources, and a project shutdown at the end</li></ul><h3>🏛️ Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5hF1s9YC9-aiAkROR9NCw.png" /></figure><p>Borders in the diagram show how each part was built: solid blue for Terraform, dashed amber for gcloud, kubectl or the Console, and dashed red for resources created only for the test and removed afterwards. The Gateway resources lived on the config cluster, cluster-a.</p><p>A plain-text version of the same picture:</p><pre> GitHub repo -&gt; GitHub Actions -&gt; Workload Identity Federation -&gt; Terraform<br>                                                                    |<br>                                                                    v<br> +----------------------- Google Cloud project --------------------------+<br> |  VPC anthos-fleet-vpc  (private nodes, Cloud NAT, no external IPs)    |<br> |                                                                       |<br> |  +--------------------------+  MCS   +--------------------------+     |<br> |  | cluster-a  (Mumbai)      |&lt;------&gt;| cluster-b  (Singapore)   |     |<br> |  | config cluster           |        | mesh and WI demos        |     |<br> |  | Config Sync, Gatekeeper  |        | Config Sync, Gatekeeper  |     |<br> |  +--------------------------+        +--------------------------+     |<br> |               ^                                  ^                    |<br> |               +---------- fleet (Connect) -------+                    |<br> |                                                                       |<br> |  Global external load balancer (test only) -&gt; pods in both clusters   |<br> +-----------------------------------------------------------------------+</pre><h3>🔄 Layer Breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*W5KNjQ17rFkWInkG0IxyXA.png" /></figure><h4>🎯 Capabilities, In the Order They Were Actually Tested</h4><p>Listed in the order the work really happened, not in a tidy logical order:</p><ol><li><strong>Foundation</strong>: project, budget, state bucket, a CI service account and keyless GitHub authentication</li><li><strong>Infrastructure with Terraform</strong>: private clusters and Cloud NAT, after an organization policy refused the first design</li><li><strong>Fleet management</strong>: memberships, fleet features and Connect Gateway access</li><li><strong>Config Sync</strong>: a RootSync, drift correction, and an invisible character that blocked the whole sync</li><li><strong>Policy Controller</strong>: deny on both clusters, audit mode, constraints shipped through Git</li><li><strong>Cloud Service Mesh</strong>: injection, strict mTLS, authorization, a canary, and configuration that took minutes to reach running proxies</li><li><strong>Multi-cluster Services</strong>: export, import, a wrong IAM member format, merged endpoints and failover</li><li><strong>The global Gateway</strong>: path routing, failover, and a weighted split that looked broken until I waited</li><li><strong>RepoSync</strong>: namespace-scoped GitOps and a policy that refuses a foreign namespace</li><li><strong>Workload Identity</strong>: two pods, one grant, one HTTP 403</li><li><strong>A custom ConstraintTemplate</strong>: a rule written in Rego and delivered through Git</li><li><strong>Fleet scopes</strong>: a team’s namespace created on both clusters from one definition</li><li><strong>Binary Authorization in dry-run</strong>: a would-be denial recorded in the audit log</li><li><strong>A least-privilege node service account</strong>: validated on a temporary node pool</li><li><strong>Closing the caveats</strong>: proving the organization policy, reading the fleet’s view of Config Sync, checking the node service account’s roles</li><li><strong>Teardown</strong>: an ordered cleanup, then shutting the whole project down</li></ol><p>The list above is the compact version. The sections that follow cover the same ground in full: the commands, the log excerpts, the errors and the fixes.</p><h3>📖 The Full Build Log</h3><p>Every step below includes what I ran, what came back, and what I got wrong along the way.</p><h3>🏗️ Step 1: Foundation</h3><p>Before any cluster exists, four things have to be in place: a project with a spending guardrail, somewhere safe to keep Terraform state, an identity for the pipeline, and a way for GitHub to become that identity without a downloaded key.</p><p><strong>The project and the budget.</strong> The project is gcp-anthos-fleet, linked to the trial billing account. I created a budget named anthos-fleet-lab for 3,000 rupees, scoped to the project, with alerts at 50%, 90% and 100%. Budget alerts only send email. They do not stop spending, which matters later when the load balancer is running.</p><p><em>Screenshot: Billing &gt; Budgets &amp; alerts (docs/snapshots/01-foundation/01-billing-budgets-and-alerts.png)</em></p><p><strong>The state bucket.</strong> Terraform state lives in a Cloud Storage bucket, gcp-anthos-fleet-tfstate, in asia-south1 with versioning on. Versioning is what lets you recover a state file after a bad run, and this lab produced a bad run.</p><pre>gcloud storage buckets create &quot;gs://gcp-anthos-fleet-tfstate&quot; --location=asia-south1 --uniform-bucket-level-access<br>gcloud storage buckets update &quot;gs://gcp-anthos-fleet-tfstate&quot; --versioning</pre><p><strong>The pipeline’s identity.</strong> A service account named tf-github-actions is what Terraform runs as. It gets the roles it needs and nothing broader: container.admin, compute.networkAdmin, compute.viewer, gkehub.admin, serviceusage.serviceUsageAdmin and iam.serviceAccountUser at project level, plus storage.objectAdmin on the state bucket only.</p><pre>foreach ($role in @(&quot;roles/container.admin&quot;,&quot;roles/compute.networkAdmin&quot;,&quot;roles/compute.viewer&quot;,&quot;roles/gkehub.admin&quot;,&quot;roles/serviceusage.serviceUsageAdmin&quot;,&quot;roles/iam.serviceAccountUser&quot;)) {<br>  gcloud projects add-iam-policy-binding $PROJECT_ID &quot;--member=serviceAccount:$SA_EMAIL&quot; &quot;--role=$role&quot; --condition=None<br>}<br>gcloud storage buckets add-iam-policy-binding &quot;gs://$BUCKET&quot; &quot;--member=serviceAccount:$SA_EMAIL&quot; --role=&quot;roles/storage.objectAdmin&quot;</pre><p><strong>Keyless authentication.</strong> I did not want a downloadable service account key in the first place. Workload Identity Federation lets GitHub Actions exchange its own short-lived OIDC token for Google credentials. The provider is locked to this one repository with an attribute condition, so a workflow in any other repository cannot use it:</p><pre>gcloud iam workload-identity-pools create github-pool --location=global --display-name=&quot;GitHub Pool&quot;<br>gcloud iam workload-identity-pools providers create-oidc github-provider --location=global --workload-identity-pool=github-pool `<br>  --issuer-uri=&quot;https://token.actions.githubusercontent.com&quot; `<br>  &quot;--attribute-mapping=google.subject=assertion.sub,attribute.repository=assertion.repository&quot; `<br>  &quot;--attribute-condition=assertion.repository==&#39;&lt;owner&gt;/gcp-anthos-fleet&#39;&quot;</pre><p>The last piece is letting that GitHub identity impersonate the service account, then handing the workflow three values through repository secrets, with no key among them:</p><pre>gh secret set WIF_PROVIDER --repo &lt;owner&gt;/gcp-anthos-fleet --body &quot;projects/&lt;PROJECT_NUMBER&gt;/locations/global/workloadIdentityPools/github-pool/providers/github-provider&quot;<br>gh secret set WIF_SERVICE_ACCOUNT --repo &lt;owner&gt;/gcp-anthos-fleet --body &quot;tf-github-actions@gcp-anthos-fleet.iam.gserviceaccount.com&quot;<br>gh secret set TF_STATE_BUCKET --repo &lt;owner&gt;/gcp-anthos-fleet --body &quot;gcp-anthos-fleet-tfstate&quot;</pre><p>The PowerShell backticks and the quoting around — member and — attribute-mapping are not decoration. Windows PowerShell splits and rewrites some unquoted arguments differently from bash, and quoting caused several failures later in this lab.</p><h3>🌐 Step 2: Infrastructure with Terraform</h3><p>The Terraform lives in one folder with one concern per file: providers.tf, variables.tf, apis.tf, network.tf, nat.tf, clusters.tf, fleet.tf and outputs.tf. The provider is google ~&gt; 6.0 and the backend is the GCS bucket from Step 1.</p><p><strong>The network.</strong> One custom-mode VPC, anthos-fleet-vpc, with a VPC-native subnet in each region. Each subnet carries two secondary ranges, one for pods and one for services, which is what makes the clusters VPC-native (alias IP) clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*AOlOj1rS8opJqyE6ls0vxQ.png" /></figure><p><strong>The first design failed.</strong> My first version used GKE’s defaults, which means nodes with external IP addresses. The apply did not get far. This organization enforces the constraint compute.vmExternalIpAccess, and no virtual machine in the project is allowed an external IP. Nodes are virtual machines. I come back to this constraint in Step 10 and prove exactly what it says, but at the time all I saw was a failed apply.</p><p><strong>The fix: private nodes and Cloud NAT.</strong> If nodes cannot have external IPs, they have to be private, and private nodes still need a way out to pull container images and reach Google APIs. That way out is Cloud NAT. The relevant part of each cluster looks like this:</p><pre>private_cluster_config {<br>  enable_private_nodes    = true<br>  enable_private_endpoint = false   # keep the control plane reachable from outside<br>  master_ipv4_cidr_block  = &quot;172.16.0.0/28&quot;<br>}</pre><p>Each region also gets a Cloud Router and a Cloud NAT gateway, named router-cluster-a, nat-cluster-a, router-cluster-b and nat-cluster-b. I left the control-plane endpoint public (enable_private_endpoint = false) so that kubectl from my laptop could reach the API server directly.</p><p><strong>The clusters and the fleet.</strong> Each cluster is a Standard (not Autopilot) zonal cluster, with Workload Identity enabled and a node pool named primary of two e2-standard-4 nodes on Container-Optimized OS. The fleet registration is a single fleet {} block on each cluster resource, and Terraform also turns on two fleet features, configmanagement and servicemesh. Kubernetes came up as version 1.35.8.</p><pre>gcloud container clusters list --project gcp-anthos-fleet<br>NAME: cluster-a   LOCATION: asia-south1-a      MASTER_VERSION: 1.35.8-gke.1225000  NUM_NODES: 2  STATUS: RUNNING<br>NAME: cluster-b   LOCATION: asia-southeast1-a  MASTER_VERSION: 1.35.8-gke.1225000  NUM_NODES: 2  STATUS: RUNNING</pre><p><strong>The pipeline.</strong> Terraform runs from a GitHub Actions workflow with a manual trigger and one input, action, which takes plan, apply or destroy. A plan is read before an apply, and an apply is a deliberate act:</p><pre>gh workflow run terraform.yml --repo &lt;owner&gt;/gcp-anthos-fleet -f action=plan<br>gh workflow run terraform.yml --repo &lt;owner&gt;/gcp-anthos-fleet -f action=apply</pre><p><strong>Three process mistakes worth recording.</strong></p><ul><li><strong>Two runs, one lock.</strong> I started a second workflow run about a minute after the first. Both wanted the Terraform state lock and one failed with Error acquiring the state lock. Run one at a time, and clear a stale lock only after confirming nothing is running.</li><li><strong>The fix that was never committed.</strong> After one failed run I fixed the Terraform, committed and pushed, and the next run behaved exactly like the old code. The commit contained only an error log file. The Terraform changes were never staged. Since then I check git show — stat HEAD before every push.</li><li><strong>Cancelling a destroy does not stop it.</strong> I cancelled a destroy run that looked stuck. The cancel stopped the workflow, but the delete requests it had already sent kept running on Google’s side, and the node pools and the two fleet features disappeared anyway. Recovery was to wait for those operations to finish, clear the stale lock, then plan and apply again. Never cancel a destroy; let it finish.</li></ul><h3>🧭 Step 3: Fleet Management</h3><p>Terraform had already registered both clusters, so the first job was only to confirm what the fleet looked like from the outside.</p><pre>gcloud container fleet memberships list --project gcp-anthos-fleet<br>NAME: cluster-a   LOCATION: asia-south1<br>NAME: cluster-b   LOCATION: asia-southeast1</pre><p>The fleet-level features that were already active:</p><pre>gcloud container fleet features list --project gcp-anthos-fleet<br>authorizer, configmanagement, fleetobservability, metering, policycontroller,<br>rbacrolebindingactuation, servicemesh, workloadidentity     (all STATE: ACTIVE)</pre><p>In the Console, the Fleet Dashboard shows the clusters in the fleet and their health, and the Feature Manager lists every fleet-level feature with a per-cluster status. At this point Identity Service, Multi Cluster Ingress and Knative serving all showed as not enabled, which is the right starting state: I had not asked for them.</p><p><strong>Reaching the clusters: Connect Gateway.</strong> The fleet gives you a way to run kubectl against a member cluster through Google rather than straight at the cluster’s own endpoint. One command writes a kubeconfig entry for it:</p><pre>gcloud container fleet memberships get-credentials cluster-a --location=asia-south1 --project gcp-anthos-fleet<br>A new kubeconfig entry &quot;connectgateway_gcp-anthos-fleet_asia-south1_cluster-a&quot; has been generated and set as the current context.<br><br>kubectl get nodes<br>NAME                                  STATUS   ROLES    AGE   VERSION<br>gke-cluster-a-primary-5f59b5d0-dhhc   Ready    &lt;none&gt;   43m   v1.35.8-gke.1225000<br>gke-cluster-a-primary-5f59b5d0-fp2r   Ready    &lt;none&gt;   43m   v1.35.8-gke.1225000</pre><p><strong>A limit worth knowing early: exec does not work through Connect Gateway.</strong> kubectl get, apply and describe all worked fine. kubectl exec returned an HTTP 400. For anything that needs exec, which in this lab meant every traffic test that ran curl inside a pod, I used the direct cluster contexts instead, named gke_&lt;project&gt;_&lt;zone&gt;_&lt;cluster&gt;:</p><pre>gcloud container clusters get-credentials cluster-a --location=asia-south1-a --project gcp-anthos-fleet</pre><p>From here on, two contexts per cluster exist in my kubeconfig. I used the Connect Gateway ones for reading and applying, and the direct ones whenever I needed to run a command inside a pod.</p><h3>🔁 Step 4: GitOps with Config Sync</h3><p>Config Sync watches a folder in a Git repository and makes a cluster match it. The idea is simple and the fleet makes it scale: point every member cluster at the same folder and they converge on the same state. Anything you change by hand gets put back.</p><p><strong>Installing it.</strong> I installed Config Sync from the Console, under Kubernetes Engine &gt; Config delivery &gt; Install Config Sync, choosing Install Config Sync on individual clusters and selecting both clusters. The Settings tab showed both clusters as Pending for a short while, then Enabled, with version 1.25.0 on each.</p><p><em>Screenshots: the install dialog, Settings with both clusters pending, then enabled, and the dashboard before the first package was deployed (docs/snapshots/04-config-sync/01-install-config-sync-dialog.png to 04-dashboard-before-first-package.png)</em></p><p>The Console also offers a fleet-level Configure step and a Sync to fleet settings action, and I used both. I come back to that in Step 10, because the fleet’s own record of Config Sync turned out to look different from what the Console showed.</p><pre>kubectl get pods -n config-management-system<br>NAME                                  READY   STATUS    RESTARTS   AGE<br>reconciler-manager-69484dd5ff-mb6sj   2/2     Running   0          10m<br><br>kubectl get crd rootsyncs.configsync.gke.io</pre><p><strong>Why a kubectl RootSync and not a gcloud command.</strong> The documented gcloud commands for applying and checking Config Sync, config-management apply and config-management status, live in the beta command group. Installing the beta component on my Windows machine failed:</p><pre>ERROR: (gcloud) You cannot perform this action because you do not have permission to modify the<br>Google Cloud SDK installation directory [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk].</pre><p>I did not have admin rights, so I skipped gcloud for this step and created the RootSync object directly with kubectl. A RootSync is just a Kubernetes custom resource, and Config Sync does not care how it got there:</p><pre>apiVersion: configsync.gke.io/v1beta1<br>kind: RootSync<br>metadata:<br>  name: root-sync<br>  namespace: config-management-system<br>spec:<br>  sourceFormat: unstructured<br>  sourceType: git<br>  git:<br>    repo: https://github.com/bikram-singh/gcp-anthos-fleet<br>    branch: main<br>    dir: config-sync-repo<br>    auth: none</pre><p>auth: none works because the repository is public. A private repository needs a credential. I applied the same file to both clusters:</p><pre>kubectl apply -f fleet-config\rootsync.yaml      # once per cluster context<br>rootsync.configsync.gke.io/root-sync created</pre><p><strong>What the repository contains.</strong> The folder the RootSync reads is config-sync-repo/. At this stage it held a namespace called demo, a second namespace, demo-2, and a default-deny ingress NetworkPolicy in demo. Later steps add policy constraints and a custom policy template to the same folder.</p><p><strong>The invisible character that blocked everything.</strong> One of the namespace files I pushed failed to sync, and the error was not obvious: Config Sync reported KNV2010 with a message about a missing apiVersion, on a file that plainly had an apiVersion. The cause was a byte-order mark. In Windows PowerShell 5.1, Set-Content -Encoding utf8 writes a UTF-8 file with a BOM at the start. The YAML parser sees three invisible bytes before the first key, and the first key, apiVersion, no longer matches. One bad file blocked the whole sync. The fix is to write files with an encoder that omits the BOM:</p><pre>$utf8 = New-Object System.Text.UTF8Encoding($false)<br>[System.IO.File]::WriteAllText($path, $text, $utf8)</pre><p>I used that writer for every file in every repository after this.</p><p><strong>Checking the sync.</strong> The RootSync object reports its own state, and the two commit columns should match:</p><pre>kubectl get rootsync -n config-management-system<br>NAME        SOURCECOMMIT   SYNCCOMMIT     SYNCERRORCOUNT<br>root-sync   7165701b83...  7165701b83...</pre><p>The output above is abridged to the columns that matter. When SYNCCOMMIT equals SOURCECOMMIT and the error count is empty, the cluster matches Git. In the Console, Config delivery &gt; Packages shows root-sync as Synced and Current on both clusters, with the repository as its source.</p><p><strong>Drift correction.</strong> This is the demonstration that makes GitOps feel real. I deleted the default-deny NetworkPolicy from the demo namespace on cluster-b with kubectl, as if someone had done it by hand during an incident:</p><pre>kubectl --context &lt;cluster-b&gt; delete networkpolicy default-deny-ingress -n demo<br>kubectl --context &lt;cluster-b&gt; get networkpolicy -n demo -w</pre><p>Within about a minute the policy was back, recreated by Config Sync from Git. The thing that was deleted by hand is not the source of truth, and the cluster knows it. I ran this check on cluster-b only.</p><h3>📜 Step 5: Policy as Code with Policy Controller</h3><p>Policy Controller is Google’s managed distribution of OPA Gatekeeper. It has two halves that are easy to mix up. A <strong>ConstraintTemplate</strong> defines a kind of rule and the logic behind it. A <strong>Constraint</strong> is one use of that template: this rule, on these objects, enforced this way. Enforcement comes in two forms that matter here. Deny means an admission webhook rejects the object when someone tries to create it. Dryrun means the object is allowed and a periodic audit reports it as a violation afterwards.</p><p><strong>Enabling it.</strong> The fleet-wide form of the enable command failed. First it returned an internal error, and when I tried to look at the state afterwards it complained that the membership was not found. Enabling it one membership at a time, with an explicit location, worked:</p><pre>gcloud container fleet policycontroller enable --memberships=cluster-a --location=asia-south1<br>gcloud container fleet policycontroller enable --memberships=cluster-b --location=asia-southeast1</pre><p>A few minutes later each cluster had the Gatekeeper components and the default template library, more than 80 templates including k8spspprivilegedcontainer and k8srequiredlabels.</p><p><strong>Delivering constraints through Git.</strong> This is where Step 4 pays off. The constraints are plain files in config-sync-repo/policies/, so Config Sync delivers them to both clusters and policy changes go through pull requests like everything else. Two constraints, both scoped to the demo namespace:</p><ul><li>no-privileged-containers, built on K8sPSPPrivilegedContainer, enforcement deny</li><li>pods-must-have-app-label, built on K8sRequiredLabels, enforcement dryrun</li></ul><p>The first one has this shape:</p><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: K8sPSPPrivilegedContainer<br>metadata:<br>  name: no-privileged-containers<br>spec:<br>  enforcementAction: deny<br>  match:<br>    kinds:<br>    - apiGroups: [&quot;&quot;]<br>      kinds: [&quot;Pod&quot;]<br>    namespaces: [&quot;demo&quot;]</pre><p><strong>Deny, on both clusters.</strong> I tried to create a privileged pod in the demo namespace:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: bad-pod<br>  namespace: demo<br>spec:<br>  containers:<br>    - name: nginx<br>      image: nginx<br>      securityContext:<br>        privileged: true</pre><p>Both clusters rejected it with the same message, from the admission webhook:</p><pre>Error from server (Forbidden): admission webhook &quot;validation.gatekeeper.sh&quot; denied the request:<br>[no-privileged-containers] Privileged container is not allowed: nginx, securityContext: {&quot;privileged&quot;: true}</pre><p>This check ran on cluster-b first. For a while I had only done it there, and the cluster-a result came later, when I went back to close that gap.</p><p><strong>Audit, on both clusters.</strong> For the dryrun constraint I created an ordinary nginx pod with no app label. It was admitted without complaint, which is the point of dryrun. About two minutes later the audit listed it:</p><pre>kubectl run ok-pod --image=nginx -n demo<br># wait about two minutes for the audit<br>kubectl describe k8srequiredlabels pods-must-have-app-label<br>  Total Violations:  1<br>  Violations:<br>    Enforcement Action:  dryrun<br>    Kind:                Pod<br>    Message:             you must provide labels: {&quot;app&quot;}<br>    Name:                ok-pod<br>    Namespace:           demo</pre><p>The two modes complement each other. Deny stops a bad object at the door. Audit finds the objects that were already there, or that arrived while a constraint was still in dryrun.</p><p><strong>The Console view.</strong> The Policy page showed both clusters with Policy Controller installed and with violations, and counted 26 constraints by enforcement: 24 in dryrun and 2 in deny. The two deny entries match my single deny constraint counted once per cluster. The dryrun entries are my app-label constraint plus built-in bundle constraints, which report violations without blocking anything. The page lists bundles such as the CIS Kubernetes benchmark and the Pod Security Standards.</p><h3>🕸️ Step 6: Cloud Service Mesh</h3><p>A service mesh puts a proxy next to every workload and lets you enforce encryption, identity and routing without touching application code. Cloud Service Mesh is Google’s managed Istio. With the managed control plane, Google runs the control plane for you and you only deal with the sidecars and the policy objects.</p><p><strong>Enabling it.</strong> One command per cluster. On a new fleet the managed control plane comes up as the Traffic Director implementation, under the revision name asm-managed:</p><pre>gcloud container fleet mesh update --management automatic --memberships=cluster-a --location=asia-south1<br>gcloud container fleet mesh update --management automatic --memberships=cluster-b --location=asia-southeast1<br>gcloud container fleet mesh describe      # wait until control plane and data plane are ACTIVE</pre><p><strong>The demo workloads.</strong> I put them all on cluster-b, in a namespace called mesh-demo, labeled so that sidecars get injected automatically:</p><pre>kubectl label namespace mesh-demo istio.io/rev=asm-managed</pre><p>The namespace holds httpbin (the server), a client, two callers with their own service accounts called sleep-allowed and sleep-denied, and two versions of a small web application, webapp-v1 and webapp-v2. A separate caller, outside-client, runs in a different namespace with no injection, standing in for anything that is not part of the mesh.</p><p>Pods in the mesh show two containers, READY 2/2, the application plus its Envoy sidecar. The first pods I created showed 1/2 for a short while until the control plane finished provisioning. A response header confirms the traffic really goes through Envoy: server: envoy.</p><p><strong>Strict mTLS.</strong> A PeerAuthentication object set to STRICT makes every workload in the namespace refuse plaintext traffic:</p><pre>apiVersion: security.istio.io/v1beta1<br>kind: PeerAuthentication<br>metadata:<br>  name: default<br>  namespace: mesh-demo<br>spec:<br>  mtls:<br>    mode: STRICT</pre><p>The first test looked like a failure. Right after applying it, the caller outside the mesh still got HTTP 200. I will come back to why, because it happened three times in this lab. After waiting, and restarting the target pod, the outside caller was rejected. Its curl returned exit code 56, a connection reset, because it could not complete the mutual TLS handshake.</p><p><strong>Authorization by identity.</strong> Strict mTLS proves who is calling. An AuthorizationPolicy decides whether that caller is allowed. This policy lets exactly one workload identity reach httpbin:</p><pre>apiVersion: security.istio.io/v1beta1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: httpbin-allow-only-sleep-allowed<br>  namespace: mesh-demo<br>spec:<br>  selector:<br>    matchLabels:<br>      app: httpbin<br>  action: ALLOW<br>  rules:<br>  - from:<br>    - source:<br>        principals: [&quot;cluster.local/ns/mesh-demo/sa/sleep-allowed&quot;]</pre><p>After the policy had reached the running proxies, four callers got four different answers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*LC1mXVffQ8TdQF-yLSY-8Q.png" /></figure><p><strong>The lesson that repeated: configuration takes minutes to reach running proxies.</strong> I applied PeerAuthentication, AuthorizationPolicy and routing rules, tested immediately, and got answers that contradicted the configuration: callers that should have been rejected got through, and in one case I got a 503. The configuration was correct and the proxies were simply behind. What fixed it every time was waiting a few minutes and restarting the target pods, after which they picked the new configuration up quickly. If you test a mesh change in the first minute, you are testing the old configuration.</p><p><strong>A canary release.</strong> With two Services, webapp-v1 and webapp-v2, a VirtualService can send a weighted share of traffic to each. Before any rule existed, traffic split 49 and 51 between the versions. Then I applied a 90/10 rule, shown here in the shape that worked:</p><pre>apiVersion: networking.istio.io/v1beta1<br>kind: VirtualService<br>metadata:<br>  name: webapp<br>  namespace: mesh-demo<br>spec:<br>  hosts:<br>  - webapp<br>  http:<br>  - route:<br>    - destination:<br>        host: webapp-v1<br>      weight: 90<br>    - destination:<br>        host: webapp-v2<br>      weight: 10</pre><p>A loop of 500 requests from the client pod counted <strong>447 answers from v1 and 53 from v2</strong>, which is 89.4 percent and 10.6 percent against a configured 90 and 10. An earlier sample of only 100 requests gave 82 and 18, a reminder that small samples wander, and that I may also have sampled before the proxies caught up.</p><p><strong>What did not work, and I never explained.</strong> The more common way to write a canary is one Service, a DestinationRule that defines subsets by version label, and a VirtualService that routes to the subsets. I wrote it that way first. Traffic to webapp came back HTTP 503, and it kept coming back 503 even after waiting and restarting. The same split written as two Services and a plain VirtualService worked immediately. I do not know why the subset version failed, and I did not find out.</p><p><strong>In the Console.</strong> The Service Mesh page lists the services with their traffic, error rate and latency, and draws a topology of who calls whom. The Workloads page shows the pods in mesh-demo with two containers each. I did not try to create an SLO on the Service Mesh page.</p><p>One limit on all of this: the injection, mTLS, authorization and canary tests ran on cluster-b only. I enabled the managed mesh on both clusters, but I did not repeat the demo on cluster-a.</p><h3>🌍 Step 7: Multi-cluster Services</h3><p>A Kubernetes Service stops at the edge of its cluster. If a pod in Mumbai needs a service that runs in Singapore, plain Kubernetes gives it nothing to call. Multi-cluster Services (MCS) fixes that with two small objects. You create a <strong>ServiceExport</strong> next to the Service you want to share. The fleet then creates a <strong>ServiceImport</strong> in every other cluster, with its own virtual IP, and a DNS name of the form service.namespace.svc.clusterset.local that resolves to endpoints in all the clusters that export it.</p><p><strong>Enabling it.</strong> The APIs first, then the fleet feature:</p><pre>gcloud services enable multiclusterservicediscovery.googleapis.com trafficdirector.googleapis.com dns.googleapis.com gkehub.googleapis.com cloudresourcemanager.googleapis.com<br>gcloud container fleet multi-cluster-services enable</pre><p>Enabling the feature also creates firewall rules in the VPC so pods in one cluster can reach pods in the other. They show up in VPC network &gt; Firewall, named like gke-cluster-a-75319e45-mcsd and described as a managed firewall for multi-cluster pod and service ingress.</p><p><strong>The first failure: the wrong IAM member format.</strong> MCS runs an importer in each cluster, in a namespace called gke-mcs, and it needs permission to read network information in the project (the role roles/compute.networkViewer). I granted it using the older Workload Identity member format, the one with the pool name and the Kubernetes service account in square brackets:</p><pre>serviceAccount:&lt;PROJECT_ID&gt;.svc.id.goog[gke-mcs/gke-mcs-importer]</pre><p>The symptoms were quiet and confusing. A ServiceImport appeared and had a ClusterSetIP, but no endpoint slices were created behind it, so a call to that IP was refused (curl exit code 7). Nothing in the Console said the grant was the problem. The format that works is the principal:// form, which names the workload identity directly. After adding it and restarting the importer, endpoints appeared:</p><pre>gcloud projects add-iam-policy-binding &lt;PROJECT_ID&gt; `<br>  &quot;--member=principal://iam.googleapis.com/projects/&lt;PROJECT_NUMBER&gt;/locations/global/workloadIdentityPools/&lt;PROJECT_ID&gt;.svc.id.goog/subject/ns/gke-mcs/sa/gke-mcs-importer&quot; `<br>  --role=roles/compute.networkViewer</pre><p><strong>Exporting a service.</strong> I deployed a small echo service called hello in a namespace called mcs-demo on cluster-b, two pods that answer with hello from cluster-b, behind a Service on port 80. Then I exported it:</p><pre>kind: ServiceExport<br>apiVersion: net.gke.io/v1<br>metadata:<br>  name: hello<br>  namespace: mcs-demo</pre><p>A ServiceImport named hello appeared on cluster-a with a ClusterSetIP of 10.30.8.121, an address from cluster-a’s own service range. In the Console, Gateways, Services &amp; Ingress also shows derived Services named gke-mcs-&lt;hash&gt; in the mcs-demo namespace, which are how the fleet represents the imported endpoints inside each cluster.</p><p><strong>Four checks, from a client pod in cluster-a:</strong></p><ol><li><strong>A call straight to a pod IP in cluster-b.</strong> It answered hello from cluster-b. This proves the network path between the two regions works before DNS or the importer are involved.</li><li><strong>A call by clusterset name,</strong> hello.mcs-demo.svc.clusterset.local. It resolved and answered. The name resolves through the cluster’s own DNS.</li><li><strong>Merged endpoints.</strong> I deployed the same hello service on cluster-a and exported it from both clusters. One service name now fronted pods in both regions, and 100 requests came back 53 from cluster-b and 47 from cluster-a.</li><li><strong>Failover.</strong> I scaled the hello deployment on cluster-b to zero and waited for the endpoints to refresh. All of the next 50 requests were answered by cluster-a.</li></ol><p>Two things differed from what I expected. First, the documentation says MCS creates Cloud DNS zones for clusterset.local. In this project it created none: gcloud dns managed-zones list came back empty, and the name still resolved. I recorded that as an observed difference and did not chase it. Second, the failover is only as fast as the endpoint refresh, so a test run immediately after scaling down measures the old state. Waiting before measuring was the right call here, as it was with the mesh.</p><h3>🛣️ Step 8: The Global Multi-cluster Gateway</h3><p>Multi-cluster Services lets pods call each other across regions. A multi-cluster Gateway does the same for outside traffic: one external load balancer, one public address, backends in several clusters. The Gateway API objects live on one cluster, the <strong>config cluster</strong>, and the load balancer’s backends point at pods in every cluster that exports the service. I made cluster-a the config cluster.</p><p><strong>Order matters: Gateway API first, fleet ingress second.</strong> The Gateway API has to be enabled on the clusters before the fleet ingress feature, so I did it in that order:</p><pre>gcloud container clusters update cluster-a --gateway-api=standard --location=asia-south1-a<br>gcloud container clusters update cluster-b --gateway-api=standard --location=asia-southeast1-a<br>kubectl --context &lt;cluster-a&gt; get gatewayclasses</pre><p>At this point there were four single-cluster classes: gke-l7-global-external-managed, gke-l7-gxlb, gke-l7-regional-external-managed and gke-l7-rilb. Then I enabled fleet ingress with cluster-a as the config cluster and gave the multi-cluster ingress service agent the container.admin role, as Google’s documentation requires:</p><pre>gcloud container fleet ingress enable --config-membership=projects/&lt;PROJECT_ID&gt;/locations/asia-south1/memberships/cluster-a<br>gcloud projects add-iam-policy-binding &lt;PROJECT_ID&gt; &quot;--member=serviceAccount:service-&lt;PROJECT_NUMBER&gt;@gcp-sa-multiclusteringress.iam.gserviceaccount.com&quot; --role=roles/container.admin<br>gcloud container fleet ingress describe     # state: OK, description: Ready to use</pre><p>A minute later five new classes appeared with an -mc suffix: gke-l7-global-external-managed-mc, gke-l7-gxlb-mc, gke-l7-regional-external-managed-mc, gke-l7-rilb-mc and gke-l7-cross-regional-internal-managed-mc. Those are the multi-cluster classes.</p><p><strong>Cluster-specific backends.</strong> For path-based routing I wanted a way to address each cluster on its own. I created two more Services, hello-a on cluster-a and hello-b on cluster-b, each exported with its own ServiceExport. Together with the shared hello service, cluster-a then listed three ServiceImports: hello, hello-a and hello-b.</p><p><strong>The Gateway and the route.</strong> The Gateway asks for the global external multi-cluster class. The route sends three kinds of request to three different backends:</p><pre>kind: Gateway<br>apiVersion: gateway.networking.k8s.io/v1<br>metadata:<br>  name: external-http<br>  namespace: mcs-demo<br>spec:<br>  gatewayClassName: gke-l7-global-external-managed-mc<br>  listeners:<br>  - name: http<br>    protocol: HTTP<br>    port: 80<br>    allowedRoutes:<br>      kinds:<br>      - kind: HTTPRoute<br>---<br>kind: HTTPRoute<br>apiVersion: gateway.networking.k8s.io/v1<br>metadata:<br>  name: hello-route<br>  namespace: mcs-demo<br>spec:<br>  hostnames:<br>  - &quot;hello.example.com&quot;<br>  parentRefs:<br>  - name: external-http<br>  rules:<br>  - matches:<br>    - path: {type: PathPrefix, value: /a}<br>    backendRefs:<br>    - {group: net.gke.io, kind: ServiceImport, name: hello-a, port: 80}<br>  - matches:<br>    - path: {type: PathPrefix, value: /b}<br>    backendRefs:<br>    - {group: net.gke.io, kind: ServiceImport, name: hello-b, port: 80}<br>  - backendRefs:<br>    - {group: net.gke.io, kind: ServiceImport, name: hello, port: 80}</pre><p>The backendRefs are ServiceImport objects, not Services. That is what makes the backends span clusters.</p><p><strong>It took about ten minutes to serve traffic.</strong> Right after creation the Gateway had no address, and when it did get one, my first requests failed. I tested with a retry loop and the sequence was always the same: a connection reset, then a 502, then 200:</p><pre>12:56:51   [http=000]      connection reset<br>12:57:11   502 Server Error<br>12:57:31   hello from cluster-a  [http=200]</pre><p>If you build this and see resets and 502s in the first ten minutes, nothing is wrong yet.</p><p><strong>Path routing, and where the default path goes.</strong> Once it served, /a answered hello from cluster-a and /b answered hello from cluster-b. The default path, with no prefix, goes to the shared hello service, which has pods in both clusters, and the load balancer sends each request to the nearest healthy region. From my location in India, 70 of 70 requests on the default path were answered by cluster-a in Mumbai. That is the load balancer working as designed, not a lack of balancing.</p><p><strong>Failover through the load balancer.</strong> I scaled the hello deployment on cluster-a to zero and sampled every 20 seconds. The first sample after the change was a single failure, upstream connect error or disconnect/reset before headers, HTTP 503. The next sample, 20 seconds later, was answered by cluster-b, and it stayed that way. So the failover completed within one 20-second sampling interval.</p><p><strong>A mistake that voided my first rejoin test.</strong> I scaled cluster-a back up with a command that printed nothing, assumed it had run, and sampled for several minutes. Every answer came from cluster-b. When I listed the pods, cluster-a had no hello pods at all. The command had never taken effect, and it had printed no confirmation. After I restored it properly, the answers moved back to cluster-a at the second sample after the pods were ready, about 30 seconds. The lesson is the boring one: after a scale command, check the pods before you interpret anything.</p><p><strong>The weighted split, and why it looked broken.</strong> I added a fourth rule, /split, with 80 percent of traffic to hello-a and 20 percent to hello-b. Then I sent 200 requests and all 200 came from cluster-a. I sent 200 more and the answer was the same. The weights looked ignored.</p><p>They were not. Before assuming a bug, I looked at the load balancer’s own URL map, which is the source of truth for what Google had actually programmed:</p><pre>- fullPathMatch: /split<br>  routeAction:<br>    weightedBackendServices:<br>    - backendService: .../gkemcg1-mcs-demo-hello-a-80-...<br>      weight: 80<br>    - backendService: .../gkemcg1-mcs-demo-hello-b-80-...<br>      weight: 20</pre><p>The configuration was correct. To find out how long a route change takes to apply, I changed /split to send everything to cluster-b and polled. Five samples in a row still came from cluster-a, and the first cluster-b answer arrived about 100 seconds after the change. Then I restored 80/20, and the answers did not follow it cleanly: the first batch of 20 had 3 from cluster-b, but the next 200 requests all came from cluster-b, as if the previous rule were back. A few minutes later the split settled, and over 200 requests it measured <strong>157 from cluster-a and 43 from cluster-b</strong>. A second run gave <strong>156 and 44</strong>, against a configured 80 and 20.</p><p>The lesson is the same one as with the mesh, only slower: after changing a route, the load balancer takes minutes to apply it, and results in that window can look like anything. The mixed batches I saw in the middle, 3 of 20 and then 200 of 200, I can describe but not fully explain. My guess is that different front-end servers picked up the new rule at different times, and that is only a guess.</p><p><strong>The load balancer in the Console.</strong> Network services &gt; Load balancing shows the load balancer the Gateway created, an external Application Load Balancer. Its Backends tab lists the backend services for hello, hello-a and hello-b plus two default-response services. The Frontends tab shows a global forwarding rule on HTTP port 80 in the Premium network tier.</p><p>The Gateway, its public address and its load balancer were created for this test and deleted afterwards, in the right order. Step 11 covers that.</p><h3>🧩 Step 9: Extras That Fill in the Gaps</h3><p>With the core fleet features working, I added six more experiments. The weighted Gateway split is already covered in Step 8. Here are the other five, in the order I ran them, starting with three that are about scope and identity.</p><h4>👥 RepoSync: GitOps limited to one namespace</h4><p>A RootSync reconciles whole-cluster configuration. A <strong>RepoSync</strong> belongs to a single namespace, runs its own reconciler, and can only manage objects in that namespace. That makes it the right tool for handing a team a corner of the cluster they can change through Git without being able to touch anything else.</p><p>I created a namespace called team-a on both clusters, gave the RepoSync’s reconciler permission to manage objects there, and pointed the RepoSync at a different folder of the same repository. The reconciler runs as a service account named ns-reconciler-team-a, so the RoleBinding names that:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: syncs-team-a<br>  namespace: team-a<br>subjects:<br>- kind: ServiceAccount<br>  name: ns-reconciler-team-a<br>  namespace: config-management-system<br>roleRef:<br>  kind: ClusterRole<br>  name: edit<br>  apiGroup: rbac.authorization.k8s.io<br>---<br>apiVersion: configsync.gke.io/v1beta1<br>kind: RepoSync<br>metadata:<br>  name: repo-sync<br>  namespace: team-a<br>spec:<br>  sourceFormat: unstructured<br>  git:<br>    repo: https://github.com/bikram-singh/gcp-anthos-fleet<br>    branch: main<br>    dir: team-a-repo<br>    auth: none</pre><p>The folder team-a-repo/ holds one ConfigMap, team-a-config. My first status check right after creating it showed no ConfigMap and a reconciler deployment at 0/1. That was only startup time: the reconciler is created on demand and takes a minute to become ready. A few minutes later team-a-config existed on both clusters.</p><p><strong>Does the scope hold?</strong> I added a file to team-a-repo/ that tried to create a ConfigMap in a different namespace, demo:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: out-of-scope<br>  namespace: demo<br>data:<br>  note: &quot;should be rejected&quot;</pre><p>The RepoSync refused it:</p><pre>KNV1058: Resources in the &quot;team-a&quot; repo must either omit metadata.namespace<br>or declare metadata.namespace=&quot;team-a&quot;</pre><p>Two details are worth noticing. The sync did not break: the SYNCCOMMIT stayed at the last good commit, and the ConfigMap that was already there kept existing, while the SOURCECOMMIT and the error count showed the bad commit. And when I deleted the offending file, the error cleared by itself on both clusters and the sync caught up. A bad commit does not take away what was already synced, and fixing the commit is all the recovery there is.</p><h4>🪪 Workload Identity: a pod reads a bucket with no key</h4><p>The usual way to give a pod access to a Google Cloud API is to create a service account, download a key, and mount it as a secret. That key is a long-lived credential sitting in your cluster. Workload Identity Federation for GKE removes it: a pod’s Kubernetes service account is itself a principal that you can grant IAM roles to directly.</p><p>I created a bucket, put one small file in it, and ran two pods in a namespace called wi-demo, each with its own Kubernetes service account, reader and stranger. Both ran the Google Cloud CLI image. Then I granted read access to the reader identity only, and only on that one bucket:</p><pre>gcloud storage buckets add-iam-policy-binding gs://&lt;bucket&gt; `<br>  &quot;--member=principal://iam.googleapis.com/projects/&lt;PROJECT_NUMBER&gt;/locations/global/workloadIdentityPools/&lt;PROJECT_ID&gt;.svc.id.goog/subject/ns/wi-demo/sa/reader&quot; `<br>  --role=roles/storage.objectViewer</pre><p>Then I tried to read the file from each pod:</p><pre>kubectl exec -n wi-demo reader   -- gcloud storage cat gs://&lt;bucket&gt;/hello.txt<br>hello from a private bucket<br><br>kubectl exec -n wi-demo stranger -- gcloud storage cat gs://&lt;bucket&gt;/hello.txt<br>ERROR: (gcloud.storage.cat) HTTPError 403: Caller does not have storage.objects.get access to the<br>Google Cloud Storage object. Permission &#39;storage.objects.get&#39; denied on resource ...</pre><p>No key file exists anywhere in this setup. The only difference between the two pods is a line in the bucket’s IAM policy. One caution on reading the output: gcloud auth list shows the same account, the pool identity for the whole project, in both pods, so that command does not tell you which Kubernetes service account is which. The proof is the IAM policy plus the two different outcomes. Also, Google’s documentation notes that pods using hostNetwork bypass this mechanism.</p><h4>🧪 A custom ConstraintTemplate written in Rego</h4><p>The built-in library covers a lot, but sooner or later you want a rule that is yours. A ConstraintTemplate holds the logic in Rego, OPA’s policy language. Mine is deliberately simple: require a label on a resource, with the label’s name supplied as a parameter by the constraint.</p><pre>apiVersion: templates.gatekeeper.sh/v1<br>kind: ConstraintTemplate<br>metadata:<br>  name: k8srequireowner<br>spec:<br>  crd:<br>    spec:<br>      names:<br>        kind: K8sRequireOwner<br>      validation:<br>        openAPIV3Schema:<br>          type: object<br>          properties:<br>            label:<br>              type: string<br>  targets:<br>    - target: admission.k8s.gatekeeper.sh<br>      rego: |<br>        package k8srequireowner<br><br>        violation[{&quot;msg&quot;: msg}] {<br>          required := input.parameters.label<br>          not input.review.object.metadata.labels[required]<br>          msg := sprintf(&quot;%v %v is missing the required label &#39;%v&#39;&quot;, [input.review.kind.kind, input.review.object.metadata.name, required])<br>        }</pre><p>The constraint that uses it applies to ConfigMaps in a namespace called policy-lab, in deny mode:</p><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: K8sRequireOwner<br>metadata:<br>  name: configmaps-need-owner<br>spec:<br>  enforcementAction: deny<br>  match:<br>    kinds:<br>    - apiGroups: [&quot;&quot;]<br>      kinds: [&quot;ConfigMap&quot;]<br>    namespaces: [&quot;policy-lab&quot;]<br>  parameters:<br>    label: owner</pre><p>Both files went into config-sync-repo/policies/ and arrived on both clusters through the RootSync, with no extra step. The template reported Created: true with no errors, and an unlabeled ConfigMap was refused on both clusters:</p><pre>Error from server (Forbidden): admission webhook &quot;validation.gatekeeper.sh&quot; denied the request:<br>[configmaps-need-owner] ConfigMap no-owner is missing the required label &#39;owner&#39;</pre><p>A ConfigMap with the label owner: bikram was created normally.</p><p><strong>A finding from the audit.</strong> Before I had created anything, the constraint already reported one violation. The audit had flagged kube-root-ca.crt, a ConfigMap Kubernetes creates in every namespace, which has no owner label. That is a neat illustration of the difference between the two halves of Gatekeeper: the webhook only judges requests as they arrive, while the audit judges what already exists, including objects you did not create and cannot easily label.</p><h4>🏷️ Fleet scopes: a team’s slice of the fleet</h4><p>A <strong>fleet scope</strong> is a way to group clusters and namespaces for a team. You bind member clusters to a scope, and then create a <strong>fleet namespace</strong> inside it. The fleet creates that namespace on every bound cluster for you. I made a scope called team-checkout, bound both clusters to it, and created one fleet namespace:</p><pre>gcloud container fleet scopes create team-checkout<br>gcloud container fleet memberships bindings create checkout-a --membership=cluster-a --scope=team-checkout --location=asia-south1<br>gcloud container fleet memberships bindings create checkout-b --membership=cluster-b --scope=team-checkout --location=asia-southeast1<br>gcloud container fleet scopes namespaces create checkout-ns --scope=team-checkout</pre><p>About half a minute later the namespace existed on both clusters, with labels that show the fleet created it:</p><pre>kubectl get ns checkout-ns --show-labels<br>NAME          STATUS   AGE   LABELS<br>checkout-ns   Active   35s   fleet.gke.io/actuate-deletion=true,fleet.gke.io/actuation-active=true,<br>                             fleet.gke.io/fleet-scope=team-checkout,kubernetes.io/metadata.name=checkout-ns</pre><p>I did not set up access for team members. The convenient helper for that is in the beta command group, which I could not install, and I did not try the RBAC route. So this proves the namespace-on-every-cluster half of fleet scopes and says nothing about the access half.</p><h4>🧱 Binary Authorization in dry-run mode</h4><p>Binary Authorization decides which container images may run in a cluster. In its strict form it blocks any image without a valid attestation. I did not want to block anything, so I used dry-run mode: the policy is evaluated, a would-be denial is written to the audit log, and the pod is admitted anyway.</p><p>I enabled the API, switched the feature on for cluster-b only, and imported a policy that would deny every image but only records the verdict:</p><pre>gcloud services enable binaryauthorization.googleapis.com<br>gcloud container clusters update cluster-b --zone asia-southeast1-a --binauthz-evaluation-mode=PROJECT_SINGLETON_POLICY_ENFORCE<br>gcloud container binauthz policy import binauthz-policy.yaml</pre><pre>globalPolicyEvaluationMode: ENABLE<br>defaultAdmissionRule:<br>  evaluationMode: ALWAYS_DENY<br>  enforcementMode: DRYRUN_AUDIT_LOG_ONLY<br>name: projects/gcp-anthos-fleet/policy</pre><p>I wrote that file with a BOM-free writer rather than a shell redirect, because the redirect operator in Windows PowerShell 5.1 writes UTF-16, and I did not want to find out whether the import accepts that. A few minutes after the import, I created a plain nginx pod. It was admitted and ran. Then I looked for the record of what the policy would have done:</p><pre>gcloud logging read &#39;&quot;image-policy.k8s.io/dry-run&quot;&#39; --project gcp-anthos-fleet --freshness=30m --limit=1 --format=json</pre><p>The audit-log entry for the pod carried two annotations, one marking the evaluation as a dry run and one with the verdict:</p><pre>&quot;imagepolicywebhook.image-policy.k8s.io/dry-run&quot;: &quot;true&quot;,<br>&quot;imagepolicywebhook.image-policy.k8s.io/overridden-verification-result&quot;: &quot;&#39;nginx&#39; : Denied by an ALWAYS_DENY admission rule\n&quot;</pre><p>That is exactly what dry-run is for: you can see what a stricter policy would break before you turn it on. One thing I should have done first: I imported this policy without exporting the project’s original policy, so when I restored it afterwards I had to assume the default, ALWAYS_ALLOW with enforcement on. Export the existing policy before you replace it.</p><h4>🔑 A least-privilege node service account</h4><p>By default, GKE nodes run as the Compute Engine default service account, which in many organizations carries broad permissions. Google’s guidance is to give nodes a dedicated service account with only the roles nodes need: write logs, write metrics and read monitoring data.</p><p>To see whether that actually works, I created a service account called gke-node-min, granted it those three roles (roles/logging.logWriter, roles/monitoring.metricWriter and roles/monitoring.viewer), and added a <strong>temporary extra node pool</strong> to cluster-b that used it. I did not replace the primary pool, because that would have rescheduled every workload on the cluster.</p><pre>gcloud container node-pools create lp --cluster cluster-b --zone asia-southeast1-a --num-nodes 1 `<br>  --machine-type e2-medium --service-account gke-node-min@&lt;PROJECT_ID&gt;.iam.gserviceaccount.com --node-labels pool=least-priv</pre><p>The node was already Ready when I first listed it, 42 seconds old, with no external IP. The instance listed gke-node-min as its service account, and an nginx pod pinned to the node with a nodeSelector pulled its image and reached Running. I then deleted the pod and the pool.</p><p>What this proves is that a node can register and run workloads with only those three roles. What it does not prove, because I did not check, is that logs and metrics from that node actually reached Cloud Logging and Cloud Monitoring, which is what those roles are for. And the primary node pools still use the default service account.</p><h3>🔍 Step 10: Closing the Caveats</h3><p>By this point the lab had four caveats I did not like leaving as assertions: the organization policy behind the private-node design, the way Config Sync was set up, the node service account question, and the fact that the mesh demo had only run on one cluster. I tested what could be tested.</p><p><strong>Proving the organization policy.</strong> I had said the policy blocks external IPs. Rather than repeat that, I asked Google for the effective policy and then tried to break it:</p><pre>gcloud resource-manager org-policies describe compute.vmExternalIpAccess --project gcp-anthos-fleet --effective<br>constraint: constraints/compute.vmExternalIpAccess<br>listPolicy:<br>  allValues: DENY<br><br>gcloud compute instances create ip-test --zone asia-south1-a --machine-type e2-micro `<br>  --network=anthos-fleet-vpc --subnet=subnet-cluster-a --project gcp-anthos-fleet<br>ERROR: (gcloud.compute.instances.create) Could not fetch resource:<br> - Constraint constraints/compute.vmExternalIpAccess violated for project &lt;PROJECT_NUMBER&gt;.<br>   Add instance projects/gcp-anthos-fleet/zones/asia-south1-a/instances/ip-test to the constraint<br>   to use external IP with it.</pre><p>allValues: DENY means no virtual machine in the project may have an external IP, with no allow-list. Nothing was created, so there was nothing to clean up. That is the constraint that forced the design in Step 2, now shown directly. My first attempt at this command actually failed for a different reason, my own: I wrote the network and subnet as one comma-separated value, and PowerShell split it at the comma. A reminder that the shell is a layer you also have to get right.</p><p><strong>What the fleet thinks Config Sync is doing.</strong> In Step 4 I set Config Sync up with a RootSync created by kubectl. I wanted to see how the fleet’s own record looked, so I ran the read-only describe command, the one in the GA command group that I could actually run:</p><pre>gcloud container fleet config-management describe --project gcp-anthos-fleet<br>name: projects/gcp-anthos-fleet/locations/global/features/configmanagement<br>resourceState:<br>  state: ACTIVE<br>spec: {}</pre><p>The feature is ACTIVE, but its spec is empty and there is no per-cluster state in the output. Compare that with the mesh and Multi-cluster Services features, which list each membership. This is consistent with a sync that is driven by a RootSync object and not by a fleet-level configuration, so the fleet does not report the sync status here. It does not mean the sync is not working: both clusters reported matching commits. The Console had shown 2 of 2 clusters with Config Sync enabled right after the install, and I did not find out why the CLI view does not show that. I am recording it as an unexplained difference.</p><p><strong>Who the nodes run as.</strong> The node pools use the Compute Engine default service account. I wanted to know what that account can do in this organization, so I looked for role bindings on it at every level of the hierarchy:</p><pre>$anc = gcloud projects get-ancestors-iam-policy gcp-anthos-fleet --format=json | ConvertFrom-Json<br>$anc | ForEach-Object { &quot;$($_.type) $($_.id)  bindings: $(@($_.policy.bindings).Count)&quot; }<br>project gcp-anthos-fleet  bindings: 30<br>organization &lt;ORG_ID&gt;     bindings: 12</pre><p>The hierarchy has two levels, the project and the organization, with no folder in between. Searching all of those bindings for the default service account found nothing: it has no direct roles anywhere. A related organization policy is enforced, which would explain why the project did not hand it the usual Editor role:</p><pre>gcloud resource-manager org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --project gcp-anthos-fleet --effective<br>booleanPolicy:<br>  enforced: true</pre><p>I will be careful about what that proves. It shows that no role is bound to the account directly, and that a policy exists that is consistent with that. It does not cover deny policies or access granted through groups, which I did not check, and the policy applies when a project is created, so it is a likely explanation and not a proven one.</p><p><strong>The mesh on the second cluster.</strong> The mesh demo only ran on cluster-b. Repeating it on cluster-a was possible, about half an hour of work, but it would have kept the clusters and the load balancer billing, and I chose to leave it as a stated limit.</p><h3>🧹 Step 11: Teardown and Cost</h3><p>Teardown order matters in a fleet. Google’s documentation warns that turning off fleet ingress while a Gateway still exists can leave load balancer resources behind, and those resources bill. So I took the pieces down from the outside in.</p><p><strong>1. The Gateway first.</strong> I deleted the HTTPRoute and then the Gateway, and checked what the controller had cleaned up:</p><pre>kubectl --context &lt;cluster-a&gt; delete httproute hello-route -n mcs-demo<br>kubectl --context &lt;cluster-a&gt; delete gateways.gateway.networking.k8s.io external-http -n mcs-demo<br>gcloud compute forwarding-rules list --global<br>gcloud compute addresses list --global<br>gcloud compute backend-services list --global --filter=&quot;name~^gkemcg1&quot;</pre><p>Within seconds, the Gateway’s public address was gone and its forwarding rule with it. The backend services and health checks with names starting gkemcg1 were still listed on that first check, and a polling loop a few minutes later found none. Two naming families in that output are not the Gateway’s: resources starting gkemcs belong to Multi-cluster Services, and those starting gsmrsvd belong to the managed mesh. They disappear when those features go away, and you should not delete them by hand.</p><p><strong>2. The exports.</strong> I deleted the four ServiceExport objects, hello and hello-a on cluster-a, hello and hello-b on cluster-b. The MCS feature kept reporting There are 2 ServiceExports in the Fleet for a while after kubectl showed none, which fits Google’s note that MCS cleanup can lag.</p><p><strong>3. The fleet scope objects,</strong> in order: the fleet namespace, then both membership bindings, then the scope. The namespace disappeared from both clusters.</p><p><strong>4. Fleet ingress and MCS.</strong> I disabled fleet ingress without any force flag. When I then checked MCS, it already reported that the feature was not enabled, before my own disable command had run. I do not know what turned it off.</p><p><strong>5. Everything outside Terraform.</strong> The Workload Identity demo bucket, the gke-node-min service account with its three role bindings, and the project-level bindings I had added by hand: the MCS importer in both member formats, and container.admin for the multi-cluster ingress service agent.</p><p><strong>6. Terraform destroy.</strong> I started the destroy through the workflow. After that I decided to stop doing a careful cleanup and shut down the whole project, so I cannot tell you how that destroy run ended. I never confirmed whether it finished.</p><p><strong>Why I shut the project down.</strong> Shutting a project down stops billing for it and starts a 30-day recovery period, after which everything in it is permanently deleted. It also clears in one step everything my teardown could not reach: the state bucket, the CI service account, the Workload Identity pool, the fleet features, and a set of firewall rules (the MCS rules and the mesh health-check rules) that were still in the VPC after MCS was off. Those rules might have blocked the network’s deletion during the destroy. I did not see that happen, so that is a risk I avoided, not a failure I observed.</p><p>The trade-offs are real. The project ID, gcp-anthos-fleet, cannot be reused once the project is fully deleted. The Terraform defaults and the examples in this article use it, so anyone rebuilding needs a new project ID and a fresh bootstrap. And because the state bucket and the Workload Identity pool are gone, the GitHub workflow no longer works until it is re-bootstrapped.</p><p><strong>What shutting it down did to my command line.</strong> Right after the shutdown, a gcloud command that reads from the billing account failed with USER_PROJECT_DENIED and a message that the project had been deleted. gcloud was still using the deleted project as both my active project and the quota project for my default credentials. The fix, once you have a new project, is to set both, or to clear the active project if you have none:</p><pre>gcloud config unset project<br>gcloud config set project &lt;NEW_PROJECT_ID&gt;<br>gcloud auth application-default set-quota-project &lt;NEW_PROJECT_ID&gt;</pre><p>The deleted project was named in two separate places: my active project, and the quota project recorded in my default credentials file. They are different settings, so there are two things to check after a shutdown.</p><p><strong>What it cost.</strong> I have to be honest here: I did not record the project’s real cost, and the numbers I do have are not it.</p><ul><li>At the start of the lab, the trial credit showed 7,869 rupees remaining of 28,694.</li><li>The banner on the Console later showed 6,750.95 rupees, a drop of 1,118.05.</li></ul><p>That drop is not the lab’s cost. It is a billing-account figure, not a project figure, so anything else billed to that account counts too, and it lags behind real usage: it sat unchanged for hours while the clusters and a load balancer were running.</p><p><strong>[Fill in before publishing: the gross total for project gcp-anthos-fleet from Billing &gt; Reports, with a custom date range from 1 October 2026, the project filter set to gcp-anthos-fleet, grouped by service. Read the figure before credits are applied. Billing data lags, so read it again about a day later and note both readings.]</strong></p><p>The cost drivers I would expect are the two clusters’ nodes and cluster fees, Cloud NAT, and while it existed the Gateway’s load balancer. I did not break the cost down by service, so treat that list as an expectation, not a finding.</p><h3>🧭 Where Anthos Fits: Hybrid, Multi-cloud, and When Plain GKE Is Enough</h3><p>Everything in this lab ran on Google Cloud, so “hybrid” here only meant a second region. I used cluster-b as a stand-in for a remote environment, nothing more. This section is reading, not hands-on, and I have marked which facts come from Google’s own documentation and which I could not verify.</p><p><strong>What a fleet can contain.</strong> Google’s <a href="https://docs.cloud.google.com/kubernetes-engine/enterprise/docs/deployment-options">GKE deployment options</a> page, last updated on 30 September 2026 when I read it, lists the environments a fleet can span:</p><ul><li>GKE on Google Cloud, which is what this lab used</li><li>Google Distributed Cloud (GDC), meaning GKE on your own premises: on VMware, on bare metal, and as a connected deployment</li><li>GKE on AWS and GKE on Azure, the multi-cloud products</li><li>Attached clusters, which are third-party Kubernetes clusters registered to your fleet</li></ul><p><strong>Google Distributed Cloud</strong> is the on-premises route. It needs your own servers, which a free trial does not give you, so I could not try it. The fleet idea is the same: GDC clusters are fleet members and appear next to your cloud clusters in the Console.</p><p><strong>Attached clusters</strong> are the lightest way to bring a foreign cluster under the same roof. The deployment-options page lists attaching Amazon EKS clusters, Azure AKS clusters and other conformant clusters. You get a subset of the fleet features, not all of them, and the page carries caveats. One example: to install Policy Controller on an AKS cluster, the Azure Policy add-on must not be installed.</p><p><strong>GKE on AWS and GKE on Azure are on their way out.</strong> Google’s deprecation announcement for <a href="https://docs.cloud.google.com/kubernetes-engine/multi-cloud/docs/aws/deprecations/deprecation-announcement">GKE on AWS</a> says maintenance mode started on 17 March 2025 and that the product is no longer supported from 17 March 2027, when its APIs are disabled. The same date appears for GKE on Azure in the <a href="https://docs.cloud.google.com/service-mesh/docs/supported-platforms">Cloud Service Mesh supported platforms</a> page. Google recommends migrating to GKE or another Kubernetes distribution, and points to attached clusters for anyone who wants to keep using Google Cloud features. In practice this means that if you run Kubernetes on AWS or Azure today, attaching is the route to look at, not starting new GKE on AWS or Azure clusters.</p><p><strong>The name, and the packaging, have shifted.</strong> The platform was renamed from Anthos to GKE Enterprise, and older versions of Google’s setup documentation describe an enterprise tier with a per-vCPU charge. The current deployment-options page reads differently. It is titled simply GKE deployment options. It says that enabling the GKE API gives you access to features including Config Sync, Policy Controller, GKE Identity Service and the security posture dashboard, and that Cloud Service Mesh, Binary Authorization and Multi Cluster Ingress are enabled individually, each with its own pricing guide.</p><p>My own experience in this lab fits that second description better than the first: Config Sync, Policy Controller and the mesh each had their own enabling step. What I did not check is how they were billed, because I never broke the cost down by service. So I cannot tell you today’s per-vCPU rate or whether an enterprise charge applied to my clusters. Check Google’s pricing pages before you budget anything from this article.</p><p><strong>When is plain GKE enough? My read, not Google’s:</strong></p><ul><li><strong>One or two clusters, one team, one cloud.</strong> Config Sync and Policy Controller are the parts that paid for themselves in this lab, and Google’s page lists them as available once the GKE API is enabled. You may not need the multi-cluster machinery at all.</li><li><strong>Many clusters, regions or teams.</strong> This is where the fleet earns its keep: one set of Git-driven config and policy everywhere, services that span regions through MCS and the multi-cluster Gateway, and fleet scopes to give each team its slice.</li><li><strong>Clusters in your own data centre.</strong> Google Distributed Cloud, with the hardware and the operational work that implies.</li><li><strong>Clusters on AWS or Azure.</strong> Attach them.</li></ul><p>The parts of this lab that only a fleet could have done were the multi-cluster ones: the cross-region Service names, the global Gateway and the fleet namespace created on both clusters from one definition.</p><h3>⚠️ Prerequisites and Reproduction</h3><p>This is a reference build, not an installer. It involves a billing account, a GitHub repository and several manual steps. The order below is the one that worked.</p><ul><li>A GCP project with billing enabled. A free trial account worked, and you need permission to create IAM, networking, GKE and fleet resources</li><li>gcloud with kubectl and the gke-gcloud-auth-plugin, and optionally the GitHub CLI, gh</li><li>Terraform 1.5 or newer, though you do not need it locally if you run it through the workflow</li><li>A public GitHub repository. The RootSync reads it with auth: none, and a private repository needs credentials</li><li>Commands in this article are PowerShell. The quoting and encoding notes matter</li><li>Your organization policy may differ. This build tolerates compute.vmExternalIpAccess set to DENY. If yours does not enforce it, you may not need private nodes</li><li>A new project ID. The one used here, gcp-anthos-fleet, was shut down and cannot be reused</li></ul><p><strong>Reproduce 1, clone and set the project ID.</strong></p><pre>git clone https://github.com/bikram-singh/gcp-anthos-fleet.git<br>cd gcp-anthos-fleet<br># set project_id in terraform/variables.tf to your new project ID</pre><p><strong>Reproduce 2, bootstrap once, outside Terraform.</strong> The state bucket, the CI service account and its roles, the Workload Identity pool and provider, and the three GitHub secrets, exactly as in Step 1 of the build log.</p><p><strong>Reproduce 3, plan, read, then apply once.</strong></p><pre>gh workflow run terraform.yml --repo &lt;owner&gt;/gcp-anthos-fleet -f action=plan<br># read the plan, then run ONE apply and do not start another run while it works<br>gh workflow run terraform.yml --repo &lt;owner&gt;/gcp-anthos-fleet -f action=apply</pre><p>Apply takes about 15 minutes. Two runs at the same time collide on the state lock.</p><p><strong>Reproduce 4, turn on the fleet features in the order of the build log.</strong> Config Sync from the Console plus the RootSync from fleet-config/rootsync.yaml, Policy Controller per membership, the managed mesh, Multi-cluster Services with the principal:// IAM binding, the Gateway API on both clusters before fleet ingress, and the extras. The repository README has every command in order.</p><p><strong>Reproduce 5, check each feature after a wait.</strong> This environment needs minutes to settle after a change. Read statuses and counts in a retry loop, not once:</p><pre>kubectl get rootsync,reposync -A                 # SYNCCOMMIT equals SOURCECOMMIT, no errors<br>kubectl get constraints<br>gcloud container fleet mesh describe             # control plane and data plane ACTIVE<br>gcloud container fleet ingress describe          # Ready to use</pre><p><strong>Reproduce 6, tear down in order,</strong> from the outside in, as in Step 11. Do not cancel a destroy once it has started.</p><p>There is no automated test suite in this repository. Verification is done against live GCP with the checks above.</p><h3>🐛 What Went Wrong</h3><p>Most write-ups skip this part. Each row below happened in this lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*7gI7tar84StxDlGbCbeNlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*uAWsXue7MQaW_yAGw20Y_w.png" /></figure><h3>📊 The Real Numbers</h3><p>These come straight from terminal output and Console pages during the lab. Every figure is a single run with samples at least 20 seconds apart, so read the timings as approximate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*AVlXVZxg3D9K3IPIRLhvug.png" /></figure><h3>🚧 Known Limitations</h3><p>Recorded here so nobody has to discover them:</p><ul><li><strong>Single runs.</strong> Every timing and traffic split is one run with samples 20 seconds or more apart.</li><li><strong>Cluster-b only for the mesh work.</strong> Sidecar injection, strict mTLS, the authorization policy, the canary and Binary Authorization ran on cluster-b. The policy demos, deny and audit, ran on both clusters.</li><li><strong>Not everything is in Terraform.</strong> Config Sync install, the RootSync, Policy Controller, the mesh, MCS, fleet ingress, the Gateway API setting on the clusters, the Binary Authorization policy and the demo bucket were applied with gcloud or kubectl.</li><li><strong>Demo manifests are not in the repository.</strong> Only the Config Sync and RepoSync content is stored there.</li><li><strong>The fleet view of Config Sync is empty.</strong> The fleet describe command shows the feature active with an empty spec and no per-cluster state, which is consistent with a RootSync created by kubectl. The Console showed 2 of 2 clusters right after the install, and I did not investigate the difference.</li><li><strong>An unexplained 503.</strong> A VirtualService with a subset-based DestinationRule returned 503. The two-Service version worked and I never found the cause.</li><li><strong>Mesh SLO views were not tried.</strong></li><li><strong>Least-privilege nodes were validated on a temporary pool only.</strong> The primary pools were not replaced, and log and metric delivery from the test node was not verified.</li><li><strong>The node service account check is partial.</strong> It covers direct role bindings at project and organization level, not deny policies or group-based access.</li><li><strong>MCS did not create Cloud DNS zones here,</strong> which differs from the documentation.</li><li><strong>The destroy run’s outcome is unknown.</strong> I shut the project down while cleanup was in progress and never confirmed how the Terraform destroy ended.</li><li><strong>No real cost figure was recorded for the project.</strong> The credit-balance numbers are billing-account figures that lag.</li><li><strong>No automated tests.</strong></li><li><strong>The hybrid and multi-cloud material is reading, not hands-on.</strong> I had no on-premises hardware, and cluster-b stood in for a remote environment only as a second region.</li></ul><h3>✅ Conclusion</h3><p>✅ Two private clusters in two regions, built with Terraform and delivered by a pipeline that holds no cloud keys</p><p>✅ Config Sync reconciling Git into both clusters at two scopes, with drift put back and a bad commit unable to undo what was already synced</p><p>✅ A privileged pod rejected on both clusters, and a custom Rego rule shipped through Git and enforced</p><p>✅ Strict mTLS and a per-identity authorization policy in the mesh, with a measured 447 / 53 canary</p><p>✅ A global Gateway with path routing, health-based failover and a measured 157 / 43 weighted split</p><p>✅ A pod reading a bucket with no key, and its neighbour refused with HTTP 403</p><p>✅ An organization policy proven with a rejected VM instead of just asserted</p><p>✅ A teardown that avoids orphaned load balancer resources, and a project shutdown at the end</p><p>The actual lessons are less about any single feature than about how this kind of environment behaves.</p><p><strong>Most of my wrong conclusions were measured too early.</strong> The mesh took minutes to reach its proxies, the Gateway took ten minutes to serve and minutes more to apply a route change, and MCS endpoints lag behind a scale-down. Three times I saw a result that looked like a bug and was a delay. The habit that fixed it was cheap: wait, then read the source of truth, such as the URL map or the sync status, before concluding anything.</p><p><strong>Check that the command ran.</strong> A scale-up that printed nothing had never taken effect, and I tested against a cluster with no pods for several minutes.</p><p><strong>An organization policy is a design input, not an error.</strong> The external-IP constraint dictated the whole network design, and it is worth proving what a policy says before building around a guess about it.</p><p><strong>Write down what you did not verify.</strong> Several things here, the fleet’s empty Config Sync record, the subset DestinationRule 503, the missing DNS zones, I never explained. They are in the article because a reader who hits the same thing is better off knowing it happened.</p><p><strong>What I would do differently:</strong></p><ul><li>Export the existing Binary Authorization policy before replacing it</li><li>Record the project’s cost by service before tearing anything down, and keep the numbers</li><li>Keep the demo manifests in the repository, not only the Config Sync content</li><li>Run each cleanup step to confirmation instead of moving on to a shutdown while a destroy was in flight</li><li>Repeat the mesh demo on the second cluster</li></ul><h3>📸 Snapshots</h3><p>The screenshots live in the repository under <a href="https://github.com/bikram-singh/gcp-anthos-fleet/tree/main/docs/snapshots">docs/snapshots</a>, grouped by section. Upload them into the matching step when you publish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*2mf9dLWb_qvA3y_IV2ePAw.png" /></figure><p>Not captured: the Workload Identity Federation pool page, the Multi-cluster Services card in Feature manager (the Console had none), constraint violation and webhook denial views, and screenshots of the RepoSync, Workload Identity, custom template, fleet scope and Binary Authorization results. Those are evidenced by terminal output in the article.</p><h3>📚 Sources</h3><ul><li><a href="https://docs.cloud.google.com/kubernetes-engine/enterprise/docs/deployment-options">GKE deployment options</a>, Google Cloud documentation, page last updated 30 September 2026</li><li><a href="https://docs.cloud.google.com/kubernetes-engine/multi-cloud/docs/aws/deprecations/deprecation-announcement">GKE on AWS deprecation announcement</a>, Google Cloud documentation, page last updated 30 September 2026</li><li><a href="https://docs.cloud.google.com/service-mesh/docs/supported-platforms">Cloud Service Mesh supported platforms</a>, Google Cloud documentation, which I read as a search result and did not open in full</li></ul><h3>🔗 Repository</h3><p>The full source code, the Terraform, the Config Sync content, the lab plan and the architecture diagram are at:</p><p><a href="https://github.com/bikram-singh/gcp-anthos-fleet"><strong>gcp-anthos-fleet</strong></a>: A hands-on Anthos and GKE Enterprise fleet lab on a GCP free trial, with measured results and honest caveats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=161856c4d3e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DHG CareTrack: Synthetic Patients, Real Pipeline on GCP]]></title>
            <link>https://medium.com/@bikram23march/dhg-caretrack-synthetic-patients-real-pipeline-on-gcp-6056992fbab6?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6056992fbab6</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 12:47:44 GMT</pubDate>
            <atom:updated>2026-09-30T12:50:44.665Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A real-time healthcare telemetry system built with FHIR, BigQuery ML, Gemini, and Cloud DLP</strong></p><h3>🌟 Introduction</h3><p>This is a real-time healthcare telemetry pipeline on Google Cloud: synthetic wearable-style vitals stream through Pub/Sub and Dataflow, get de-identified inline by Cloud DLP, land in both a FHIR R4 store and BigQuery, get risk-scored by BigQuery ML, get explained in plain language by Gemini 2.5 Flash, and reach a clinician through an IAP-protected portal, an analytics dashboard, an email alert, or an API-key-protected partner integration. Every service below was deployed for real, debugged against real GCP errors, and verified against live infrastructure not a static architecture diagram.</p><p>The one thing that is not real is the patients. Every reading, every report note, every name is synthetically generated. That distinction matters enough that it is worth stating up front and repeating throughout: <strong>no real patient, wearable device, or hospital system is involved anywhere in this build.</strong> The risk score and the Gemini explanation are demonstration outputs, not a medical diagnosis, and not validated by any clinician. What is real is the infrastructure, the data flow, the governance controls, and the failures a genuine reference for what it actually takes to run this kind of system on GCP, not just diagram it.</p><h3>🏥 The Problem, In Plain Terms</h3><p>Wearables and home monitors produce a constant stream of vital signs heart rate, oxygen saturation, blood pressure, temperature. Two things go wrong with a stream like that, and both are fixable if you build for them:</p><p><strong>Nobody can watch every reading, all the time.</strong> A dashboard nobody is staring at is the same as no dashboard. And even when someone does look, a bare number “risk score 1.00” doesn’t tell a clinician what to check first. Pairing a numeric score with a plain-language explanation turns “1.00” into “elevated blood pressure, low oxygen saturation, and a rapid heart rate” something a human can act on immediately.</p><p><strong>Clinical data is sensitive by nature, and “sensitive” has to mean something enforced, not just documented.</strong> A free-text report note can carry a name, a phone number, a location. Access to it has to be restrictable at the level of the specific column that carries it not just “this whole table needs a login” and every read or write against it needs a permanent record.</p><p>This project builds one working answer to both problems on GCP: stream the data, de-identify it inline, store it in both a clinical standard (FHIR) and an analytics engine (BigQuery), score and explain risk automatically, alert a clinician, and expose the results through a portal and an API with the column-level security, audit logging, and encryption controls built in from the start, not bolted on afterward.</p><h3>🧰 Tech Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*04CN-YLeZeAm1sYFi2O43Q.png" /></figure><h3>🏛️ Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZBNSPsE0ONZYhr_GSZU-Q.png" /></figure><pre>[Synthetic Data Generator]  Cloud Run Job, scheduled every 15 min<br> (generator/)                 via Cloud Scheduler<br>          |<br>          v<br>      [Pub/Sub]  --topic: patient-telemetry-raw--  (+ dead-letter topic)<br>          |<br>          v<br>     [Dataflow]  (custom Apache Beam pipeline, streaming)<br> (pipeline/dataflow-beam/)<br>   parse -&gt; DE-IDENTIFY (Cloud DLP, inline DoFn) -&gt; route<br>          |<br>          |-------------------------+-------------------------|<br>          v                                                   v<br>[Cloud Healthcare API]                                   [BigQuery]<br> FHIR Store: Patient,                          observations, diagnostic_reports<br> Observation, DiagnosticReport                  (written directly by Dataflow,<br> resources                                       not via FHIR export)<br>                                                          |<br>                                    - Dataplex/Data Catalog column-level<br>                                      security tags on report_text_redacted<br>                                      and gemini_explanation<br>                                    - Cloud Audit Logs (Data Access) enabled<br>                                      for BigQuery, Healthcare API, DLP<br>                                    - CMEK default key on the dataset<br>                                      (new tables only)<br>                                    - dashboard_* views (never select the<br>                                      tagged columns) feed /analytics<br>                                          |<br>                                          v<br>                          [risk-insight-processor]  (Cloud Run Job, scheduled<br>                          (pipeline/risk-insight-processor/)  :05/:20/:35/:50)<br>                             BigQuery ML  --&gt; numeric ml_risk_score<br>                             Gemini (Vertex AI) --&gt; plain-language explanation<br>                                          |<br>                                          v<br>                                 [risk_assessments table]<br>                                          |<br>                                          |---&gt; [alerting/] Cloud Run Job,<br>                                          |      scheduled :10/:25/:40/:55;<br>                                          |      emails clinician on high risk<br>                                          |      via Gmail API (OAuth), HTML,<br>                                          |      color-coded by risk level<br>                                          v<br>   +-------------------------+-------------------------+<br>   |                                                     |<br>[Clinician Portal]                              [Partner-Clinic API]<br> (portal/backend/)                               (partner-api/backend/)<br> Cloud Run, ingress locked to the load           Cloud Run, API-key auth<br> balancer: real IAP + external HTTPS LB +          (Secret Manager) *and*<br> Cloud Armor + managed SSL cert on                  IAM-restricted (see note)<br> dhg-caretrack.gcpcloudhub.in<br> - patient list, vitals chart (Chart.js),         - GET /patients/{id}/telemetry<br>   Gemini risk insight                            - OpenAPI spec auto-published<br> - /analytics: population dashboard                  at /docs, /openapi.json<br>   (KPIs, risk mix, trends, ingestion),<br>   defined in code, from dashboard_* views</pre><p>Synthetic vitals flow through Pub/Sub and Dataflow, split into a FHIR store and BigQuery, get scored and explained, then reach a clinician through one of three doors: alerting, the portal, or the partner API. Terraform and GitHub Actions sit under all nine boxes, not beside them.</p><h3>🔄 Layer Breakdown</h3><p>The three scheduled jobs are staggered five minutes apart, not run simultaneously, so each stage always has fresh upstream data to work from: the generator fires at :00/:15/:30/:45, risk scoring at :05/:20/:35/:50, and alerting at :10/:25/:40/:55.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*zbBiSDYNoosK62RL7GRyTw.png" /></figure><h3>🧱 What It Does</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*8ybjVvrQXVMEY66XTuC8-A.png" /></figure><h3>🛠️ Under the Hood</h3><p>The core of the Dataflow job parses each event, then immediately de-identifies its free-text report note before anything else touches it inline, as a DoFn, not as a separate service. That design choice matters: it means there is no window where raw text sits in a queue waiting for a downstream de-identification step to catch up.</p><pre>class DeidentifyEvent(beam.DoFn):<br>    def process(self, element):<br>        dlp = dlp_v2.DlpServiceClient()<br>        try:<br>            info_types = [{&quot;name&quot;: t} for t in (<br>                &quot;PERSON_NAME&quot;, &quot;PHONE_NUMBER&quot;, &quot;EMAIL_ADDRESS&quot;,<br>                &quot;LOCATION&quot;, &quot;DATE_OF_BIRTH&quot;, &quot;AGE&quot;)]<br>            response = dlp.deidentify_content(<br>                request={<br>                    &quot;parent&quot;: f&quot;projects/{self.project_id}&quot;,<br>                    &quot;deidentify_config&quot;: {<br>                        &quot;info_type_transformations&quot;: {<br>                            &quot;transformations&quot;: [{<br>                                &quot;primitive_transformation&quot;: {<br>                                    &quot;replace_with_info_type_config&quot;: {}<br>                                }<br>                            }]<br>                        }<br>                    },<br>                    &quot;inspect_config&quot;: {&quot;info_types&quot;: info_types},<br>                    &quot;item&quot;: {&quot;value&quot;: element[&quot;report_text&quot;]},<br>                })<br>            element[&quot;report_text_redacted&quot;] = response.item.value<br>        except Exception:<br>            # Fail safe, not fail open: never store the raw text on error.<br>            element[&quot;report_text_redacted&quot;] = &quot;[unavailable - de-identification failed]&quot;<br>        yield element</pre><p>One consequence of this design is honest to report: the generator’s synthetic report templates are generic clinical phrases with no names, dates, or contact details baked in, so DLP typically finds nothing to redact in this demo’s data. The call still runs successfully on every event proving the pipeline integration genuinely works end to end but there is rarely visible redacted output to point to as evidence. A real deployment, with real free text, would see this control actively rewriting content on a regular basis.</p><p>The risk label itself is a deliberately simple rule, used only so BigQuery ML has something structured to train a logistic regression against:</p><pre>CASE<br>  WHEN bp_systolic &gt;= 145 OR heart_rate &gt;= 100 OR spo2 &lt;= 94 THEN 1<br>  ELSE 0<br>END AS high_risk_label</pre><p>A rule this simple has a real consequence, covered honestly under Known Limitations below: because the model’s only ground truth is a deterministic function of the same inputs it scores on, it separates the classes almost perfectly. Every score this build has produced, at two decimal places, has been 0.00 or 1.00 the medium band is defined but has never once been populated.</p><h3>🧠 The AI Layer</h3><p>Two different kinds of intelligence do two different jobs here, deliberately not one model doing everything. BigQuery ML produces a quantitative score a trained model’s numeric output. Gemini produces a qualitative, human-readable explanation of that score, grounded in the patient’s actual readings and report text. Using both demonstrates knowing when to reach for a trained ML model versus an LLM, rather than defaulting to an LLM for a task a simple model already handles well.</p><p>Calling Gemini turned out to have its own real gotcha: gemini-2.0-flash-001, the model this build originally targeted, was retired on June 1, 2026 discovered mid-build, after this project&#39;s own knowledge cutoff. The fix was switching to gemini-2.5-flash, called through the current google-genai SDK rather than the older vertexai.generative_models module, which was separately deprecated and removed on June 24, 2026:</p><pre>from google import genai<br><br>client = genai.Client(vertexai=True, project=project_id, location=&quot;us-central1&quot;)<br><br>response = client.models.generate_content(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    contents=prompt,<br>)<br>explanation = response.text</pre><p>Here is a real explanation this pipeline generated during the build, from an actual high-risk assessment not a hand-crafted example:</p><p><em>“The elevated systolic and diastolic blood pressure, along with an increased heart rate, are notable. Additionally, the oxygen saturation is low and the BMI is in the overweight range, collectively contributing to the high risk assessment.”</em></p><p>Both the score and the explanation land in a risk_assessments table, from which the alerting job, the clinician portal, and the analytics dashboard all read but never the same way. The dashboard&#39;s data source is deliberately built on views that never select gemini_explanation at all, which is covered in Security and Governance below.</p><h3>🎯 A Real Run: What Verification Looked Like</h3><pre>#1  Cloud Scheduler fires the generator every 15 minutes<br>    -&gt; gcloud scheduler jobs list --location=us-central1<br>    -&gt; ENABLED, recent lastAttemptTime on all three jobs<br><br>#2  gcloud dataflow jobs describe &lt;job-id&gt; --region=us-central1<br>    -&gt; JOB_STATE_RUNNING, dhg-caretrack-telemetry-pipeline-v7<br><br>#3  SELECT patient_id, heart_rate, spo2, bp_systolic, event_timestamp<br>    FROM dhg_caretrack.observations ORDER BY event_timestamp DESC LIMIT 10<br>    -&gt; real per-patient readings, one row per generator run<br><br>#4  A risk-processor run scores a patient at 1.00<br>    -&gt; risk_assessments row + a real Gemini explanation, logged<br><br>#5  The alerting job sends a real HTML email through the Gmail API<br>    -&gt; received, HIGH badge, color-coded, matching the risk level<br><br>#6  Sign-in at https://dhg-caretrack.gcpcloudhub.in through IAP<br>    -&gt; the direct Cloud Run URL returns 404; only the load balancer works<br><br>#7  Invoke-RestMethod against the Partner API<br>    -&gt; 200 with a valid X-API-Key, 401 without one<br><br>#8  gcloud run jobs executions list --job=dhg-caretrack-risk-processor<br>    -&gt; succeeded, 1/1, on schedule<br><br>#9  terraform plan after every apply<br>    -&gt; &quot;No changes. Your infrastructure matches the configuration.&quot;</pre><p>Independently, the scoring job itself proved the column-level security control was real, not cosmetic: before its service account was granted the Fine-Grained Reader role on the sensitive-data policy tag, it failed with a genuine 403:</p><pre>google.api_core.exceptions.Forbidden: 403 Access Denied: BigQuery BigQuery:<br>User has neither fine-grained reader nor masked get permission to get data<br>protected by policy tag &quot;dhg-caretrack-sensitive-data : Sensitive Free Text&quot;<br>on column dhg-caretrack.dhg_caretrack.diagnostic_reports.report_text_redacted</pre><p>That error was not staged for this article. It was a genuine blocker hit mid-build, and it is the single strongest piece of evidence in this whole project that the governance controls actually enforce something, rather than just existing in a Terraform file.</p><h3>🛡️ Security and Governance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*bQADnM3tyK3etRsFGVUORg.png" /></figure><p>One governance decision is worth calling out specifically, because it shapes the whole analytics layer discussed next: the BigQuery views behind the dashboard were written to never select the two tagged columns at all, and every column in them is listed explicitly no SELECT *. That means a future tagged column cannot leak into the dashboard by accident, and it means the dashboard&#39;s protection does not depend on remembering to check who is viewing it. The protection is structural, not procedural.</p><h3>📈 The Analytics Dashboard</h3><p>The original design called for a Looker Studio dashboard. It got as far as a report with all three BigQuery data sources connected, and then it was dropped — not because Looker Studio is a bad product, but because it cannot be defined in code. There is no Terraform resource for a Looker Studio report; its API cannot create charts; and its Linking API, which looked at first like a shortcut, turned out to only copy an <em>existing</em> report pointed at a blank one, it rejects the data source aliases outright with “not a valid data source alias.” Every chart would have had to be clicked together by hand, with nothing to review, version, or reproduce.</p><p>Instead, the Clinician Portal now serves a population-level dashboard at /analytics, defined entirely in code and deployed by the same pipeline as the rest of the portal:</p><ul><li><strong>KPI cards</strong>: patients monitored, high risk now, high-risk assessments in the last 24 hours, average heart rate and SpO2, and the age of the newest reading — which doubles as a pipeline health light, turning amber and then red as data goes stale.</li><li><strong>Charts</strong>: the risk-level split, average vitals by hour, assessments per hour by risk level, and readings ingested per 15 minutes a steady bar every 15 minutes is itself proof the generator and pipeline are running without gaps.</li><li><strong>A patient table</strong>, sorted highest risk first, where any value crossing the model’s own risk thresholds is marked in red, and a risk badge computed before a patient’s newest reading arrived is faded with an “updating” pill rather than shown as if it were current.</li><li><strong>Governance by construction</strong>: it reads only the three dashboard_* views, which never select the policy-tagged columns so there is nothing to accidentally expose even if someone shared the wrong screenshot.</li></ul><p>It is private, sitting behind the same IAP that protects the rest of the portal, so there is no public link to hand out only screenshots. That is a real trade-off against the original plan, and it is stated as one rather than glossed over.</p><h3>🔁 CI/CD, and the Night It Almost Deleted Everything</h3><p>GitHub Actions authenticates to GCP through Workload Identity Federationa short-lived OIDC token exchange, restricted to this exact repository, with no downloaded service account key stored anywhere. Two workflows do the work: one plans and applies Terraform, the other rebuilds and redeploys the five application images whenever their own folder changes, deliberately excluding the Dataflow pipeline, whose version bump is a considered decision, not something to trigger on every push.</p><p>The first design was simpler and more dangerous: plan on every push, apply automatically if the plan succeeded. It worked cleanly for a while until a security-and-monitoring change was applied locally (Cloud KMS, Cloud Monitoring, several new IAM grants) but only partially committed. A single unrelated one-line change went to GitHub; the new Terraform modules that had already been applied locally never did.</p><p>CI didn’t know any of that. It saw its own state file which <em>did</em> have the new KMS key, the new alert policy, the new IAM roles sitting next to code that didn’t define any of them. From automation’s point of view, that is indistinguishable from “someone deleted these on purpose.” It planned to tear all of it down, including the CI identity’s own permissions.</p><p>The fix was not “commit more carefully.” It was structural: <strong>pushes now only run </strong><strong>terraform plan. Applying is a separate, deliberate, manual step triggered by hand from the Actions tab and that manual apply refuses to run at all if its own plan contains a single delete or replace, unless a person explicitly ticks a box saying so.</strong> The unpushed files were the tell: git status showed two new Terraform modules sitting untracked, and the commit that had gone out contained one file where it should have contained ten. A local terraform plan showed exactly what would have been destroyed; re-applying it locally restored all eight resources, no data touched.</p><p>No automation should have the standing authority to delete infrastructure it merely suspects should not exist. It should have to ask, every single time and that is the actual design lesson this incident produced, not just the specific fix.</p><h3>🚧 Known Limitations</h3><p>Recorded here so nobody discovers them the hard way:</p><ul><li><strong>Risk scores are effectively binary.</strong> The label the model trains on is a deterministic rule over the same inputs it scores, so scores land on 0.00 or 1.00 and the medium band never populates. A demonstration, not a validated clinical model.</li><li><strong>No automated unit-test suite yet.</strong> Verification throughout this build was done against live GCP, not a test harness.</li><li><strong>Not everything is in Terraform.</strong> The base BigQuery views and the BQML model are created by running SQL files by hand, and the Dataflow workers’ IAM grants were applied with gcloud rather than codified a fresh project needs those added manually.</li><li><strong>CMEK covers new BigQuery tables only.</strong> The four existing tables and the Pub/Sub topics still use Google-managed encryption; changing a live topic’s key forces Terraform to destroy and recreate it, which was not worth the risk this late in the build.</li><li><strong>VPC Service Controls was not attempted</strong>, deliberately it is an org-level, all-or-nothing control that can lock out every live service simultaneously if misconfigured.</li><li><strong>The Partner API is IAM-restricted as well as key-protected</strong>, because this organization’s policy blocks fully public Cloud Run access a truly anonymous external caller cannot reach it today.</li><li><strong>The analytics dashboard is private</strong> and can only be shown through screenshots, not a shareable link.</li><li><strong>Alert volume isn’t fully solved.</strong> A 15-minute schedule with a one-hour lookback re-sends the same high-risk assessments across overlapping runs; this was manageable enough to leave for a later pass, and the scheduler was simply paused once it stopped being manageable.</li><li><strong>The </strong><strong>patients BigQuery table is empty.</strong> The pipeline writes patient records to the FHIR store only; nothing populates the BigQuery table with the same schema.</li></ul><h3>✅ Conclusion</h3><ul><li>Real-time streaming pipeline, Pub/Sub to Dataflow to a FHIR store and BigQuery, fully live-tested</li><li>Cloud DLP de-identification running inline, on every event, not bolted on afterward</li><li>BigQuery ML risk scoring paired with Gemini 2.5 Flash explanations, the right tool for each half of the job</li><li>Column-level security that genuinely denies access proven by the pipeline’s own service account hitting the exact 403 a real intruder would</li><li>A clinician portal and an analytics dashboard, both defined in code, both behind real Identity-Aware Proxy</li><li>A partner-clinic API behind an API key and Secret Manager, with an auto-published OpenAPI spec</li><li>Fully Terraform-managed, including IAM, networking, KMS, and the CI/CD trust relationship itself</li><li>Keyless GitHub Actions via Workload Identity Federation, restructured after a real incident into a design that refuses to delete anything without explicit human consent</li></ul><p>What this build actually proves is smaller and more honest than “a healthcare platform”: it is that the individual pieces of a defensible architecture de-identification, column-level access control, audit logging, encryption, keyless CI, a change-safety net can be made to work together, for real, against a real cloud, with real failures along the way. The synthetic patients were never the point. The infrastructure was.</p><h3>📸 Snapshots</h3><p>Real console and browser captures from the actual build nothing simulated. The full set, organised by area, is in <a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots"><strong>docs/snapshots/</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1QTKEQT6JxR_MWTdo4f8Mg.png" /></figure><ul><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/analytics"><strong>analytics/</strong></a> — the /analytics dashboard and the patient detail page it links to</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/data-pipeline"><strong>data-pipeline/</strong></a> — Dataflow job, Pub/Sub, BigQuery, Healthcare API / FHIR store</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/ai-ml"><strong>ai-ml/</strong></a> — BigQuery ML model training and scoring, Gemini-generated risk explanations</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/alerting"><strong>alerting/</strong></a> — a real high-risk alert email sent by the alerting service</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/compute"><strong>compute/</strong></a> — Cloud Run services and jobs, Cloud Scheduler, Artifact Registry, and the portal&#39;s ingress locked to the load balancer</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/networking"><strong>networking/</strong></a> — VPC, load balancer, Cloud DNS, managed SSL certificate</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/security-governance"><strong>security-governance/</strong></a> — IAM, policy tags, audit logs, Cloud Armor, IAP, Secret Manager, the KMS key and its use as the BigQuery default, and the Monitoring alert</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/cicd"><strong>cicd/</strong> </a>— Workload Identity Federation, GitHub Actions runs, and the versioned Terraform state bucket</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/portal-access-demo"><strong>portal-access-demo/</strong></a><strong> </strong>— the portal&#39;s patient list, the IAP sign-in flow, and the DNS fix that unblocked the custom domain</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/oauth-setup"><strong>oauth-setup/</strong></a> — OAuth consent screen and client configuration for the alerting service and IAP</li><li><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo/tree/main/docs/snapshots/billing-and-registry"><strong>billing-and-registry/</strong></a><strong> </strong>— billing account linkage and GCS bucket setup</li></ul><h3>🔗 Repository</h3><p><a href="https://github.com/bikram-singh/dhg-clinical-insights-demo">dhg-clinical-insights-demo</a> — the full source: Terraform, the pipeline, the portal, the partner API, and every document referenced above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6056992fbab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Real DMS Migration, Built From a Home Network: On-Prem SQL Server to GCP Cloud SQL for PostgreSQL]]></title>
            <link>https://medium.com/@bikram23march/a-real-dms-migration-built-from-a-home-network-on-prem-sql-server-to-gcp-cloud-sql-for-postgresql-017f4f2f5ab7?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/017f4f2f5ab7</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 15:46:08 GMT</pubDate>
            <atom:updated>2026-09-25T16:31:27.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbyaQU7CEecxMz9WgD7ByA.png" /></figure><p><strong>🔗 Companion repository:</strong> <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration">onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration</a> — full setup guides, exact commands, and 146 screenshots for every step below.</p><ul><li>📄 <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-strongswan-setup-guide.md">strongSwan / VPN gateway setup guide</a></li><li>📄 <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-sqlserver-setup-guide.md">SQL Server VM setup guide</a></li><li>📸 <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots">146 snapshots, organized by phase</a></li></ul><p>Most migration tutorials show you the happy path click here, click there, done in ten minutes. This isn’t that. This is what actually happens when you build a real on-prem-to-cloud migration from a home network: two Hyper-V VMs, a hand-rolled Cloud VPN connection, a subtle networking bug that took hours to trace, a missing BGP route that silently broke Database Migration Service, and finally, a working pipeline moving four SQL Server databases into Cloud SQL for PostgreSQL.</p><p>If you’re planning something similar or just want to see what real troubleshooting looks like instead of a sanitized console walkthrough this is the whole thing, start to finish, with nothing smoothed over.</p><h3>Why I Built This</h3><p>There’s a specific kind of learning that only happens when nothing is handed to you pre-configured. Anyone can follow a quickstart guide where the source database is already sitting in a neighboring GCP project with connectivity already solved. Almost nobody documents what happens when your source is a single Windows machine on a home Wi-Fi connection with a dynamic public IP, no static addressing, no business-grade router, and no existing VPN infrastructure of any kind.</p><p>That gap is exactly why this project exists: to build a <strong>genuine</strong> on-prem-to-GCP migration, from the actual physical and network constraints most home labs and small businesses start with, using nothing but free and open-source software on the on-prem side, and Google’s managed services on the cloud side.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urHWJx8qh_N0kIFbxMG6Rg.png" /></figure><pre>[Home Network — Wi-Fi, dynamic public IP]<br>        │<br>        ├── Ubuntu-strongswan-vm (Hyper-V, Default Switch)<br>        │     strongSwan (IPsec) + FRR (BGP)<br>        │     → HA VPN tunnels to GCP<br>        │<br>        └── Ubuntu-sqlserver-vm (Hyper-V, Default Switch)<br>              SQL Server 2025 on Linux<br>              5 databases: MyDatabase, LibraryDB,<br>              HospitalDB, InventoryDB, SchoolDB<br>                    │<br>                    │ (same NAT&#39;d subnet as strongswan-gw,<br>                    │  advertised to GCP via BGP)<br>                    ▼<br>[GCP: HA VPN Gateway] ── [VPC: my-vpc] ── [Cloud SQL for PostgreSQL: my-postgres]<br>                              │<br>                              └── [DMS: Private Connectivity → Conversion Workspace → Migration Jobs]</pre><p>Two deliberate decisions shaped everything downstream, and they’re worth stating up front because the rest of the article keeps referring back to them:</p><ol><li><strong>Two separate VMs, not one.</strong> A VPN gateway and a database server are different roles with different failure modes. Keeping them apart matches real production architecture, and — as you’ll see — it sidesteps a genuinely ugly double-NAT/port-forwarding problem.</li><li><strong>SQL Server on Linux, not Windows.</strong> The natural instinct is to just point the migration at whatever’s already running. But the “obvious” source — SQL Server on the Windows Hyper-V host itself — sits on a different network path than the VPN gateway, which would have meant DNAT rules and real complexity. Running SQL Server 2025 natively on Ubuntu, inside a VM on the <em>same</em> subnet as the gateway, made it directly reachable with zero extra routing tricks.</li></ol><h3>Part 1: Building the Two VMs in Hyper-V</h3><h4>The Wi-Fi trap</h4><p>The first VM, Ubuntu-strongswan-vm (hostname later set to strongswan-gw), was created the standard way: Hyper-V Manager → New → Virtual Machine, Generation 1, 2048 MB of Dynamic Memory, a 40 GB dynamically-expanding VHDX, Ubuntu Server ISO attached as the install source.</p><p>For networking, the obvious first instinct was an <strong>External Switch</strong> — bridge the VM directly onto the physical network, so it looks like just another device on the LAN. It failed immediately. Inside the VM, eth0 showed &quot;not connected,&quot; and DHCP autoconfiguration never completed.</p><p>The root cause took a moment to place: OPTIPLEX-PC (the physical host) connects to the internet over <strong>Wi-Fi</strong>, not the wired Ethernet port. The External Switch had been dutifully bound to a physical Ethernet adapter that had no cable plugged into it at all — a completely dead link. And even if a cable <em>had</em> been available, Hyper-V’s Wi-Fi bridging support is separately known to be unreliable: Microsoft ships a “Wi-Fi Direct Virtual Adapter” mechanism meant to make this work, but it frequently fails to hand the guest VM a working IP, and in some cases can disrupt the <em>host’s own</em> Wi-Fi connection mid-attempt.</p><p>The fix was switching to <strong>Default Switch</strong> instead — Hyper-V’s built-in NAT-based virtual switch. Unlike External Switch, it doesn’t try to bridge a physical adapter at all; Windows manages the NAT translation itself, which means it works identically whether the host is on Wi-Fi or Ethernet. The moment the VM’s network adapter was reassigned from ExternalSwitch to Default Switch, eth0 picked up a real DHCP-assigned address in the 172.24.x.x/20 range, with working internet access.</p><p><strong>VM 1 — </strong><strong>strongswan-gw</strong></p><p>With networking sorted, the rest of the Ubuntu Server install followed a standard flow: English language, default keyboard layout, “Use an entire disk” for storage with LVM enabled and <strong>LUKS encryption deliberately left unchecked</strong> — a LUKS passphrase prompt on every boot would block headless, unattended startup, which is fatal for a server VM you can’t always sit in front of.</p><p>Profile setup used username bikram and server name strongswan-gw. The single most important checkbox in the entire install was easy to miss: <strong>&quot;Install OpenSSH server.&quot;</strong> Without it, there&#39;s no way to manage a VM with no attached display once the install finishes — you&#39;d be stuck working exclusively through the (much clunkier) Hyper-V console window for everything that follows.</p><p><strong>VM 2 — </strong><strong>Ubuntu-sqlserver-vm</strong></p><p>Same install flow, same Default Switch decision, but sized differently to match its heavier workload: <strong>4096 MB</strong> of memory (SQL Server needs real headroom that the lightweight gateway VM never will) and a <strong>127 GB</strong> virtual disk. Hostname: ubuntu-sqlserver.</p><p>Both VMs landed cleanly inside 172.24.96.0/20 — strongswan-gw at 172.24.107.2, ubuntu-sqlserver at 172.24.100.130. This shared subnet becomes the single most load-bearing detail in the entire architecture: it&#39;s the one range that eventually gets advertised to GCP over BGP, and it&#39;s precisely <em>why</em> putting SQL Server in its own VM on this subnet — rather than leaving it on the Windows host, which sits outside this range entirely — avoids needing any port-forwarding at all.</p><p>📄 Full command-by-command build for both VMs: <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-strongswan-setup-guide.md">strongSwan / VPN gateway guide</a> · <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-sqlserver-setup-guide.md">SQL Server VM guide</a></p><h3>Part 2: SQL Server 2025 on Linux</h3><p>Installing SQL Server on Ubuntu turned out to be refreshingly close to installing any other Linux package — a world away from the Windows installer’s VC++ Redistributable dance that had actually caused real friction earlier in the on-prem setup (a known SQL Server 2025 issue requiring a <em>repair</em>, not just an install, of the Visual C++ 2015–2022 Redistributable before setup would proceed).</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install -y wget curl gpg gnupg2 software-properties-common apt-transport-https lsb-release ca-certificates<br>curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg<br>curl -fsSL https://packages.microsoft.com/config/ubuntu/24.04/mssql-server-2025.list | sudo tee /etc/apt/sources.list.d/mssql-server-2025.list<br>sudo apt update<br>sudo apt install -y mssql-server<br>sudo /opt/mssql/bin/mssql-conf setup</pre><p>The setup wizard prompts for an edition — <strong>4 (Express)</strong> was chosen specifically to match what the original Windows instance ran, sets the sa password, and starts the mssql-server systemd service automatically once license terms are accepted.</p><p>One detail worth flagging for anyone following along: this used Microsoft’s Ubuntu <strong>24.04</strong> repository track — the officially GA-supported version — even though the VM itself was running Ubuntu <strong>26.04</strong>. Technically an unsupported combination. In practice, it installed and ran without a single compatibility hiccup, which is worth knowing if you’re on a similarly bleeding-edge distro release and hesitant to try.</p><p>Command-line tools (sqlcmd) followed the identical repository-registration pattern:</p><pre>curl -fsSL https://packages.microsoft.com/config/ubuntu/24.04/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list<br>sudo apt update<br>sudo apt install -y mssql-tools18 unixodbc-dev<br>echo &#39;export PATH=&quot;$PATH:/opt/mssql-tools18/bin&quot;&#39; &gt;&gt; ~/.bashrc<br>source ~/.bashrc</pre><h4>Rebuilding five databases from scratch</h4><p>The original Windows instance carried five sample databases with real relational structure — foreign keys, indexes, realistic row counts:</p><ul><li><strong>MyDatabase</strong> — an HR/sales dataset: Departments, Employees, Projects, EmployeeProjects, Customers, Products, Orders, OrderDetails</li><li><strong>LibraryDB</strong> — Books, Members, Loans</li><li><strong>HospitalDB</strong> — Doctors, Patients, Appointments</li><li><strong>InventoryDB</strong> — Warehouses, Items, StockMovements</li></ul><p>Rather than transferring .sql files across the network, both setup scripts were recreated directly on the VM through an SSH session, using a tee heredoc:</p><pre>cat &gt; multi_db_setup.sql &lt;&lt; &#39;SQLEOF&#39;<br>-- full T-SQL: CREATE DATABASE, CREATE TABLE, INSERT statements for<br>-- LibraryDB, HospitalDB, InventoryDB<br>SQLEOF<br>sqlcmd -S localhost -U sa -P &#39;YourSAPassword&#39; -C -i multi_db_setup.sql</pre><p>This choice wasn’t arbitrary — it came directly out of a real, repeated annoyance: both vi and nano kept mangling multi-line pastes over SSH (missing characters, garbled indentation, occasional dropped lines mid-paste), while a tee-based heredoc handled every large paste cleanly, every single time, across dozens of similar operations throughout this project. If you&#39;re doing heavy SSH-based scripting work, this is a small habit worth adopting early.</p><p>A full row-count verification query across all fifteen tables confirmed an exact match against the original Windows dataset — 30 employees, 5 departments, 12 books, 6 doctors, 4 warehouses, and so on down the list, all fifteen numbers matching precisely.</p><p><strong>Proving remote reachability before GCP ever enters the picture</strong></p><p>One check mattered more than it might initially seem: confirming SQL Server was actually listening on <em>all</em> network interfaces, not just localhost.</p><pre>sudo ss -tlnp | grep 1433<br># LISTEN 0.0.0.0:1433 ...<br># LISTEN *:1433 ...</pre><p>And then proving it from a genuinely separate machine — SSH’d into strongswan-gw, installed the same client tools there, and connected across the network to 172.24.100.130:1433. A clean SQL Server version banner came back immediately. That&#39;s precisely the kind of cross-machine access DMS would eventually need to replicate from much further away (from inside Google&#39;s network, through a VPN tunnel) — confirming it worked at the shortest possible distance first, before adding layers of complexity on top, saved a lot of guesswork later when things did break.</p><p>📄 Full command sequence, both setup scripts, and the complete verification query: <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-sqlserver-setup-guide.md">SQL Server VM setup guide</a></p><h3>Part 3: Cloud VPN — Building the GCP Side</h3><p>This is the part that deserves its own dedicated section, because it’s easy to undersell just how much of this project’s real complexity lives here.</p><h4>HA VPN vs. Classic VPN</h4><p>Google Cloud offers two flavors of Cloud VPN. <strong>Classic VPN</strong> is the older option — supports only static routing, single-tunnel by default, and is generally considered legacy for new deployments. <strong>HA VPN (High-Availability VPN)</strong> is the modern, recommended choice: it supports dynamic routing via BGP, and — critically — it’s architected from the ground up as a <strong>two-interface resource</strong>, specifically so that a properly configured HA VPN gateway maintains two independent tunnel paths for a 99.99% SLA.</p><p>That two-interface design is the single fact that shapes almost everything else in this section, including a warning message that initially looked like something had gone wrong.</p><h4>Creating the HA VPN Gateway</h4><p>In the GCP Console: <strong>Network Connectivity → VPN → Create a VPN → High-availability (HA) VPN.</strong></p><ul><li><strong>Name:</strong> home-vpn-gateway</li><li><strong>Network:</strong> my-vpc</li><li><strong>Region:</strong> us-central1</li><li><strong>IP version:</strong> IPv4</li><li><strong>IP stack type:</strong> IPv4 (single-stack)</li></ul><p>The moment this gateway is created, Google auto-allocates <strong>two external IP addresses</strong> — one per interface — regardless of how many tunnels you end up building. In this project, those came out to 35.242.125.164 (interface 0) and 34.184.18.124 (interface 1). Both of these IPs exist from the very first click, whether or not a tunnel is ever attached to the second one.</p><h4>Defining the peer gateway</h4><p>GCP needs to know what it’s tunneling <em>to</em>. Under <strong>Peer VPN gateway</strong>, the option <strong>“On-prem or Non Google Cloud”</strong> was selected, and a new peer gateway resource was created — named home-strongswan-gw — representing the home network&#39;s own endpoint. Since this is a genuine home network with a single public-facing connection (not a redundant multi-ISP setup), it was configured with <strong>one interface</strong>, pointed at the home network&#39;s actual public IP.</p><p>Finding that IP required nothing more elaborate than:</p><pre>curl -4 ifconfig.me</pre><pre>106.219.121.170</pre><p>That single IP address is what GCP’s peer gateway resource is built around — it’s the identity GCP uses to recognize which incoming connection attempts are legitimately from this home network’s tunnel.</p><h4>The first tunnel</h4><p>With both the local gateway and the peer gateway defined, the first VPN tunnel was created:</p><ul><li><strong>High availability:</strong> “Create a single VPN tunnel” (deliberately — see below for why this changed)</li><li><strong>Routing:</strong> Dynamic (BGP)</li><li><strong>Cloud Router:</strong> a new router, home-vpn-router, ASN 65001</li><li><strong>Associated Cloud VPN gateway interface:</strong> 0 : 35.242.125.164</li><li><strong>Associated peer VPN gateway interface:</strong> 0 : 106.219.121.170</li><li><strong>Name:</strong> home-tunnel-1</li><li><strong>IKE version:</strong> IKEv2</li><li><strong>Pre-shared key:</strong> generated via GCP’s own key generator</li></ul><p>That pre-shared key deserves its own callout: GCP shows it to you <strong>exactly once</strong>, with an explicit warning that it cannot be retrieved after the form closes. Losing it isn’t catastrophic, but it does mean deleting and recreating the tunnel from scratch to set a new one — GCP doesn’t support editing a tunnel’s shared secret after creation, on the theory that a secret you can rotate through the UI isn’t really a secret. (This happened during the build — the original key wasn’t saved, and the tunnel had to be deleted and recreated with a fresh key that <em>was</em> properly recorded.)</p><p>Configuring the BGP session that rides on top of this tunnel produced a pair of <strong>link-local addresses</strong> (from the 169.254.0.0/16 range reserved for exactly this purpose) — 169.254.193.169 on GCP&#39;s Cloud Router side, 169.254.193.170 on the peer side — with the peer&#39;s ASN set to 65002, deliberately different from the Cloud Router&#39;s own 65001, since BGP fundamentally requires two distinct autonomous systems on either end of a session.</p><p><strong>The warning that wasn’t actually a failure</strong></p><p>Once home-tunnel-1 was up and the VM-side configuration (covered in Part 4) had it fully ESTABLISHED, GCP&#39;s Console displayed a persistent, easy-to-misread warning:</p><p><em>“The following HA VPN tunnels are not properly configured: home-tunnel-1.”</em></p><p>This is worth being precise about, because it’s the single easiest part of this whole project to describe wrong. <strong>home-tunnel-1 was never broken.</strong> At no point did it stop working, drop its connection, or fail to carry traffic. The warning is Google&#39;s Console simply reminding you that an HA VPN gateway, by design, has two interfaces — and you&#39;ve only attached a tunnel to one of them. It&#39;s a configuration-completeness warning, not a health alert.</p><p>The fix was adding a <strong>second tunnel</strong>, home-tunnel-2, to the <em>same</em> peer gateway, this time on the gateway&#39;s other interface:</p><ul><li><strong>Associated Cloud VPN gateway interface:</strong> 1 : 34.184.18.124</li><li><strong>Associated peer VPN gateway interface:</strong> 0 : 106.219.121.170 (same single home IP — one peer, tunneled from both of GCP&#39;s interfaces)</li><li>Same Cloud Router (home-vpn-router), same pre-shared key for simplicity</li><li><strong>Name:</strong> home-tunnel-2</li></ul><p>This produced its own independent BGP session, with its own link-local pair: 169.254.99.253 (Cloud Router) and 169.254.99.254 (peer). Once the matching VM-side configuration was added (again, Part 4), both tunnels showed ESTABLISHED, both BGP sessions showed Established, and the earlier warning cleared entirely.</p><p>Think of it this way: this was never “tunnel A failed, so we built tunnel B to replace it.” It’s “the bridge was designed with two lanes, and we’d only opened one.” Both lanes belong to the same bridge, run to the same destination, and were open and usable simultaneously by the end of this step.</p><p><strong>What Cloud VPN actually provides — and what it doesn’t</strong></p><p>It’s worth being explicit about the division of labor here, because it becomes important in Part 5. <strong>Cloud VPN’s HA VPN Gateway handles exactly one thing: encrypted tunnel endpoints.</strong> It terminates IPsec on Google’s side, matching whatever the on-prem side sends. It does <strong>not</strong>, by itself, know anything about routing, doesn’t understand what’s reachable through the tunnel, and doesn’t move a single packet toward any actual destination inside your VPC on its own.</p><p>That’s the Cloud Router’s job — and by extension, BGP’s job, and by extension, FRR’s job on the VM side. Cloud VPN gets you an encrypted pipe. Something else has to tell both ends what belongs on the other side of that pipe. That’s exactly where Part 4 picks up.</p><h3>Part 4: strongSwan + FRR — The On-Prem Side of the Tunnel</h3><pre>sudo apt install -y strongswan strongswan-pki libcharon-extra-plugins<br>sudo apt install -y frr</pre><p>Worth flagging immediately for anyone following along with older strongSwan tutorials online: this install uses the modern swanctl/charon-systemd configuration system, <strong>not</strong> the legacy ipsec.conf/ipsec command-line tool most older guides assume. Configuration lives under /etc/swanctl/conf.d/, and the swanctl command — not ipsec — is what manages the running daemon. This distinction cost real early time: a perfectly well-formed ipsec.conf file was written and populated correctly, only for the running charon daemon to simply never read it, because it wasn&#39;t looking there at all.</p><p><strong>Disabling automatic route installation</strong></p><p>Before writing any tunnel configuration, one setting had to be changed globally, and it’s easy to skip because nothing in a typical strongSwan guide calls it out as mandatory for this specific setup:</p><pre>sudo tee -a /etc/strongswan.d/charon.conf &lt;&lt; &#39;EOF&#39;<br>charon {<br>    install_routes = no<br>}<br>EOF</pre><p>By default, strongSwan tries to manage kernel routing tables itself whenever a tunnel comes up — perfectly reasonable behavior for a simple policy-based VPN, and directly destructive here, where FRR is meant to be the sole authority over the routing table via BGP-learned routes. With both trying to manage the same routes, the result was a genuinely confusing failure mode discovered later: ip route get &lt;destination&gt; would resolve to the <em>wrong</em> interface (the regular default gateway instead of the VPN tunnel), even though the BGP session itself showed as perfectly healthy.</p><p><strong>Tunnel 1 configuration</strong></p><pre>connections {<br>    gcp-tunnel1 {<br>        version = 2<br>        local_addrs = %any<br>        remote_addrs = 35.242.125.164<br>        local  { auth = psk; id = 106.219.121.170 }<br>        remote { auth = psk; id = 35.242.125.164 }<br>        children {<br>            gcp-tunnel1-child {<br>                local_ts = 0.0.0.0/0<br>                remote_ts = 0.0.0.0/0<br>                mode = tunnel<br>                start_action = start<br>                dpd_action = restart<br>                updown = /etc/ipsec-vti.sh<br>                mark_in = 42<br>                mark_out = 42<br>            }<br>        }<br>        proposals = aes256-sha256-modp2048<br>    }<br>}</pre><p>With a matching secrets block holding the pre-shared key generated back in Part 3. The local_ts/remote_ts values of 0.0.0.0/0 mean this is deliberately a <strong>route-based</strong> VPN (traffic selectors covering &quot;everything&quot;), rather than a traditional <strong>policy-based</strong> VPN with specific subnet-to-subnet selectors — route-based is what makes dynamic BGP routing over the tunnel possible at all, since the actual routing decisions get delegated entirely to the kernel routing table rather than baked into the IPsec policy itself.</p><p><strong>The VTI interface — where IPsec meets BGP</strong></p><p>The updown script is where this all becomes concrete. It creates a <strong>VTI (Virtual Tunnel Interface)</strong> — a genuine Linux network interface that the kernel can route through, carrying exactly the link-local IPs GCP&#39;s BGP session assigned:</p><pre>#!/bin/bash<br>PLUTO_MARK_OUT_ARR=(${PLUTO_MARK_OUT//// })<br>PLUTO_MARK_IN_ARR=(${PLUTO_MARK_IN//// })<br>case &quot;$PLUTO_VERB&quot; in<br>    up-client)<br>        ip link add vti1 type vti local $PLUTO_ME remote $PLUTO_PEER \<br>            okey ${PLUTO_MARK_OUT_ARR[0]} ikey ${PLUTO_MARK_IN_ARR[0]} 2&gt;/dev/null<br>        ip addr add 169.254.193.170/30 remote 169.254.193.169/30 dev vti1 2&gt;/dev/null<br>        ip link set vti1 up mtu 1436<br>        sysctl -w net.ipv4.conf.vti1.disable_policy=1<br>        sysctl -w net.ipv4.conf.vti1.rp_filter=0<br>        ;;<br>    down-client)<br>        ip link del vti1 2&gt;/dev/null<br>        ;;<br>esac</pre><p>This is genuinely the architectural crux of the whole IPsec side: without a VTI interface, an IPsec tunnel is just an encrypted policy applied to matching traffic — there’s no actual network interface for a routing protocol like BGP to run over. The VTI interface turns the tunnel into something that looks, to the rest of the Linux networking stack, like any other network card: something with an IP address, something ip route can point traffic at, something FRR can establish a BGP neighbor relationship across.</p><pre>sudo systemctl restart strongswan<br>sudo swanctl --load-all<br>sudo swanctl --list-sas</pre><p>Result: gcp-tunnel1: ESTABLISHED, with its child SA showing INSTALLED — genuine encrypted traffic now able to flow.</p><pre>sudo sed -i &#39;s/bgpd=no/bgpd=yes/&#39; /etc/frr/daemons<br>sudo systemctl restart frr<br>sudo vtysh</pre><p><strong>FRR — teaching the VM to speak BGP</strong></p><pre>sudo sed -i &#39;s/bgpd=no/bgpd=yes/&#39; /etc/frr/daemons<br>sudo systemctl restart frr<br>sudo vtysh</pre><pre>configure terminal<br>router bgp 65002<br>neighbor 169.254.193.169 remote-as 65001<br>no bgp ebgp-requires-policy<br>address-family ipv4 unicast<br>neighbor 169.254.193.169 activate<br>redistribute connected<br>exit-address-family<br>exit<br>write memory</pre><p>The no bgp ebgp-requires-policy line is the single easiest thing to skip in this entire config, and among the most expensive to miss. Modern FRR enforces <strong>RFC 8212</strong> by default — a rule requiring an explicit inbound and outbound routing policy on any eBGP session (a session between two different autonomous systems, which this is) before <em>any</em> routes are accepted or advertised, even with zero actual filters configured anywhere. Without disabling this, the BGP session itself shows as cleanly Established — keepalives flowing, session healthy — while silently exchanging <strong>zero routes</strong> in either direction. show ip bgp neighbor eventually surfaced the actual giveaway, buried in its detailed output:</p><pre>Inbound updates discarded due to missing policy<br>Outbound updates discarded due to missing policy<br>0 accepted, 0 sent prefixes</pre><p>A perfectly healthy-looking BGP session that was, functionally, doing nothing. With no bgp ebgp-requires-policy applied, show ip bgp immediately began showing GCP&#39;s 10.0.0.0/24 subnet, correctly installed into the kernel routing table via vti1.</p><p><strong>Wiring up tunnel 2</strong></p><p>The VM-side configuration for home-tunnel-2 mirrors tunnel 1 almost exactly — a second swanctl connection block pointed at GCP&#39;s second interface (34.184.18.124), a second VTI script (vti2, carrying the new link-local pair 169.254.99.253/.254), and a second FRR BGP neighbor statement. Both tunnels came up ESTABLISHED; both BGP sessions came up Established; FRR&#39;s routing table began showing genuine multipath entries (*=) for routes reachable via either tunnel — real redundancy, not just a second connection sitting idle.</p><p>📄 Every command from this section, plus tunnel 2 in full: <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/ubuntu-strongswan-setup-guide.md">strongSwan / VPN gateway setup guide</a></p><h3>Part 5: The Bug That Ate an Afternoon — Link-Local Packets Dropped Silently</h3><p>With two tunnels, dynamic BGP routing, and a Cloud SQL for PostgreSQL instance (my-postgres, reachable via Private Service Connect at 10.0.0.2) all independently confirmed as correctly configured, a simple connection attempt —</p><pre>psql -h 10.0.0.2 -U postgres -d postgres</pre><p>— still timed out. Every single time.</p><p>What made this genuinely difficult wasn’t a lack of tools — it was that <strong>every layer checked out clean.</strong> GCP’s own Connectivity Test tool, run directly from Cloud Shell, reported REACHABLE in both directions, tracing the simulated packet&#39;s entire path all the way to <em>&quot;packet delivered to Cloud SQL instance.&quot;</em> The relevant firewall rule allowed the right source range on the right port. The PSC endpoint&#39;s connection status showed ACCEPTED. swanctl --list-sas showed real, growing byte counters in <em>both</em> the in and out directions across both tunnels — genuine encrypted traffic was flowing, not just idle keepalives.</p><p>The eventual answer came from watching actual packets leave the interface, rather than trusting any tool’s summary of what <em>should</em> happen:</p><pre>sudo tcpdump -i vti1 -n port 5432</pre><pre>169.254.193.170.35680 &gt; 10.0.0.2.5432: Flags [S], seq ...</pre><p>There it was, sitting in plain sight the whole time. The outbound SYN packet’s <strong>source address</strong> was 169.254.193.170 — the VTI interface&#39;s own link-local address, straight out of the 169.254.0.0/16 block reserved by RFC 3927 for exactly this kind of link-local, non-globally-routable use. Linux, by default, selects a packet&#39;s source address based on the interface it&#39;s leaving through — and since the route to 10.0.0.2 correctly pointed out vti1, that interface&#39;s own address became the packet&#39;s source, entirely automatically, with no explicit configuration choosing it.</p><p>GCP’s Connectivity Test never caught this, and it’s worth understanding exactly why: it’s a <strong>static configuration analyzer</strong>. It checks whether the <em>path</em> — the routes, the firewall rules, the peering — is theoretically correct for a packet with the source address <em>you tell it to assume</em>. It was never told to assume a link-local source, because nobody realized that’s what would actually happen.</p><p>The real underlying mechanism: <strong>GCP’s Private Service Connect infrastructure silently drops packets carrying a link-local source address.</strong> PSC needs to build a connection-tracking and return-routing entry for every flow it handles — a record of “this specific source needs replies routed back this specific way.” A link-local address, by its very nature, isn’t something PSC can build a meaningful, globally-unambiguous entry for. So the SYN packet simply vanishes on arrival. No RST, no ICMP error, nothing — which is precisely why it looks, from every diagnostic tool above the packet level, identical to a generic network timeout with no discernible cause.</p><p>The fix, once the actual cause was identified, was two lines of iptables:</p><pre>sudo iptables -t nat -A POSTROUTING -o vti1 -j SNAT --to-source 172.24.107.2<br>sudo iptables -t nat -A POSTROUTING -o vti2 -j SNAT --to-source 172.24.107.2</pre><p>Rewriting the VTI interfaces’ outbound source address to the VM’s real, globally-meaningful subnet address (172.24.107.2, sitting inside 172.24.96.0/20 — the very range BGP was already correctly advertising) instead of the link-local tunnel address. psql connected successfully on the very next attempt, with no other change to anything.</p><pre>sudo apt install -y iptables-persistent</pre><p>— selecting “Yes” when prompted to save current IPv4 rules, so this fix survives every future reboot via the netfilter-persistent systemd service, rather than needing to be reapplied by hand.</p><p>This single discovery is, without much competition, the most broadly useful thing in this entire project for anyone doing similar work: <strong>if you’re running a route-based VPN (VTI interfaces) into GCP, and anything on the other end sits behind Private Service Connect, SNAT your tunnel-bound traffic to a real, routable subnet address before it leaves the tunnel interface. Never let it leave with a link-local source.</strong></p><h3>Part 6: A Second, Quieter Gap — DMS Couldn’t Find the Route Either</h3><p>Everything in Part 5 proved connectivity <em>from the gateway VM itself</em> into GCP. Weeks later, once Database Migration Service private connectivity was configured (see Part 8), an eerily familiar symptom reappeared: DMS’s own connection tests to the SQL Server source kept failing with a plain <strong>“Connect timed out”</strong> — the exact same generic message, for what turned out to be an almost identical underlying cause, in a completely different part of the stack.</p><p>Tracing this one followed the same pattern that had worked before: tcpdump on strongswan-gw&#39;s vti1 interface showed DMS&#39;s SYN packets <em>arriving correctly</em> — sourced from 10.250.0.2, the private connectivity peering range. So packets were reaching the tunnel. The problem was one hop further back: checking ip route get 10.250.0.2 from strongswan-gw showed it resolving via the regular default gateway (eth0), not via either VPN tunnel at all.</p><p>The actual cause, found by cross-referencing GCP’s route table:</p><pre>gcloud compute routes list --project=migration-project-111 --filter=&quot;network:my-vpc&quot; \<br>  --format=&quot;table(name,destRange,nextHopVpnTunnel)&quot;</pre><pre>NAME                              DEST_RANGE      NEXT_HOP_VPN_TUNNEL<br>peering-route-c56af68ef660120e    10.250.0.0/29</pre><p>That last column — NEXT_HOP_VPN_TUNNEL — was <strong>empty</strong>. GCP&#39;s Cloud Router had never actually advertised the DMS private-connectivity peering range (10.250.0.0/29) back over BGP to the home network at all. The reason: <strong>VPC peering only automatically exchanges subnet routes by default — never custom, dynamically-learned routes.</strong> The 10.250.0.0/29 range is exactly that kind of route: it exists only because of a peering relationship DMS itself created behind the scenes, not because it&#39;s a &quot;real&quot; subnet that belonged to my-vpc from the start. Cloud Router&#39;s default &quot;advertise all subnets&quot; behavior genuinely doesn&#39;t cover it.</p><p>The fix required switching the Cloud Router’s advertisement mode from its default to <strong>Custom</strong>, and explicitly re-adding <em>both</em> pieces side by side — the existing subnet advertisement (so nothing already working broke) plus the new peering range:</p><pre>gcloud compute routers update home-vpn-router \<br>  --region=us-central1 \<br>  --advertisement-mode=CUSTOM \<br>  --set-advertisement-groups=ALL_SUBNETS \<br>  --set-advertisement-ranges=10.250.0.0/29 \<br>  --project=migration-project-111</pre><p>Once applied, show ip bgp on strongswan-gw immediately showed 10.250.0.0/29 alongside the existing 10.0.0.0/24, and ip route get 10.250.0.2 correctly resolved via vti1. DMS&#39;s connection test passed on the very next attempt.</p><p>The broader lesson here echoes Part 5 almost exactly, just one layer higher in the stack: <strong>anything that introduces a new IP range into your VPC after the fact — a new peering, a new private connectivity configuration, a new PSC endpoint — needs to be explicitly checked against whatever’s actually being advertised over your dynamic routing sessions.</strong> “It’s reachable inside the VPC” and “it’s reachable <em>through your VPN</em> from outside the VPC” are two genuinely different questions, and GCP’s default behaviors don’t automatically make the second one true just because the first one is.</p><h3>Part 7: Forwarding Between the Two VMs</h3><p>Even with tunnels, BGP, and the SNAT fix all working, one more gap remained specific to the two-VM split described back in the architecture overview. GCP’s traffic reaches strongswan-gw — the actual tunnel endpoint — but the real destination, ubuntu-sqlserver, is a <em>different</em> machine on the shared subnet. Two more settings on strongswan-gw closed this gap:</p><pre>sudo sysctl -w net.ipv4.ip_forward=1<br>sudo tee /etc/sysctl.d/99-ip-forward.conf &lt;&lt; &#39;EOF&#39;<br>net.ipv4.ip_forward=1<br>EOF<br>sudo iptables -t nat -A POSTROUTING -o eth0 -d 172.24.96.0/20 -j MASQUERADE<br>sudo netfilter-persistent save</pre><p>The first line enables the Linux kernel’s core packet-forwarding capability — disabled by default on a standard Ubuntu install, since most machines aren’t meant to route traffic for other machines. The persisted /etc/sysctl.d/99-ip-forward.conf file matters more than it might look: a plain sysctl -w change is <em>not</em> persistent by itself, and this setting reverting silently across a reboot was, in fact, the exact cause of a full afternoon&#39;s worth of confusing &quot;it worked yesterday&quot; debugging later in the project, before the dedicated persistence file was added.</p><p>The second line — the MASQUERADE rule — ensures that when ubuntu-sqlserver replies to a request that arrived via the tunnel, that reply gets correctly routed back out through strongswan-gw and the tunnel, rather than attempting to go directly out ubuntu-sqlserver&#39;s own default gateway (which has no idea what a GCP VPN tunnel even is).</p><p>This forwarding requirement is, again, precisely the cost the “two VMs” architectural decision knowingly took on in exchange for avoiding something worse. The alternative — SQL Server running directly on the Windows host — would have needed a genuine DNAT (destination NAT) setup bridging <em>two separate NAT layers</em> (the home router’s NAT, plus Windows’ own Default Switch NAT), which is a meaningfully messier problem than one clean, subnet-level IP forward and MASQUERADE rule between two VMs that already share an address space.</p><p><strong>A memory lesson, learned the hard way</strong></p><p>Partway through this phase of testing, SQL Server started disappearing without warning:</p><pre>Active: failed (Result: oom-kill)</pre><p>Both VMs, sharing one physical host’s RAM pool through Hyper-V’s Dynamic Memory feature, had quietly ballooned down under host-level pressure — a free -h check on the SQL Server VM showed only <strong>2.1 GiB total</strong>, despite the VM being explicitly configured with a 4096 MB Startup memory setting. Dynamic Memory, it turns out, can shrink a running VM below what you configured as its starting point if the host genuinely doesn&#39;t have enough free physical RAM to sustain it — and a starved SQL Server process is exactly the kind of thing the Linux OOM killer terminates first.</p><p>The real fix required two separate changes working together:</p><ol><li><strong>Explicit Minimum RAM floors</strong> in each VM’s Hyper-V Dynamic Memory settings — 3072 MB minimum for the SQL Server VM (guaranteeing Dynamic Memory could never shrink it below what SQL Server genuinely needs to stay alive), while trimming the lightweight gateway VM down to a leaner 1024 MB Startup / 512 MB Minimum, freeing up host headroom for the VM that actually needed it.</li><li><strong>An explicit memory ceiling inside SQL Server itself</strong>, so the database engine would never try to claim more RAM than the VM could actually sustain in the first place:</li></ol><pre>   sudo /opt/mssql/bin/mssql-conf set memory.memorylimitmb 2800</pre><p>The general lesson: a Hyper-V “Minimum RAM” setting isn’t merely a performance-tuning knob — without one, Dynamic Memory can silently starve a VM’s workload to the point of an out-of-memory kill, with symptoms (a service that “just crashes sometimes”) that look nothing like a memory problem until you specifically go looking for one.</p><p>Static IP addresses, configured via netplan on both VMs, closed out the infrastructure-hardening work — removing a smaller but persistent source of friction where DHCP-assigned addresses occasionally shifted after a reboot, silently invalidating SNAT rules and connection-profile hostnames that had been hardcoded against the previous address.</p><h3>Part 8: Database Migration Service, End to End</h3><p>With connectivity fully proven at every layer, the actual migration work — the part everything above existed to enable — could finally begin.</p><h4>Private Connectivity: giving DMS a way in</h4><p>Database Migration Service doesn’t run inside your VPC at all. It runs from a completely separate, Google-managed tenant project, and needs its own explicit bridge into my-vpc before it can reach anything on the other side of that bridge — including, eventually, everything reachable via the VPN tunnels built in Parts 3 and 4.</p><p><strong>Database Migration → Private connectivity → Create Private Connection</strong>, with a genuinely important fork in the road: GCP offers two distinct connectivity methods here, <strong>PSC Interfaces</strong> and <strong>VPC peering</strong>, and they’re built for opposite situations. PSC Interfaces is meant for when you don’t already have VPC-level connectivity to your source and want DMS to reach it through a dedicated network attachment you create specifically for that purpose. VPC peering is meant for exactly this project’s situation — an existing VPC that already has VPN or Interconnect connectivity to the source, which DMS can simply piggyback on rather than needing its own separate path built from scratch.</p><p>VPC peering was configured against my-vpc, with a peering range (10.250.0.0/29) deliberately chosen to avoid overlapping the existing 10.0.0.0/24 subnet. This is the exact peering relationship whose missing BGP advertisement caused the whole detour documented in Part 6.</p><p><strong>📸 Screenshots for this step:</strong> <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots/02-dms-private-connectivity-setup">docs/snapshots/02-dms-private-connectivity-setup/</a></p><h4>Connection Profiles: one pair per database</h4><p>Each of the four databases ultimately migrated needed its own matched pair of connection profiles:</p><ul><li><strong>A source profile</strong> — SQL Server engine, hostname 172.24.100.130, port 1433, the sa login, private connectivity via the configuration above, and critically, the exact source database name (MyDatabase, LibraryDB, HospitalDB, or InventoryDB).</li><li><strong>A destination profile</strong> — pointing at the existing my-postgres Cloud SQL instance, the postgres login, and the matching lowercase destination database name (mydatabase, librarydb, and so on — PostgreSQL lowercases unquoted identifiers by convention).</li></ul><p>One early mistake here deserves a full explanation, because it produced a genuinely confusing symptom. The very first source connection profile had its “Database name” field left at the SQL Server default, master. DMS&#39;s schema-pull step succeeded — no error at all — because master is a perfectly real, connectable database. But master is SQL Server&#39;s own internal system database; it has no user tables. The conversion workspace consequently showed &quot;0 schemas&quot; with real user tables entirely absent, not because anything had failed, but because it had faithfully converted the schema of a database that was never meant to be migrated in the first place. The fix was creating a fresh connection profile with the actual target database name explicitly specified — after which the schema pull correctly surfaced all eight real tables.</p><p>Screenshots for each database’s full connection-profile → conversion-workspace → migration-job → verification walkthrough:</p><p><strong>Database — Tables — Snapshots</strong></p><p><strong>MyDatabase</strong> <strong>-</strong> HR/sales datasetDepartments, Employees, Projects, EmployeeProjects, Customers, Products, Orders, OrderDetails<br><a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots/03-mydatabase">03-mydatabase/</a></p><p><strong>HospitalDB - </strong>Doctors, Patients, Appointments<br><a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots/04-hospitaldb">04-hospitaldb/</a></p><p><strong>InventoryDB - </strong>Warehouses, Items, StockMovements<br><a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots/05-inventorydb">05-inventorydb/</a></p><p><strong>LibraryDB - </strong>Books, Members, Loans <br><a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration/blob/main/docs/snapshots/06-librarydb">06-librarydb/</a></p><p>Conversion Workspace: translating SQL Server into PostgreSQL</p><p>DMS’s Conversion Workspace exists because SQL Server (T-SQL) and PostgreSQL are genuinely different SQL dialects — this isn’t a raw data copy, it’s an actual schema translation. Creating a workspace (sqlserver-to-postgres-cw) and pulling a schema snapshot produced a clean, largely-automatic result on the first real database: <strong>31 total objects, 23 with zero issues, 8 flagged &quot;awaiting review,&quot; 0 requiring hard manual action.</strong></p><p>Every single flagged object shared the identical underlying cause: CLUSTERED INDEX is not yet implemented. SQL Server makes every primary key a clustered index by default — meaning the table&#39;s actual rows are physically stored on disk in that key&#39;s order. PostgreSQL has genuinely no equivalent concept at all; its closest analog, the CLUSTER command, is a one-time manual reordering operation rather than a maintained table property. There is, quite simply, nothing for the deterministic converter to map this onto. The underlying primary key constraint and its supporting index still get created correctly, as a standard (non-clustered-concept) index — functionally equivalent for every practical query pattern this project&#39;s sample data would ever exercise. Safe to proceed without modification.</p><p>Applying to destination committed this converted schema — every table, primary key, foreign key, and index — onto my-postgres. On the two databases with denser foreign-key relationships (LibraryDB and InventoryDB), a first application attempt occasionally collided with a partially-applied leftover from an earlier attempt (cannot drop table dbo.items because other objects depend on it), resolved cleanly with a manual DROP TABLE ... CASCADE via psql on the conflicting child and parent tables before re-running the apply step, which then completed with zero issues.</p><h4>The Migration Job: One-time vs. Continuous</h4><p>This is the step that actually moves data, and it forces a real architectural decision: <strong>One-time migration</strong> versus <strong>Continuous migration</strong>.</p><p>Continuous migration relies on SQL Server’s native Change Data Capture (CDC) mechanism to keep replicating ongoing changes after the initial load — which in turn requires SQL Server Agent to be installed and running, since Agent is what processes CDC’s underlying capture and cleanup jobs. And SQL Server Agent has never been available on Express Edition, on Windows or on Linux — this is a longstanding, deliberate licensing restriction, not a bug or an oversight.</p><p>Since this build’s SQL Server instance was deliberately Express Edition (to match the original Windows source), switching to Developer Edition purely to unlock Agent for a proof-of-concept migration would have been solving a problem this project didn’t actually have. One-time migration — a single full-dump phase, with no CDC phase and no Agent dependency whatsoever — turned out to be exactly the right fit, and it’s worth being clear that this is a fully legitimate, first-class DMS migration type in its own right, not a lesser workaround for when Continuous “isn’t available.”</p><p>One warning from the migration job’s built-in test deserves genuine explanation rather than a quick dismissal: DMS flagged that foreign keys couldn’t be strictly enforced during a bulk, non-transactional load — naming specific tables like orders and employeeprojects whose foreign keys reference other tables being loaded in parallel, with no guarantee the parent row lands before the child row does. The recommended, and correct, fix:</p><pre>ALTER USER postgres WITH REPLICAT</pre><p>Granting the destination database user PostgreSQL’s REPLICATION attribute allows it to bypass foreign-key enforcement specifically during the bulk-loading process. This isn&#39;t a security compromise or a permanent weakening of the schema — the foreign key constraints remain fully defined and fully enforced immediately afterward; they&#39;re simply not actively re-checked row-by-row while thousands of rows are being loaded in parallel across multiple tables at once, which is standard, expected, and necessary behavior for essentially any bulk migration tool moving relational data with foreign keys intact.</p><p>With that single fix applied once, every subsequent migration job’s test passed cleanly, and each job — for MyDatabase, HospitalDB, InventoryDB, and LibraryDB — ran to completion: Status: Completed. Every table: Promoted. 0 errors, across the board.</p><h4>Verification: the only check that actually counts</h4><p>Console status pages are reassuring, but the only verification that genuinely matters is querying the destination directly and comparing it against the known source:</p><pre>SELECT &#39;employees&#39; AS tbl, COUNT(*) FROM dbo.employees<br>UNION ALL SELECT &#39;departments&#39;, COUNT(*) FROM dbo.departments<br>UNION ALL SELECT &#39;projects&#39;, COUNT(*) FROM dbo.projects<br>UNION ALL SELECT &#39;customers&#39;, COUNT(*) FROM dbo.customers<br>UNION ALL SELECT &#39;employeeprojects&#39;, COUNT(*) FROM dbo.employeeprojects<br>UNION ALL SELECT &#39;orders&#39;, COUNT(*) FROM dbo.orders<br>UNION ALL SELECT &#39;orderdetails&#39;, COUNT(*) FROM dbo.orderdetails<br>UNION ALL SELECT &#39;products&#39;, COUNT(*) FROM dbo.products;</pre><p>Every table, across every migrated database, came back an exact match against the SQL Server source.</p><h3>Lessons Learned</h3><p>A few patterns emerged repeatedly enough across this project that they’re worth naming explicitly, independent of any single specific bug:</p><ul><li><strong>A green checkmark from a config validator is not proof of a working data path.</strong> GCP’s Connectivity Test tool said “REACHABLE” throughout the entire Part 5 saga, because it validates configuration, not runtime packet behavior. The gap between “the config permits this” and “a real packet actually gets there” is exactly where the two hardest bugs in this project — the link-local source address, and the missing BGP route advertisement — both lived.</li><li><strong>tcpdump, watched at the right layer, resolves ambiguity that no higher-level tool can.</strong> Both of this project&#39;s genuinely hard bugs were solved the same way: capturing traffic simultaneously on multiple interfaces across multiple machines, and comparing exactly what left one interface against exactly what arrived at the next. Every other diagnostic — Console error messages, gcloud describe output, connectivity test results — narrowed the search space usefully, but never actually identified the root cause on its own.</li><li><strong>A generic error message (“Connect timed out”) can hide entirely different root causes at completely different layers of the stack.</strong> The exact same symptom appeared twice in this project — once from a link-local source address getting silently dropped by PSC, once from a missing BGP route advertisement for a peering range — and both times, the surface-level error text gave no hint which one it was.</li><li><strong>Infrastructure settings that look like performance tuning can silently become availability problems.</strong> Hyper-V’s Dynamic Memory Minimum RAM setting reads like a performance knob. In practice, without it, Dynamic Memory starved a running SQL Server process to the point of an OOM kill — a failure mode that looks nothing like “slow” and everything like “randomly crashes.”</li><li><strong>Persistence is not automatic, and its absence produces the most confusing kind of bug: “it worked yesterday.”</strong> sysctl -w, ad-hoc iptables rules, and DHCP-assigned addresses all share the same trap — they work perfectly in the moment, and then silently vanish across the next reboot, undoing a fix with no error message anywhere pointing back at what changed.</li></ul><h3>What’s Next</h3><p>With four databases fully migrated and independently verified, a few directions remain open: exploring a genuine Continuous/CDC migration path by switching to SQL Server Developer Edition, to demonstrate near-zero-downtime cutover rather than a one-time full dump; and documenting the teardown process for anyone using this as a learning exercise rather than a production build, since every VM, VPN tunnel, and Cloud SQL instance here continues to accrue real GCP cost while running.</p><p>Full setup guides, exact command sequences, and 146 screenshots documenting every step of this build are available in the companion</p><p><strong>Repository:</strong> <a href="https://github.com/bikram-singh/onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration"><strong>onprem-sqlserver-to-gcp-cloudsql-postgres-dms-migration</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=017f4f2f5ab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Runbooks to Architecture Decision Records: Becoming a GCP Solutions Architect]]></title>
            <link>https://medium.com/@bikram23march/from-runbooks-to-architecture-decision-records-becoming-a-gcp-solutions-architect-605ca6f1aa1f?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/605ca6f1aa1f</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 05:52:31 GMT</pubDate>
            <atom:updated>2026-09-22T05:52:31.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOhi8huPvHw_9VbWnqsjoQ.png" /></figure><h3>🎯 Introduction</h3><p>So I designed something, then applied it to a real, live GCP organization — not a sandbox, not a terraform plan left untested and abandoned once it looked clean. A real org, real projects, real billing, a real disaster recovery drill with a stopwatch in hand, and two real incidents I had to catch and fix along the way, live, with no undo button.</p><p>I mean that literally. Every Terraform module in this build was actually applied — terraform apply, watched to completion, against a genuine GCP organization I created and administered myself. Every IAM role was actually granted and actually tested against the live API, not assumed correct because the code looked right. The disaster recovery drill wasn&#39;t a tabletop exercise or a diagram with an arrow labeled &quot;failover&quot; — I wrote a timestamped row to a live database, promoted a real cross-region replica with gcloud sql instances promote-replica, and measured, with a stopwatch, exactly how long it took and exactly how much data was lost. And when something broke — twice, in ways that genuinely could have been costly — I didn&#39;t edit the mistake out of the record afterward. I fixed it, wrote down exactly what happened and why, and left both the mistake and the fix in the repository for anyone to read.</p><p>This is the story of that build: <strong>MedSecure</strong>, a reference architecture for a multi-region healthcare SaaS platform on Google Cloud. It’s not a tutorial, and it isn’t a polished demo built to look impressive in a screenshot. It’s a record of real decisions, tested against a real cloud environment, including the parts that didn’t go smoothly the first time.</p><h3>🩺 The brief</h3><p><strong>MedSecure</strong> ingests patient-consented wearable telemetry, stores and analyzes it, and exposes a clinician portal and partner-clinic APIs. I chose a healthcare scenario deliberately — it forces hard trade-offs across compliance, disaster recovery, and security simultaneously, in a way a simpler CRUD app never would.</p><p>Every architectural decision in this build traces back to one of these non-functional requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*zH2ptNZemR1koDnGC6XCAg.png" /></figure><p><strong>⚠️ One scope boundary, stated plainly before anything else:</strong> this project builds and proves the <em>infrastructure</em> MedSecure would run on — not MedSecure itself. No wearable device ever sent real telemetry. No clinician ever queried the portal. No partner clinic ever called an API. The Cloud Run services described below run Google’s public sample container image, not application code — because that application code was never written. The Pub/Sub → Dataflow → BigQuery pipeline exists structurally and is reused from a separate, already-built telemetry project, but no message has flowed through <em>this</em> deployment of it. Every infrastructure claim in this article is real and tested. Every claim about what MedSecure <em>does</em> as a product describes intent, not a tested behavior. I’m stating this here, once, clearly, rather than letting the narrative imply otherwise.</p><h3>🏗️ High-Level Design</h3><p>The architecture is organized around ten pillars, mapped onto Google’s six Well-Architected Framework pillars (Operational Excellence, Security, Reliability, Performance, Cost, Sustainability). At the top level, it looks like this:</p><pre>Organization (gcpcloudhub.in)<br>│<br>├── 🗂️ Landing Zone: folder hierarchy by environment → region → service<br>│   (residency enforced structurally via org policy, not convention)<br>│<br>├── 🌐 Network: NCC hub-and-spoke + per-region Shared VPC + Cloud Armor<br>│   (avoids VPC Peering&#39;s non-transitive routing trap at scale)<br>│<br>├── ⚙️ Compute: GKE Autopilot (API tier) + Cloud Run (event-driven)<br>│   (matched to workload shape, not one platform forced to do both)<br>│<br>├── 🗄️ Data: Cloud SQL (OLTP) + Pub/Sub → Dataflow → BigQuery (analytics)<br>│   + Dataplex (governance)<br>│<br>├── 🤖 AI/ML: Vertex AI (anomaly detection) + ADK agent (clinician Q&amp;A)<br>│   (agent gets analyst-equivalent access, never elevated)<br>│<br>├── 🔐 Security: per-region VPC Service Controls perimeters + CMEK<br>│   (two perimeters, not one — matches the residency boundary exactly)<br>│<br>├── 🛟 Reliability: active-passive Cloud SQL, drilled failover runbook<br>│<br>├── 💵 Cost: itemized model separating fixed vs. variable cost drivers<br>│<br>├── 🔁 CI/CD: HCP Terraform + GitHub Actions, WIF auth, human-gated prod apply<br>│<br>└── 📊 Observability: golden-signals dashboards + formal SLO + burn-rate alerts</pre><p>The single design principle running through every pillar: <strong>match the tool to the actual shape of the problem, and enforce boundaries structurally, not by convention.</strong> Residency isn’t a naming convention — it’s an org policy constraint that makes a violation physically impossible to apply. Least privilege isn’t a suggestion — the AI agent’s service account has exactly the BigQuery access a human analyst would have, no more.</p><p>📐 <strong>The full architecture diagram set</strong> — one per pillar, plus the real, deployed org resource hierarchy — is in <a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/tree/main/docs/diagrams">docs/diagrams/</a> in the repo. Each ADR links directly to its own diagram.</p><h3>🔧 Low-Level Design: pillar by pillar</h3><h4>1️⃣ Landing Zone &amp; Resource Hierarchy</h4><p><strong>Decision:</strong> Org → Folder (prod/non-prod) → Folder (eu/us) → Project (api/data/ml), with a separate shared-services folder for cross-cutting infrastructure (network hub, logging) that never holds customer data.</p><p><strong>Why:</strong> the residency boundary needs to be enforced by something a reviewer can’t argue with. A constraints/gcp.resourceLocations org policy scoped to each region folder makes it <em>structurally impossible</em> to create a resource in the wrong region — not a naming convention someone could accidentally violate, a hard API-level rejection.</p><p><strong>✅ Real result:</strong> applied for real. 8 folders, 4 org policies, 14 projects, all live in the org.</p><p><strong>🚨 The incident:</strong> mid-build, a terraform apply intended to fix a quota-project setting instead destroyed all 14 projects. I recovered with <strong>zero data loss</strong> using Terraform import blocks to reattach state to the undeleted (GCP&#39;s 30-day soft-delete window saved me) resources. This incident became the direct justification for Pillar 9&#39;s mandatory human-approval gate on production applies — not a best practice I read somewhere, a lesson I earned the hard way in this exact repo.</p><h4>2️⃣ Network Architecture</h4><p><strong>Decision:</strong> Network Connectivity Center hub-and-spoke, with one Shared VPC per region attached as a spoke — not VPC Peering.</p><p><strong>Why:</strong> VPC Peering is non-transitive. At six-plus service projects per environment, a peering mesh becomes an O(n²) management problem. NCC’s hub solves this structurally.</p><p><strong>✅ Real result:</strong> live — NCC hub, Shared VPC + subnet (with secondary IP ranges added later for GKE), Private Service Access peering, and a Cloud Armor WAF policy with adaptive Layer 7 DDoS protection and per-IP rate limiting.</p><p><strong>🐛 A real bug found while wiring Compute to this network:</strong> GKE Autopilot always creates VPC-native clusters, which require pre-declared secondary IP ranges on the subnet — not documented anywhere obvious in the Terraform provider’s examples. Found by hitting the actual error against the live API, not by reading documentation.</p><h4>3️⃣ Compute &amp; Modernization</h4><p><strong>Decision:</strong> GKE Autopilot for the stateful API tier, Cloud Run for event-driven services (webhook ingestion, notification dispatch) — not one platform for both.</p><p><strong>Why:</strong> the two workload types genuinely have different shapes. Forcing Cloud Run to handle a persistent, latency-sensitive API tier, or forcing GKE to manage bursty event-driven work, means running the wrong tool for at least one job.</p><p><strong>⚙️ Real result — and a genuinely hard-won one:</strong> getting GKE live required six sequential, real fixes discovered against the live API, in order:</p><ol><li>Secondary IP ranges on the subnet (see Pillar 2)</li><li>ip_allocation_policy on the cluster resource itself, referencing those ranges</li><li>roles/container.hostServiceAgentUser — GKE&#39;s service agent needs this on the Shared VPC host project, which isn&#39;t included in Owner</li><li>The Kubernetes Engine API enabled on the <strong>host</strong> project, not just the service project</li><li>The service project actually attached to the Shared VPC (a step I’d deferred earlier when the project wasn’t yet billed)</li><li>The org’s constraints/compute.vmExternalIpAccess policy, which blocked node VMs from getting external IPs — resolved not by overriding the policy, but by adding private_cluster_config with enable_private_nodes = true, which is what the design (private-only backend tiers) already called for</li></ol><p>Two broken clusters (stuck in STATUS: ERROR) were created and deleted during this process. No data loss — they were empty clusters with no workloads.</p><h4>4️⃣ Data &amp; Analytics</h4><p><strong>Decision:</strong> Cloud SQL (Postgres, regional HA) for transactional state, Pub/Sub → Dataflow → BigQuery for streaming telemetry analytics, Dataplex for governance — three systems, not one forced to do all three jobs.</p><p><strong>✅ Real result:</strong> live — Cloud SQL primary, BigQuery dataset, Pub/Sub topic/subscription, Dataplex lake.</p><p><strong>⚠️ A real, still-open trade-off:</strong> Cloud SQL currently runs on a temporary public IP with a locked-down authorized network, not the private-only design the ADR specifies. This exists because the network module’s Private Service Access peering (needed for private Cloud SQL) requires its own billed project, and the billing account’s 5-project link quota (a trial-tier limit) was the actual constraint blocking that at the time. I made a deliberate, documented trade-off — public IP, single IP allowlisted, clearly flagged — to unblock the more valuable Pillar 7 work (the DR drill) rather than wait indefinitely.</p><h4>5️⃣ AI/ML Layer</h4><p><strong>Decision:</strong> Vertex AI for anomaly detection, an ADK-based agent (Gemini 2.5 Flash) for clinician natural-language queries, grounded on BigQuery — and critically, the agent’s service account gets <strong>exactly the BigQuery access a human analyst would have</strong>, not elevated agent-specific permissions.</p><p><strong>Why this matters:</strong> grounding solves the hallucination problem (every answer traces to an actual query result), but grounding creates a new risk — a scoping bug in the agent’s retrieval logic could become a data exfiltration path. Capping the agent’s access at analyst-equivalent scope means a scoping bug can leak at most what a compromised analyst credential could leak. Not more.</p><p><strong>✅ Real result:</strong> live — Vertex AI endpoint, Cloud Run agent, service account with bigquery.dataViewer + bigquery.jobUser only.</p><h4>6️⃣ Security &amp; Compliance</h4><p><strong>Decision:</strong> two independent VPC Service Controls perimeters (one per region), not one shared perimeter, plus CMEK on data stores.</p><p><strong>Why two, not one:</strong> a single global perimeter protects against external exfiltration but does nothing to stop data moving between EU and US projects <em>inside</em> the same perimeter — silently breaking the residency guarantee every other pillar enforces structurally. Two perimeters with no bridge make any future cross-region need an explicit, reviewed decision, not a silent default.</p><p><strong>🔒 Real result:</strong> live. And confirmed, repeatedly, to work exactly as designed — the perimeter blocks unauthorized access from <em>every</em> path I tried: the gcloud CLI, the REST API, the Cloud Console UI, local Terraform, and HCP Terraform&#39;s remote execution identically. At one point it blocked my own admin account&#39;s Console access to a database I&#39;d built myself. That&#39;s not a bug. That&#39;s the security control doing its job.</p><p><strong>🚨 The other incident:</strong> importing a pre-existing, org-level VPC-SC Access Policy (owned by a separate, unrelated live project of mine) into this module’s Terraform state briefly overwrote its display title during the same apply that correctly imported it. Caught within the same session, reverted via gcloud, verified with a follow-up terraform plan showing zero drift.</p><h4>7️⃣ Reliability &amp; Disaster Recovery</h4><p><strong>Decision:</strong> active-passive Cloud SQL with a cross-region replica, a documented runbook, and — the part that actually matters — a <strong>real drill</strong>, not a design intention.</p><p><strong>The drill, for real:</strong></p><ol><li>Connected to the live primary, wrote a timestamped test row</li><li>Declared an incident, started the clock</li><li>Ran gcloud sql instances promote-replica against the live cross-region replica</li><li>Connected to the newly-promoted instance and verified the test row</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*J9O1b5lWwAJp9U2fpuinKw.png" /></figure><p>That’s a real number, not an estimate. It significantly beats the target, and it’s the single strongest artifact in the whole repo — a screenshot of a design document is a claim; a terminal transcript of an actual promotion with matching timestamps is evidence.</p><p><strong>🔄 A genuine mid-build correction:</strong> the original monitoring design assumed Cloud Monitoring’s Uptime Check API supported Cloud SQL directly. It doesn’t — confirmed against the live API, not assumed. Redesigned around Cloud SQL’s native cloudsql.googleapis.com/database/up metric queried directly via an alert policy, with the correct ALIGN_MIN aligner (the metric is a gauge, not a boolean rate — ALIGN_FRACTION_TRUE doesn&#39;t apply).</p><h4>8️⃣ Cost Optimization / FinOps</h4><p><strong>Decision:</strong> an itemized cost model separating fixed costs (regional HA, the DR replica, CMEK, SCC Premium — deliberately shown, not hidden) from variable, usage-scaling costs, to demonstrate <em>why</em> cost-per-user falls as the user base grows, not just assert that it does.</p><p><strong>💰 A real bug, and an honest correction:</strong> the budget resource failed identically across gcloud and Terraform, with a generic 400: invalid argument error. I initially documented this as a &quot;platform limitation&quot; on the trial billing account. That conclusion was wrong. Systematic isolation — testing currency, thresholds, and notification-channel wiring independently via raw gcloud calls — found the real cause: the module hardcoded USD, but the billing account&#39;s actual currency is INR. A second root cause, found later, was that roles/billing.user doesn&#39;t include budget-specific permissions at all — roles/billing.admin does, a genuine, specific detail in GCP&#39;s billing IAM design that isn&#39;t obvious from the role name.</p><p>I left the original wrong conclusion in the record and wrote a correction on top of it, rather than editing history — the point of documenting deviations honestly is undermined if I only keep the entries that make me look right the first time.</p><h4>9️⃣ CI/CD &amp; Infrastructure as Code</h4><p><strong>Decision:</strong> HCP Terraform workspaces (one per module) connected via VCS, GitHub Actions for path-filtered plan-on-PR, a GitHub Environment protection rule requiring a human reviewer before any production apply — and a dedicated Workload Identity Federation pool, scoped only to this project, not reused from an existing WIF setup I already had on another project.</p><p><strong>Why the prod-apply gate isn’t optional:</strong> it’s the direct, stated response to the accidental-destroy incident in Pillar 1. A pipeline is not meaningfully safer than a human running terraform apply locally unless something structurally forces a second, deliberate review before a destructive change reaches production.</p><p><strong>🎉 Real result, and this is the part I’m most proud of:</strong> all 9 HCP Terraform workspaces were individually tested with a genuine git push → VCS trigger → plan → human approval → apply cycle.</p><ul><li><strong>✅ 7 workspaces applied completely cleanly</strong> — network, observability, compute, ai-ml, security, reliability, cost — zero errors, zero drift.</li><li><strong>⚠️ 2 were correctly blocked</strong> on real, external, fully understood constraints: landing-zone on the billing quota (same constraint as Pillar 4), and data on the VPC-SC perimeter (confirmed to block HCP Terraform&#39;s remote execution identically to local access — the same security control proving itself consistent across every access path).</li></ul><p>Getting there required real debugging: a WIF audience mismatch (the provider needed the exact GCP-format resource name, not the OIDC issuer URL), an ADC quota-project setting silently inherited from unrelated local gcloud config, five missing APIs discovered one at a time, and — my favorite one — discovering that roles/compute.xpnAdmin is required for Shared VPC attachment and genuinely isn&#39;t included in Owner, a narrow, security-sensitive permission GCP keeps deliberately separate.</p><p>The GitHub production Environment&#39;s required-reviewer rule is verified active directly via the GitHub API — not just declared in a workflow file that might silently not be enforced.</p><h4>🔟 Observability</h4><p><strong>Decision:</strong> domain-organized golden-signals dashboards (not one dashboard per resource), a formal SLO with burn-rate alerting tied directly to the 99.95% availability NFR, and a Platform Health Summary dashboard that surfaces Pillar 7 and Pillar 8’s alerts by reference rather than duplicating them.</p><p><strong>✅ Real result:</strong> live — monitoring service, SLO, both fast (14.4x/1hr) and slow (6x/6hr) burn-rate alert policies, and the dashboard.</p><p><strong>🐛 Four real GCP schema quirks, found in sequence:</strong> the dashboard JSON required title nested inside widget (not as a tile-level sibling), explicit xPos/yPos/width/height on every tile, and a columns value on the mosaic layout — none obvious from the Terraform provider&#39;s own documentation, all found by hitting the actual 400 errors against the live API and fixing them one at a time.</p><h3>📸 Snapshots</h3><p><strong>🔁 The CI/CD pipeline, proven end-to-end</strong></p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/01-hcp-workspaces-overview.png">01-hcp-workspaces-overview.png</a> All 9 HCP Terraform workspaces, one per module</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/02-hcp-network-apply-success.png">02-hcp-network-apply-success.png</a>A clean, real apply on medsecure-network</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/03-hcp-observability-apply-success.png">03-hcp-observability-apply-success.png</a>A clean, real apply on medsecure-observability</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/11-terraform-login-hcp-terraform.png">11-terraform-login-hcp-terraform.png</a>The real terraform login and state migration into HCP Terraform</p><p><strong>🔐 The human-approval gate, genuinely active</strong></p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/04-github-production-environment-protection.png">04-github-production-environment-protection.png</a> — GitHub&#39;s production Environment, showing a required reviewer configured and enforced. This is the direct answer to the accidental-destroy incident in Pillar 1: not a policy written in a document somewhere, a setting verified active via the GitHub API</p><p><strong>⚙️ Live infrastructure</strong></p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/05-gke-cluster-healthy.png">05-gke-cluster-healthy.png</a>The GKE Autopilot cluster, healthy and running</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/09-resource-manager-hierarchy.png">09-resource-manager-hierarchy.png</a>The real, live org resource hierarchy</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/07-cloud-monitoring-dashboards-list.png">07-cloud-monitoring-dashboards-list.png</a>Live Cloud Monitoring dashboards</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/10-iam-hcp-tf-deployer-bindings.png">10-iam-hcp-tf-deployer-bindings.png</a>The real IAM role bindings for the CI/CD service account</p><p><strong>🛡️ The security perimeter, working as designed</strong></p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/06-vpc-sc-perimeter-details.png">06-vpc-sc-perimeter-details.png</a> shows the live VPC-SC perimeter and its restricted services.</p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/12-vpc-sc-blocking-own-admin-access.png">12-vpc-sc-blocking-own-admin-access.png</a> shows something more interesting: the same perimeter denying <em>my own admin account&#39;s</em> Console access.</p><p><em>I kept that second one in on purpose. A “you’re not allowed in either” screenshot is stronger evidence of a working security boundary than any success screenshot could be.</em></p><p><strong>💰 The real budget, currency bug fixed</strong></p><p><a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint/blob/main/docs/snapshots/08-billing-budgets-alerts.png">08-billing-budgets-alerts.png</a> — ₹1,50,000/month, correctly in INR, with alert thresholds at 50/80/100/120%. The story behind why this took two attempts to get right is in Pillar 8, below.</p><h3>📈 The numbers, in one place</h3><ul><li>🎯 <strong>10 of 10 architectural pillars</strong> have real, applied infrastructure or a fully proven mechanism</li><li>🔁 <strong>7 of 9 HCP Terraform workspaces</strong> apply completely cleanly through the real CI/CD pipeline; the other 2 are blocked on understood, external constraints</li><li>📘 <strong>25 documented deviations</strong>, the large majority resolved with a genuine root cause found — including one self-correction where an earlier “resolved” entry turned out to be wrong and got fixed properly</li><li>🚑 <strong>1 real DR drill</strong>: RTO ~3–4 minutes (target: ≤60), RPO 0 (target: ≤15)</li><li>🚨 <strong>2 real incidents</strong>, both caught and cleanly recovered within the same build session</li><li>✅ <strong>0 data loss</strong>, across everything</li></ul><h4>🔍 What I’d do differently</h4><p>Honestly, a few things:</p><p><strong>I’d add the DR replica’s cost to the model from the start</strong>, not retroactively. The drill was worth every rupee it cost, but a fixed cost that isn’t accounted for in the cost model from day one undermines the model’s own credibility.</p><p><strong>I’d write the “known deviations” log from the very first hour</strong>, not after the first incident forced me to start one. Once I had it, it became the single most useful artifact in the whole repo — both for me, mid-build, tracking what was actually true versus what I’d assumed, and for anyone reviewing the finished work.</p><p><strong>A single-write DR test understates real RPO risk.</strong> The drill proved the mechanism works, but a real production incident would involve sustained write load, not one test row. A follow-up drill under continuous writes during promotion is the honest next step, not a claim I’ve already made.</p><p><strong>📦 Repository:</strong> <a href="https://github.com/bikram-singh/gcp-solutions-architecture-blueprint">github.com/bikram-singh/gcp-solutions-architecture-blueprint</a></p><p>Everything is public:</p><ol><li>All 10 Terraform modules</li><li>All 10 ADRs — each with a real “Implementation Status” section, not just the original design</li><li>The full 25-entry deviation log</li><li>The real drill results</li><li>The architecture diagrams</li><li>The 12 screenshots referenced above</li></ol><p><strong>📂 Repo structure</strong></p><pre>.<br>├── README.md<br>├── docs/<br>│   ├── 01-scenario-and-nfrs.md<br>│   ├── 02-well-architected-mapping.md<br>│   ├── deployed-hierarchy.md        # real, live org structure<br>│   ├── known-deviations.md          # 25 documented real-world findings<br>│   ├── adr/                         # 10 ADRs, each with a real Implementation Status<br>│   ├── diagrams/                    # architecture diagrams per pillar<br>│   ├── snapshots/                   # the 12 real screenshots referenced above<br>│   └── dr-drill/<br>│       ├── failover-runbook.md      # real, measured drill results<br>│       └── scripts/<br>├── terraform/<br>│   ├── landing-zone/<br>│   ├── network/<br>│   ├── compute/<br>│   ├── data/<br>│   ├── ai-ml/<br>│   ├── security/<br>│   ├── reliability/<br>│   ├── cost/<br>│   └── observability/<br>├── .github/workflows/<br>│   ├── terraform-plan.yml           # path-filtered plan-on-PR<br>│   └── terraform-apply.yml          # auto-apply non-prod, gated prod apply<br>└── cost-model/<br>    └── cost-model.csv               # itemized, ADR-linked cost model</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=605ca6f1aa1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IAM Isn’t Enough: Securing GCP with VPC Service Controls]]></title>
            <link>https://medium.com/@bikram23march/iam-isnt-enough-securing-gcp-with-vpc-service-controls-f3f27556c221?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f27556c221</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 07:53:54 GMT</pubDate>
            <atom:updated>2026-09-15T07:53:54.874Z</atom:updated>
            <content:encoded><![CDATA[<p>Perimeters, VPC networks, access levels, ingress/egress rules, scoped policies, perimeter bridges, and Shared VPC tested end-to-end in a live GCP organization, with every “why did that just get blocked?” moment documented.</p><p>Console → Access Context Manager → Service Perimeter → Access Levels → Ingress/Egress Rules → Bridges → Shared VPC</p><h3>🌟 Introduction</h3><p>If you’ve ever been told “IAM isn’t enough for sensitive data,” VPC Service Controls (VPC SC) is the answer GCP gives you. It’s a second, independent security perimeter that sits <em>underneath</em> IAM — so even a principal with a valid Editor or Storage Admin role can be denied if the request comes from the wrong network, the wrong identity type, or the wrong region.</p><p>Most explanations of VPC SC stop at the conceptual slide deck. This one doesn’t. I built two GCP projects (trust-project-ok and untrust-project-x), deliberately over-permissioned one against the other, and then spent seven rounds of hands-on testing breaking and fixing access with perimeters, access levels, ingress/egress rules, scoped policies, perimeter bridges, and a Shared VPC topology. Every command and every console click below is something I actually ran — including the failures, because the failures are where VPC SC actually teaches you something.</p><h3>🔐 What Is VPC Service Controls?</h3><p><strong>VPC Service Controls (VPC SC)</strong> is a GCP security feature that creates a logical perimeter around your resources to mitigate data exfiltration risk — even when IAM permissions are correctly scoped, it prevents access to protected resources from outside an approved context (network, identity, or project boundary).</p><p>IAM controls <strong>who</strong> can access a resource. VPC SC controls <strong>from where</strong> that access is allowed to happen — a second, independent layer. Even a principal with valid IAM permissions (say, roles/bigquery.admin) can be blocked from copying data out via a compromised credential, a misconfigured public IP, or an insider using a personal account, because the perimeter itself refuses the request.</p><h4>Core building blocks</h4><ul><li><strong>Service perimeter</strong> — a boundary around a set of GCP projects (or a VPC network) that restricts communication with supported APIs (BigQuery, Cloud Storage, Pub/Sub, Vertex AI, etc.) to inside the perimeter only.</li><li><strong>Access levels</strong> — conditions (IP range, device policy, identity) defined via <strong>Access Context Manager</strong> that can allow specific access from <em>outside</em> the perimeter when needed.</li><li><strong>Perimeter bridges</strong> — allow controlled communication <em>between</em> two perimeters (e.g., a shared services project talking to an app project).</li><li><strong>Ingress/egress rules</strong> — fine-grained rules specifying exactly which identities/services can cross the perimeter boundary, in which direction.</li><li><strong>Dry-run mode</strong> — lets you test a perimeter’s rules and see what <em>would</em> be blocked, via audit logs, before you enforce it.</li></ul><h4>What it protects against</h4><ul><li>Exfiltration via stolen or leaked credentials</li><li>Unauthorized copying of data to a personal or external GCP project</li><li>Access to protected APIs from unapproved networks (public internet without an access level)</li><li>Malicious insiders trying to route data outside a compliance boundary (useful for PCI, HIPAA, etc.)</li></ul><h4>What it does NOT do</h4><ul><li>It doesn’t replace IAM — it’s an additive perimeter, not an access grant</li><li>It only governs supported services — a defined list, not every GCP API is perimeter-aware</li><li>It doesn’t encrypt data or manage keys — that’s CMEK/KMS territory</li></ul><h4>Typical setup flow</h4><ol><li>Enable the Access Context Manager and VPC SC APIs at the org level</li><li>Define access levels (trusted IP ranges, corp devices, identity conditions)</li><li>Create a perimeter in <strong>dry-run mode</strong>, add your projects and restricted services</li><li>Review violation logs in Cloud Logging over some days/weeks</li><li>Add necessary ingress/egress rules or bridges for legitimate cross-perimeter flows</li><li>Switch the perimeter from dry-run to enforced</li></ol><p>Everything below is that flow, run for real, against two live projects — including every place it broke.</p><h3>🧭 What Problem Is VPC Service Controls Actually Solving?</h3><p>IAM answers <strong>“who can do what.”</strong> VPC SC answers <strong>“from where, and under what context, can that access happen at all.”</strong> It’s an additive perimeter around Google Cloud services (Cloud Storage, BigQuery, Compute Engine, and others), independent of IAM, designed to mitigate:</p><ul><li>Access from unauthorized networks using stolen credentials</li><li>Data exfiltration by malicious insiders or compromised code</li><li>Public exposure of private data caused by misconfigured IAM</li><li>Unmonitored access to sensitive services</li></ul><p>A perimeter can run in two modes:</p><pre>Enforced mode   → requests that violate the perimeter policy are DENIED<br>Dry run mode    → requests that violate the perimeter policy are only LOGGED</pre><p>Dry run is the safe way to roll out VPC SC in a live environment — you see exactly what <em>would</em> have broken before you flip the switch.</p><h4>1️⃣ Getting Started: Access Policies &amp; Your First Perimeter</h4><h4>The setup</h4><p>Two projects, two VMs, one deliberate problem:</p><pre>trust-project-ok      → trust-vm     (trust-custom-vpc)<br>untrust-project-x     → untrust-vm   (untrust-custom-vpc)</pre><p>untrust-project-x&#39;s default Compute Engine service account had been granted Editor on trust-project-ok. That&#39;s the exact scenario VPC SC exists for: IAM is technically &quot;correct,&quot; but the blast radius if that untrusted project is compromised is enormous.</p><h4>#1 — you need org-level permission before you can even open the page</h4><p>The very first click into <strong>Security → VPC Service Controls</strong> threw a permissions error:</p><p>The very first click into <strong>Security → VPC Service Controls</strong> threw a permissions error:</p><pre>Missing permissions:<br>  accesscontextmanager.accessLevels.list<br>  accesscontextmanager.policies.list<br>  accesscontextmanager.servicePerimeters.list</pre><p>VPC Service Controls is managed through <strong>Access Context Manager</strong>, and Access Context Manager is an organization-level resource. Nothing works until an admin grants the Access Context Manager Admin role (or Organization Admin) at the <strong>organization</strong> level — not the project level. Once that role was granted, the console lit up with the <strong>Enforced mode / Dry run mode</strong> tabs.</p><p><strong>Create the access policy</strong></p><p>Every VPC SC resource — perimeters and access levels — lives inside an <strong>access policy</strong>, which is a top-level container scoped to the whole organization (you can only have one org-level policy; more on scoped policies in Part 5).</p><pre>Access policy title: my-org-policy<br>Scope: organization (gcpcloudhub.in)</pre><p><strong>Create the perimeter</strong></p><pre>Title            : secure-from-untrust-project<br>Perimeter type   : Regular<br>Resources        : untrust-project-x<br>Restricted APIs  : compute.googleapis.com, storage.googleapis.com<br>VPC accessible   : All services<br>Access levels    : (none yet)<br>Ingress/Egress   : (none yet)<br>Enforcement mode : Enforced</pre><p><strong>The test</strong></p><p>From trust-vm, using the over-permissioned service account:</p><pre>$ gsutil ls gs://untrust-bucket/<br>AccessDeniedException: 403 Request is prohibited by organization&#39;s policy.<br>vpcServiceControlsUniqueIdentifier: ...</pre><p>SSH-in-browser into untrust-vm also failed outright (&quot;Connection Failed — An error occurred while fetching instance or project metadata&quot;) because Compute Engine&#39;s own control-plane API was inside the restricted-services list.</p><p><em>⚠️ Restricting </em><em>compute.googleapis.com doesn&#39;t just block your API calls to Compute Engine — it breaks IAP tunneling and SSH-in-browser too, since those rely on the same API surface. Restrict it deliberately, not by default.</em></p><p>After removing compute.googleapis.com from the restricted list (keeping only Cloud Storage), the Cloud Storage console itself still failed to load buckets (&quot;Sorry, the server was not able to fulfil your request&quot;) — proof the perimeter was doing exactly what it was told.</p><p>Deleting the perimeter entirely restored full access instantly — no propagation delay, no cache to clear.</p><p><strong>Dry run mode</strong></p><p>I rebuilt the same perimeter as dry-run-secure-untrust-project with Enforcement mode: Dry run. Same restricted-services list, same resources — but every one of the commands above succeeded normally. Dry run perimeters are a <strong>decision-support tool</strong>, not a soft version of enforcement: they log violations to Cloud Logging / the Violation Dashboard so you can validate a configuration against real traffic before it ever blocks anything.</p><p>✅ <strong>Takeaway:</strong> An access policy is the container. A perimeter is the fence. Enforced mode denies; dry run only logs. Org-level Access Context Manager permission is a hard prerequisite for any of it.</p><h4>2️⃣ Protecting a VPC Network Instead of a Project</h4><p>This is the distinction that trips almost everyone up the first time: a perimeter’s <strong>Resources to protect</strong> step lets you choose <strong>Projects</strong> <em>or</em> <strong>VPC networks</strong> — and they behave completely differently.</p><pre>Projects     → protects the PROJECT. All API calls that touch that project&#39;s<br>               resources are governed by the perimeter, regardless of where<br>               the caller sits.<br><br>VPC networks → protects the NETWORK. Only API calls that ORIGINATE FROM<br>               INSIDE that VPC are governed. Calls to the same project&#39;s<br>               resources from outside the VPC are untouched.</pre><p>I rebuilt the perimeter, this time selecting the VPC network directly:</p><pre>Resources to protect : projects/untrust-project-x/global/networks/untrust-custom-vpc<br>Restricted services  : storage.googleapis.com</pre><h4>The test — same command, two different machines, two different outcomes</h4><p><strong>From </strong><strong>untrust-vm (inside the protected </strong><strong>untrust-custom-vpc):</strong></p><pre>$ gsutil ls<br>AccessDeniedException: 403 Request is prohibited by organization&#39;s policy.</pre><p>From trust-vm (outside the perimeter entirely, calling the same project):</p><pre>$ gcloud storage buckets list --project=untrust-project-x<br>creation_time: 2025-05-20T05:26:07+0000<br>name: untrust-bucket<br>storage_url: gs://untrust-bucket/<br>...</pre><p>Identical bucket, identical project — one call denied, one call allowed, purely because of where the request physically originated. This is the scenario the concept slides describe as: <em>“you have 5 VPCs across dev/prod, and you want no one from development to reach a production Cloud Storage bucket”</em> — VPC-network-scoped perimeters are exactly the tool for that, and they don’t require touching IAM at all.</p><p>Adding compute.googleapis.com back to the restricted list then blocked Compute Engine API calls originating from inside untrust-custom-vpc the same way.</p><p>✅ <strong>Takeaway:</strong> Project-scoped perimeters protect the resource. VPC-scoped perimeters protect the network boundary. Pick based on whether the risk is “who can reach this project” or “what can this network reach out to.”</p><h4>3️⃣ Access Levels &amp; Access Context Manager</h4><p>A perimeter by itself is binary: in the perimeter or not. <strong>Access levels</strong> add context — IP range, geography, device policy (Chrome Enterprise Premium) as a condition a request must satisfy to be treated as trusted, even from outside the perimeter.</p><pre>Access level title : access-context-level<br>Mode                : Basic<br>Condition           : IP subnetworks → Private IP<br>                       VPC network: trust-project-ok / trust-custom-vpc (all subnets)<br>When condition met  : return True</pre><p>Attached to the untrust-project-x perimeter (restricted services: bigquery.googleapis.com, storage.googleapis.com), the access level allowed exactly one VM&#39;s subnet range through:</p><pre># From a VM inside trust-custom-vpc&#39;s allowed subnet<br>$ gcloud storage buckets list --project=untrust-project-x   # ✅ succeeds<br><br># From a second VM NOT in the allow-listed subnet<br>$ gcloud storage buckets list --project=untrust-project-x   # ❌ denied</pre><p>Removing the access level from the perimeter immediately reverted the first VM back to denied — access levels are purely additive; there’s no fallback.</p><h4>Geography-based access level</h4><p>Same access level, new condition:</p><pre>+ Geographic locations: US (United States)</pre><pre># VM in us-central1                → ✅ &quot;Allow from US&quot;<br># VM in asia-south1 (same project)  → ❌ &quot;Not allowed from other region&quot;</pre><p>Flipping <strong>“When condition is met, return”</strong> from True to False inverts the logic entirely — instead of <em>allow only from US</em>, it becomes <em>allow everything except US</em>. It&#39;s easy to misread this toggle in the console, so I&#39;d recommend naming your access levels with the polarity baked in (allow-us-only vs block-us) rather than relying on remembering which way you set it.</p><h4>Combining conditions and access levels</h4><p>I also built a second access level, allow-public-ip, scoped to a specific public CIDR block, and then referenced the region-based access level as an <strong>access level dependency</strong> inside it — meaning a request now has to satisfy <em>both</em> conditions (public IP range <strong>and</strong> region) to be treated as trusted. Access levels can be composed this way to build genuinely fine-grained, defense-in-depth conditions without touching the perimeter&#39;s core resource/service configuration at all.</p><p>✅ <strong>Takeaway:</strong> Access levels are reusable, composable trust conditions (IP, geography, device policy, or other access levels) that you attach to a perimeter’s ingress path. They don’t replace the perimeter — they’re the exception mechanism layered on top of it.</p><h4>4️⃣ Ingress and Egress Rules</h4><p>Access levels answer <em>“is this request trustworthy enough to get in?”</em> — but they’re evaluated at the perimeter boundary as a whole. <strong>Ingress and egress rules</strong> are more surgical: each rule pairs a <strong>source</strong> (identity + network/project/access-level) with a <strong>destination</strong> (specific project) and a <strong>specific set of API operations</strong>, so you can allow exactly one narrow flow across the boundary instead of opening the whole perimeter.</p><h4>Building an ingress rule</h4><pre>Rule name  : Ingress rule 1<br>From<br>  Identities : Any identity<br>  Sources    : All sources<br>To<br>  Resources  : untrust-project-x<br>  Operations : storage.googleapis.com (all methods)</pre><p>Before this rule existed, a call from trust-vm to untrust-project-x&#39;s bucket was denied outright. After adding it:</p><pre>$ gcloud storage buckets list --project=untrust-project-x<br>name: untrust-bucket<br>...                                                          # ✅ now succeeds</pre><h4>Narrowing the identity type</h4><p>I then edited the same rule and changed <strong>Identities</strong> from Any identity to Any user account (excluding service accounts). Immediately, the exact same call — now running as the VM&#39;s default <em>service account</em> — was denied again:</p><pre>AccessDeniedException: 403 ... not allowed to access the resource because<br>it&#39;s not permitted by the currently active service perimeter</pre><p><em>⚠️ Ingress rules distinguish between </em><strong><em>user accounts</em></strong><em> and </em><strong><em>service accounts</em></strong><em> as separate identity classes. A rule written for “any identity” silently includes both — if you only mean human operators, be explicit, or your service accounts will fail in ways that look like a completely unrelated bug.</em></p><h4>Egress rules</h4><p>Egress works the same way in reverse — governing calls that originate <em>inside</em> a perimeter and reach <em>outside</em> it (or out to the public internet):</p><pre>Rule name  : egress<br>From<br>  Identities : Any identity<br>  Sources    : trust-project-ok<br>To<br>  Resources  : All projects (Google Cloud resources)<br>  Operations : storage.googleapis.com</pre><p>✅ <strong>Takeaway:</strong> Access levels gate <em>who gets past the fence</em>; ingress/egress rules gate <em>which specific API calls, for which specific identities, are allowed to cross it in each direction</em>. Use rules when a bridge or a blanket access level would be too coarse.</p><h4>5️⃣ Scoped Policies — Delegating VPC SC to a Folder or Project</h4><p>An organization can only have <strong>one</strong> org-level access policy. But large organizations don’t want every perimeter change to require org-admin approval — so GCP offers <strong>scoped policies</strong>: access policies whose scope is a single folder or project, used to delegate perimeter/access-level administration downward.</p><pre>untrust-project-policy  → scope: untrust-project-x (project-scoped)<br>test-folder-policy      → scope: foldergcpcloudhub (folder-scoped)</pre><h4>#2 — a project can only belong to one policy, period</h4><p>Trying to add a project that was already governed by another access policy failed immediately:</p><pre>Service perimeter creation failed<br>Policy: accessPolicies/244775374082 already contains resource:<br>projects/300702408885 or its children, thus the resource or its children<br>cannot be added to policy: accessPolicies/106482310921.</pre><p>This happened twice in the lab — once between two scoped policies, once between a folder-scoped policy and the org-level policy. <strong>A project (or its parent folder) can be a member of exactly one service-perimeter policy across the entire organization</strong>, whether that policy is org-level or scoped. Plan your folder/policy hierarchy before you start creating perimeters, because you can’t have overlapping coverage.</p><h4>#3 — access levels don’t cross policy boundaries</h4><p>An access level created under the <strong>org-level</strong> policy (my-access-level) was completely invisible when editing a perimeter that belonged to the <strong>folder-scoped</strong> policy — the &quot;Add access levels&quot; list showed zero rows. Each access policy (org or scoped) has its own separate namespace of access levels; there&#39;s no inheritance. The fix was simply to recreate the equivalent access level directly under the folder-scoped policy.</p><h4>#4 — enforcement can lag without a real org-level policy backing the scope</h4><p>Early in this test, a folder-scoped perimeter (folder-test, protecting first-project, restricting storage.googleapis.com, Enforced) was in place — and yet the target bucket was still fully browsable. It only started returning <strong>&quot;Denied by VPC security control policy&quot;</strong> once the organization&#39;s policy hierarchy was fully in place end-to-end. If a scoped-policy perimeter appears to be doing nothing, don&#39;t assume the perimeter config is wrong first — check that the org-level policy prerequisite documented in Part 1 is actually satisfied for that resource&#39;s scope.</p><p>✅ <strong>Takeaway:</strong> Scoped policies are how you delegate VPC SC administration without granting org-wide Access Context Manager permissions. The tradeoffs: one policy per project, and zero automatic sharing of access levels across policy boundaries.</p><h4>6️⃣ Perimeter Bridges — Letting Two Perimeters Talk to Each Other</h4><p>With trust-project-ok and untrust-project-x each sitting inside their <strong>own</strong> regular perimeter (protect-trust-project and protect-untrust-project, both restricting storage.googleapis.com), cross-project access was denied <strong>in both directions</strong> — each perimeter protects its own project, full stop, even against another protected project.</p><pre># From trust-vm  → untrust-project-x&#39;s bucket   → ❌ denied<br># From untrust-vm → trust-project-ok&#39;s bucket    → ❌ denied</pre><p>A <strong>perimeter bridge</strong> is a third, special perimeter type that creates bidirectional access between two <em>existing regular</em> perimeters, without merging their access levels or restricted-service lists:</p><pre>Title             : bridge<br>Perimeter type    : Bridge<br>Resources         : trust-project-ok, untrust-project-x<br>Enforcement mode  : Enforced</pre><pre># Same commands as above, run again after the bridge was created → ✅ both succeed</pre><h4>Rules worth internalizing before you reach for a bridge</h4><ul><li>A project <strong>must already belong to a regular perimeter</strong> before it can be added to a bridge — bridges connect perimeters, not bare projects.</li><li>Bridges are <strong>bidirectional only</strong> — you can’t build a one-way bridge (use ingress/egress rules for asymmetric access instead).</li><li>Bridges <strong>cannot cross organizations</strong>, and <strong>cannot cross scoped policies</strong> — for that, ingress/egress rules are the only option.</li><li>Once a project is in a bridge, you can no longer add its VPC networks to a <em>different</em> perimeter.</li><li>A project can have multiple bridges to multiple other projects, but access levels and restricted services always remain governed solely by the project’s own regular perimeter — a bridge only opens the door, it doesn’t relax what’s on the other side of it.</li></ul><p>✅ <strong>Takeaway:</strong> Reach for a bridge when two already-protected projects need routine bidirectional access to each other’s restricted services. Reach for ingress/egress rules when the access needs to be asymmetric, narrower, or cross a scoped-policy boundary.</p><h4>7️⃣ VPC Service Controls with Shared VPC</h4><p>The final scenario: a <strong>Shared VPC</strong> host project (host-project-333) exposing three environment-specific networks — dev-vpc, prod-vpc, staging-vpc — to two service projects, trust-project-ok and untrust-project-x, each running VMs on all three networks.</p><p>The final scenario: a <strong>Shared VPC</strong> host project (host-project-333) exposing three environment-specific networks — dev-vpc, prod-vpc, staging-vpc — to two service projects, trust-project-ok and untrust-project-x, each running VMs on all three networks.</p><pre>host-project-333<br> ├── dev-vpc      (subnet-asia, asia-south1)<br> ├── prod-vpc     (subnet-eu,   europe-west1)<br> └── staging-vpc  (subnet-us,   us-central1)<br><br>Attached service projects: trust-project-ok, untrust-project-x</pre><p>The key capability this part demonstrates: you can build <strong>one perimeter per VPC network inside a Shared VPC host project</strong>, instead of one perimeter for the whole host project. That means dev, prod, and staging can each carry a completely different VPC SC posture even though they share a host.</p><pre>Perimeter        : test-network<br>Resources        : host-project-333 (project) + dev-vpc (network only)<br>Restricted APIs  : storage.googleapis.com<br>Enforcement mode : Enforced</pre><h4>The test</h4><pre># From dev-vm (on the now-protected dev-vpc)<br>$ gsutil ls gs://trust-dev-bucket-333/       # ✅ before the perimeter existed<br>$ gsutil ls gs://trust-dev-bucket-333/       # ❌ after: AccessDeniedException 403</pre><p>VMs on prod-vpc and staging-vpc — same host project, same organization, same Shared VPC — were completely unaffected, because the perimeter&#39;s <strong>Resources to protect</strong> explicitly scoped it to dev-vpc and nothing else.</p><h4>Restoring access surgically with an egress rule</h4><p>Rather than removing the perimeter, I added an egress rule scoped to the service account making the call:</p><pre>Rule name  : allow-storage-bucket-rule<br>From<br>  Identities : Any service account<br>  Sources    : trust-project-ok<br>To<br>  Resources  : trust-project-ok<br>  Operations : bigquery.googleapis.com, storage.googleapis.com</pre><pre>$ gsutil ls gs://trust-dev-bucket-333/<br>gs://trust-dev-bucket-333/                                  # ✅ restored</pre><h4>Rules for VPC networks inside a perimeter</h4><ul><li>If the host project itself is <strong>not</strong> already protected by a perimeter, its individual VPC networks can be split across separate perimeters under the same access policy.</li><li>All VPC networks belonging to the same host project must sit under the <strong>same</strong> access policy.</li><li>A host project and its VPC networks must not be split across <strong>different</strong> perimeters simultaneously in a conflicting way — a network and its parent project can’t end up in two places.</li><li>A VPC network <strong>cannot</strong> belong to more than one perimeter.</li><li>A VPC network <strong>cannot</strong> be used inside a perimeter <strong>bridge</strong> — bridges only operate at the project level.</li><li>If a VPC network’s parent project is part of a bridge, that network can no longer be added to a regular perimeter.</li></ul><p>✅ <strong>Takeaway:</strong> Shared VPC and VPC SC compose cleanly down to the individual network level — you’re not forced to give every environment sharing a host project the same security posture. Combine network-scoped perimeters with narrow egress rules to keep least-privilege intact without duplicating host projects per environment.</p><h4>🧾 The Gotchas, All in One Place</h4><pre>1. Access Context Manager is an ORG-level resource — grant the role at the<br>   organization, not the project, or the console won&#39;t even load.<br><br>2. Restricting compute.googleapis.com also breaks IAP/SSH-in-browser —<br>   restrict it deliberately.<br><br>3. Project-scoped perimeters ≠ VPC-network-scoped perimeters. One protects<br>   the resource regardless of caller location; the other protects calls<br>   made FROM inside that network.<br><br>4. Access levels don&#39;t stack automatically across True/False polarity —<br>   name them so the direction of the condition is obvious.<br><br>5. A project (or folder) can belong to exactly ONE access-policy perimeter<br>   across the whole org — org-level or scoped, never both, never two scoped<br>   policies at once.<br><br>6. Access levels are scoped to the access policy they were created under —<br>   an org-level access level is invisible to a folder-scoped perimeter&#39;s<br>   configuration UI, and vice versa.<br><br>7. Ingress rules treat &quot;user account&quot; and &quot;service account&quot; as distinct<br>   identity classes — &quot;any identity&quot; quietly includes both.<br><br>8. Perimeter bridges require both projects to already sit inside a regular<br>   perimeter, are bidirectional-only, and can&#39;t cross orgs or scoped<br>   policies.<br><br>9. A VPC network can&#39;t be added to a bridge, and can&#39;t belong to more than<br>   one perimeter — plan Shared VPC network-level perimeters carefully.</pre><h3>✅ Conclusion</h3><p>✅ Two real GCP projects, deliberately over-permissioned, with every test run against a live perimeter — not a conceptual walkthrough <br>✅ Project-scoped <strong>and</strong> VPC-network-scoped perimeters, proven with the same command succeeding or failing depending on where it ran <br>✅ Access levels (IP range, geography, polarity, dependencies) layered on top of a perimeter as trusted exceptions <br>✅ Ingress/egress rules narrowing access down to a specific identity type and a specific API surface <br>✅ Scoped policies for delegated administration — and the “one policy per project” rule that breaks if you don’t plan for it <br>✅ Perimeter bridges for bidirectional access between two already-protected projects <br>✅ Shared VPC combined with VPC SC down to the individual network level, restored surgically with an egress rule</p><p>VPC Service Controls rewards hands-on testing more than almost any other GCP security feature, precisely because so much of its behavior is <em>contextual</em> — the same gsutil ls command succeeds or fails depending on which VM ran it, which network it&#39;s attached to, which policy governs the target project, and which rule (if any) opened a narrow exception. None of that is visible from IAM alone.</p><p>If you’re rolling this out on a production organization, my one hard recommendation: <strong>build everything in Dry Run mode first</strong>, review the Violation Dashboard against real traffic for a few days, and only then flip to Enforced. The gotchas above are exactly the kind of thing that show up as a 3 a.m. page if you enforce blind.</p><h3>📸 Snapshots</h3><p>Every configuration step above has a real GCP Console (or Cloud Shell / SSH-in-browser) screenshots</p><p>🔗 <a href="https://github.com/bikram-singh/gcp-vpc-sc-perimeters/tree/main/docs/snapshots">All GCP Console screenshots</a></p><h3>🔗 Repository</h3><p><a href="https://github.com/bikram-singh/gcp-vpc-sc-perimeters"><strong>gcp-vpc-sc-perimeters</strong></a> — VPC Service Controls hands-on lab · Perimeters · Access Levels · Ingress/Egress · Scoped Policies · Perimeter Bridges · Shared VPC · Google Cloud Platform</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f27556c221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sensor to Diagnosis: A Real-Time GCP Telemetry Pipeline]]></title>
            <link>https://medium.com/@bikram23march/from-sensor-to-diagnosis-a-real-time-gcp-telemetry-pipeline-d873a3c0524a?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d873a3c0524a</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 10:41:07 GMT</pubDate>
            <atom:updated>2026-09-14T10:41:07.889Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Pub/Sub → Dataflow → BigQuery → Gemini 2.5 Flash→ Looker</strong></p><p><strong>Looker Studio dashboard:</strong> <a href="https://datastudio.google.com/embed/reporting/a6052335-bf85-4d05-a74e-df423a67dd15/page/xgk8F">Machine Telemetry &amp; AI Incident Monitoring</a></p><h3>🌟 Introduction</h3><p>This article builds a real-time GCP streaming pipeline using Cloud Pub/Sub, Cloud Dataflow (Apache Beam), BigQuery, and Gemini 2.5 Flash a system that watches simulated factory machine telemetry (temperature + vibration), computes rolling 1-minute averages per machine, and the moment a machine crosses a safety threshold, automatically asks Gemini to diagnose the likely root cause and logs it as a permanent incident. Every service below was deployed for real, debugged against real GCP errors, and verified with real breaches producing real Gemini output in BigQuery not a static demo.</p><h3>🏭 The Problem, In Plain Terms</h3><p>Picture a factory floor. Rows of machines running around the clock motors, compressors, pumps, whatever the plant makes its living from. Each one has a temperature sensor and a vibration sensor bolted on, quietly reporting numbers every couple of seconds.</p><p>Two things go wrong with machines like this, and they both give you a warning if you’re listening:</p><ul><li>🌡️ <strong>They get hot before they fail.</strong> Rising temperature usually means friction, a cooling problem, or a part working harder than it should.</li><li>📳 <strong>They shake before they break.</strong> Rising vibration usually means a bearing wearing out, something coming loose, or parts drifting out of alignment.</li></ul><p>The problem in most plants isn’t a lack of sensors it’s that nobody’s watching the numbers <em>continuously</em>, and even when someone is, “average temperature over the last minute is a bit high” doesn’t tell a technician <em>what to actually go check</em>. You want two things: something that never gets tired of watching a screen, and something that turns “80.57°C” into “this looks like impaired heat dissipation inspect cooling first.”</p><p><strong>In plain terms, here’s the relay race the data runs:</strong></p><ol><li><strong>Sensors → mailroom.</strong> Every machine’s readings get dropped into a queue (Pub/Sub) as fast as they’re produced. Nothing gets lost even if the next step is momentarily busy.</li><li><strong>Mailroom → calculator.</strong> A continuously-running calculator (Dataflow) picks up every message, throws out anything malformed, and keeps a running 1-minute average per machine for both temperature and vibration.</li><li><strong>Calculator → permanent record book.</strong> Every minute’s average gets written to a database (BigQuery) the full history, queryable anytime.</li><li><strong>Calculator → alarm bell.</strong> If a machine’s average temperature goes over 80°C, <em>or</em> its vibration goes over 5.0 mm/s, an alert fires immediately.</li><li><strong>Alarm bell → smart assistant.</strong> A cloud function catches that alert and asks Gemini 2.5 Flash: <em>given these numbers, what’s the likely mechanical issue, and what should a technician check first?</em> The answer gets logged as an incident, permanently, alongside the numbers that triggered it.</li></ol><p>No human has to be staring at a dashboard for this to work the system watches, decides, and explains itself.</p><h3>🧰 Tech Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*09iJ5Hxxx8iqPGgg1M297Q.png" /></figure><h3>🏛️ Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g60SOQxOgbcwypNP0DOwQg.png" /></figure><pre>                              [ SIMULATED FACTORY TELEMETRY ]<br>                                          │<br>                         (JSON: machine_id, temperature, vibration, timestamp)<br>                                          │<br>                                          ▼<br>┌───────────────────────────────────────────────────────────────────────────────────────────┐<br>│  INGESTION LAYER            (VPC: telemetry-vpc  /  Subnet: telemetry-subnet)             │<br>│                                   ┌──────────────────────────┐                            │<br>│                                   │        Pub/Sub           │                            │<br>│                                   │   telemetry-input-topic  │                            │<br>│                                   └────────────┬─────────────┘                            │<br>└────────────────────────────────────────────────┼──────────────────────────────────────────┘<br>                                                 │<br>                                                 ▼<br>┌───────────────────────────────────────────────────────────────────────────────────────────┐<br>│  STREAM PROCESSING LAYER      (Private workers, no public IP  /  Cloud NAT egress)        │<br>│                          ┌────────────────────────────────────┐                           │<br>│                          │      Dataflow Flex Template        │                           │<br>│                          │   (Apache Beam, sa-dataflow-worker)│                           │<br>│                          │  1-min tumbling window · avg_temp, │                           │<br>│                          │  avg_vibration per machine_id      │                           │<br>│                          └──────────┬──────────────────┬──────┘                           │<br>└─────────────────────────────────────┼──────────────────┼──────────────────────────────────┘<br>                   (Windowed Averages)│                  │ (Malformed Payload)<br>                                      ▼                  ▼<br>┌────────────────────────────────────────┐   ┌───────────────────────────────────────────┐<br>│  ANALYTICS &amp; STORAGE LAYER             │   │  DEAD-LETTER QUEUE                        │<br>│  BigQuery: telemetry_analytics         │   │  Pub/Sub: telemetry-dlq-topic             │<br>│   └─ telemetry_aggregates              │   │  (Cloud Monitoring alert on backlog)      │<br>│      (clustered on machine_id)         │   └───────────────────────────────────────────┘<br>└────────────────────┬───────────────────┘<br>                     │<br>        (avg_temperature &gt; 80.0°C  OR  avg_vibration &gt; 5.0 mm/s)<br>                     ▼<br>┌───────────────────────────────────────────────────────────────────────────────────────────┐<br>│  AI &amp; INCIDENT RESPONSE LAYER                                                             │<br>│  ┌────────────────────┐   ┌───────────────────────┐   ┌──────────────────────────────┐    │<br>│  │     Pub/Sub        │──►│   Cloud Function      │──►│      Gemini 2.5 Flash        │    │<br>│  │ telemetry-alerts-  │   │  gemini-diagnostics   │   │   (google-genai SDK,         │    │<br>│  │      topic         │   │  (gen2, Eventarc,     │   │    Vertex AI backend)        │    │<br>│  │                    │   │   sa-gemini-function) │   │  Root-cause diagnostic brief │    │<br>│  └────────────────────┘   └───────────────────────┘   └──────────────┬───────────────┘    │<br>│                                                                        │                  │<br>│                                                                        ▼                  │<br>│                                              BigQuery: telemetry_analytics.incident_log   │<br>└───────────────────────────────────────────────────────────────────────────────────────────┘</pre><p><strong>A few deliberate departures from the typical reference architecture for this kind of pipeline and the reasoning behind each:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*ECdC-yFa92vdw2VFti2dvQ.png" /></figure><p>None of these are corrections to the generic version they’re the kind of decisions you actually make once you’re building for a specific use case instead of a general-purpose demo.</p><h3>🔄 Layer Breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*-F6HLihYqTEbbiiOzULs_A.png" /></figure><h3>🧱 What It Does</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ydplZPNfzkRKmhIUwNpS7w.png" /></figure><h3>🛠️ Under the Hood</h3><p>The core of the Dataflow job is a straightforward Beam pipeline: parse and validate incoming JSON (routing anything malformed to a dead-letter topic instead of crashing the pipeline), window into 1-minute tumbling windows, compute per-machine averages for both temperature and vibration, write to BigQuery, and fork a second branch that checks each windowed average against a threshold:</p><pre>class FilterAndFormatAlertsFn(beam.DoFn):<br>    def process(self, element):<br>        avg_temp = element[&#39;avg_temperature&#39;]<br>        avg_vib = element[&#39;avg_vibration&#39;]<br>        if avg_temp &gt; 80.0 or avg_vib &gt; 5.0:<br>            alert_payload = {<br>                &#39;machine_id&#39;: element[&#39;machine_id&#39;],<br>                &#39;avg_temperature&#39;: avg_temp,<br>                &#39;avg_vibration&#39;: avg_vib,<br>                &#39;window_end&#39;: element[&#39;window_end&#39;]<br>            }<br>            yield beam.pvalue.TaggedOutput(<br>                self.TAG_ALERT,<br>                json.dumps(alert_payload).encode(&#39;utf-8&#39;)<br>            )</pre><p>One design choice worth calling out: <strong>1-minute tumbling windows, not the 5-minute sliding windows</strong> you’ll see in most reference architectures. Sliding windows are more “textbook,” but tumbling windows are simpler to reason about and cheaper to compute a deliberate trade-off for a lab-scale system, not a limitation.</p><h3>🧠 The AI Layer</h3><p>When a breach fires, a 2nd-gen Cloud Function triggered via Eventarc on the alert topic calls Gemini 2.5 Flash with the breach context and asks for a concise operational diagnostic:</p><pre>response = gemini_client.models.generate_content(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    contents=prompt<br>)</pre><p>The result gets written to a BigQuery incident_log table alongside a deterministic idempotency key (a hash of machine_id + window_end), so a retried Eventarc delivery doesn&#39;t create a duplicate incident.</p><p><strong>Here’s a real one, generated from an actual detected breach during testing not a hand-crafted example:</strong></p><p><em>“Elevated vibration exceeding its threshold (5.19 mm/s) strongly indicates a developing mechanical fault on MCH-PLANT-01–002, such as imbalance, misalignment, or bearing degradation. Immediately initiate a physical inspection for loose components, unusual noises, or visible damage…”</em></p><h3>⚠️ Real Deployment Gotchas (Found &amp; Fixed)</h3><p><strong>1. Org policy silently blocked Dataflow workers.</strong> GCP org policy blocks external IPs on Compute Engine VMs by default. Dataflow’s launcher VM requests one unless you pass --disable-public-ips without it, the job dies in ~1 second with no useful error, only findable by digging into Cloud Logging.</p><p><strong>2. Cloud Build’s default service account lost its auto-granted permissions.</strong> Newer GCP projects no longer auto-grant Editor to the Cloud Build service account, silently breaking every Cloud Functions gen2 deploy. Two different service accounts can be the actual builder depending on project age — granting the wrong one repeats the same error.</p><p><strong>3. Artifact Registry read access for the Dataflow launcher.</strong> The launcher VM needs artifactregistry.reader to pull its own container image. Without it, it boots fine, then fails four docker pull retries and gives up.</p><p><strong>4. Eventarc can authenticate but still can’t invoke.</strong> A gen2 Cloud Function triggered by Pub/Sub is a Cloud Run service underneath. Eventarc’s service account needs roles/run.invoker on that Cloud Run service specifically a separate grant most people don&#39;t think to set up front.</p><p><strong>5. Zone-level resource exhaustion.</strong> ZONE_RESOURCE_POOL_EXHAUSTED a real, temporary Compute Engine capacity shortage, not a bug. Fixed by switching the worker machine type to e2-standard-2, a different capacity pool.</p><p><strong>6. PowerShell’s backtick escaping ate part of a query — twice.</strong> `t in a PowerShell here-string is a tab character, not a literal backtick-t it silently corrupted a BigQuery table reference. Fixed with single-quoted (@&#39;...&#39;@) here-strings, which skip escape processing entirely.</p><p><strong>7. Toolchain version drift.</strong> Local Python 3.14 was too new for Apache Beam’s prebuilt wheels, so grpcio-tools tried building from source and failed. The fix was trusting CI&#39;s pinned Python 3.12 runner instead of fighting the local environment.</p><p>None of these are exotic. Any one of them will cost you an afternoon if you hit it cold. Together, they’re the actual content of “deploying to GCP” that a clean architecture diagram never shows.</p><h3>🧪 Testing</h3><p>Beyond manual end-to-end verification (slow, and it costs real GCP resources every time), the repo has a proper unit test layer:</p><ul><li><strong>11 tests</strong> on the Beam pipeline logic parsing/DLQ routing, the averaging math, and the OR-threshold breach logic, including an explicit boundary test pinning that exactly 80.0°C is <em>not</em> a breach (strict &gt;, not &gt;=)</li><li><strong>5 tests</strong> on the Cloud Function successful incident logging, idempotency-key stability across retried deliveries, malformed-payload handling, and graceful (non-crashing) handling of a BigQuery insert error</li></ul><p>Both suites run in under 4 seconds combined and gate every CI deploy a broken pipeline or function never reaches terraform apply, let alone a live GCP resource.</p><h3>🔁 CI/CD</h3><p>GitHub Actions, authenticated via Workload Identity Federation no static service account keys anywhere in the repo or its secrets. The pipeline: validate Terraform → run unit tests → apply infrastructure → build the Dataflow Flex Template and Docker image → deploy the Cloud Function → launch or update the Dataflow job idempotently (a fixed job name plus a conditional --update flag, so redeploys update the running pipeline in place instead of spinning up a duplicate job that splits Pub/Sub consumption).</p><h3>🎯 What a Real Run Looks Like</h3><pre>#1  python simulator/publisher.py<br>    → publishing telemetry for MCH-PLANT-01-001, MCH-PLANT-01-002,<br>      MCH-PLANT-02-005 every 2 seconds, ~5% malformed test payloads<br><br>#2  gcloud dataflow jobs list --region=us-central1 --status=active<br>    → JOB_STATE_RUNNING, telemetry-pipeline-lab, us-central1-a<br><br>#3  SELECT machine_id, avg_temperature, avg_vibration, window_end<br>    FROM telemetry_analytics.telemetry_aggregates<br>    ORDER BY calculated_at DESC LIMIT 10<br>    → real per-machine averages, one row per 1-minute window<br><br>#4  A window crosses the threshold naturally — avg_vibration: 5.19<br>    → Pub/Sub alert → Cloud Function → Gemini 2.5 Flash<br><br>#5  SELECT * FROM telemetry_analytics.incident_log<br>    ORDER BY detected_at DESC LIMIT 5<br>    → &quot;Elevated vibration exceeding its threshold (5.19 mm/s)<br>       strongly indicates a developing mechanical fault on<br>       MCH-PLANT-01-002...&quot;</pre><p>Independently verified across a genuine 10-minute background run, not a single forced test case 7 distinct real incidents logged, each with its own Gemini-generated diagnostic.</p><h3>✅ Conclusion</h3><p>✅ Real-time streaming pipeline, Pub/Sub → Dataflow → BigQuery, fully live-tested <br>✅ Dual-metric (temperature + vibration) breach detection with an OR-threshold, not a single-signal demo <br>✅ Gemini 2.5 Flash generating genuine root-cause diagnostics on real breaches <br>✅ Idempotent incident logging a deterministic key stops duplicate incidents on retry <br>✅ Fully Terraform-managed, including IAM, networking, and CI/CD infrastructure itself <br>✅ 16-test-gated GitHub Actions pipeline, keyless via Workload Identity Federation</p><h3>📸 Snapshots</h3><p>Real, live provisioning through the deployed pipeline simulator to Terraform apply, live verification, and the dashboard build walkthrough. Every screenshot below is from an actual run, not simulated.</p><p><a href="http://github.com/bikram-singh/gcp-streaming-telemetry-pipeline/blob/main/docs/screenshots/cicd-01-github-actions-success.png"><strong>CI/CD — GitHub Actions, full green run</strong></a></p><p><a href="https://github.com/bikram-singh/gcp-streaming-telemetry-pipeline/blob/main/docs/screenshots/verify-01-simulator-running.png"><strong>Live Pipeline Verification simulator, Dataflow job, BigQuery</strong></a></p><p><a href="https://github.com/bikram-singh/gcp-streaming-telemetry-pipeline/blob/main/docs/screenshots/looker-09-dashboard-live-view.png"><strong>Looker Studio Dashboard build walkthrough</strong></a></p><h3>🔗 Repository</h3><p><a href="https://github.com/bikram-singh/gcp-streaming-telemetry-pipeline"><strong>gcp-streaming-telemetry-pipeline</strong></a> — Real-time telemetry pipeline · Dataflow · BigQuery · Gemini 2.5 Flash · Terraform · Google Cloud Platform</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d873a3c0524a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Built a Cloud Armor WAF Lab, Then Tried to Break It]]></title>
            <link>https://medium.com/@bikram23march/built-a-cloud-armor-waf-lab-then-tried-to-break-it-2bc525af4186?source=rss-e8ab82576afb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bc525af4186</guid>
            <dc:creator><![CDATA[Bikram Singh]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 09:48:53 GMT</pubDate>
            <atom:updated>2026-09-10T09:48:53.410Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Terraform · Google Cloud Armor · GitHub Actions · Workload Identity Federation · Live Attack Testing</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UDh109Itc0vz3ifH_nj3A.png" /></figure><p>📋 Table of Contents</p><ul><li>🌟 Introduction</li><li>🔑 Key Facts</li><li>✨ What It Does</li><li>🏗️ What We Are Building</li><li>🏛️ Architecture</li><li>🎯 Capabilities, In the Order They Were Actually Tested</li><li>📖 The Full Build Log — Every Step, In Detail</li><li>⚠️ Prerequisites &amp; Reproduction</li><li>🐛 What a Real Bug Getting Caught Looks Like</li><li>📊 The Real Numbers</li><li>✅ Conclusion</li><li>📸 Snapshots</li><li>🔗 Repository</li></ul><h3>🌟 Introduction</h3><p>This article builds a Google Cloud Armor lab with Terraform, wires it into a real GitHub Actions CI/CD pipeline, and then does the part most Cloud Armor content skips entirely: actually attacks it. Real SQL injection. Real stored XSS. Real brute-force login attempts. A real request from an actual US-origin VM to prove geo-blocking, not just claim it. Every error below is one I actually hit, in the order I hit it — and in a few cases, testing proved my own starting assumption wrong, which is documented here exactly as it happened, not cleaned up afterward.</p><h3>🔑 Key Facts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*mmxfQeAqZrVz0mObt2kWbw.png" /></figure><h3>✨ What It Does</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*F1n9Lq4WaSi40ggIdoLh8g.png" /></figure><h3>🏗️ What We Are Building</h3><p>A lab where this:</p><pre>curl -sk -X POST &quot;https://vulnbank-lab.&lt;domain&gt;/login&quot; \<br>  -d &quot;username=admin&#39; UNION SELECT 1,2,3--&amp;password=x&quot; \<br>  -o /dev/null -w &quot;%{http_code}\n&quot;</pre><p>turns into a real, logged, verifiable block — not a claim:</p><pre>&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;DENY&quot;,<br>  &quot;matchedFieldName&quot;: &quot;username&quot;,<br>  &quot;matchedFieldValue&quot;: &quot;&#39; UNION S&quot;,<br>  &quot;preconfiguredExprIds&quot;: [&quot;owasp-crs-v030301-id942190-sqli&quot;],<br>  &quot;priority&quot;: 1000<br>}<br><br>HTTP 403</pre><p>Concretely, this means:</p><ul><li>Two Compute Engine VMs behind a shared Cloud Armor policy — an nginx VM for simple path-based rule demos, and a real Flask banking app (<a href="https://github.com/Commando-X/vuln-bank">Commando-X/vuln-bank</a>) for real attack testing</li><li>Global HTTPS Load Balancers with trusted, Google-managed SSL certificates on real subdomains</li><li>A Cloud Armor policy covering WAF (SQLi/XSS), rate limiting, IP/geo/ASN access control, redirects, and preview mode</li><li>Regional and edge security policies, tested separately for precedence</li><li>A working CI/CD pipeline: GitHub Actions, Terraform, HCP Terraform state, Workload Identity Federation</li><li>An automated daily security regression suite</li><li>Cloud Monitoring alerting and BigQuery log export</li><li>An incident response runbook</li></ul><h3>🏛️ Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYhqSTkWjBT9DqVUmSJ4pQ.png" /></figure><pre>                    Internet<br>                       │<br>        ┌──────────────┴──────────────┐<br>        ▼                             ▼<br>  nginx-lab.&lt;domain&gt;          vulnbank-lab.&lt;domain&gt;<br>  (Google-managed cert)       (Google-managed cert, IPv6 frontend)<br>        │                             │<br>   nginx-https-proxy          vulnbank-https-proxy<br>        │                             │<br>   nginx-backend  ◄── shared ──►  vulnbank-backend<br>        │         Cloud Armor          │<br>        │       (lab-baseline-policy)  │<br>        ▼                             ▼<br>  nginx VM (path-demo)     vulnbank VM (Flask, :5000)<br><br>  Cloud Armor policy layers, evaluated in this order:<br>    Edge policy      ──► IP-range only, wins before backend is even checked<br>    Backend policy    ──► WAF, rate-limit, IP/geo/redirect rules<br>    Regional policy   ──► separate policy type, own regional LB required<br><br>  Cross-cutting:<br>    Cloud Monitoring  ── deny-rate-spike + policy-change alerts<br>    BigQuery export   ── all LB/Cloud Armor logs<br>    Daily regression  ── scripts/security-regression-tests.sh via Actions</pre><p>🏗️ Why does JA3 and JA4 each get their own dedicated path instead of sharing /login or /transfer with the other rate-limit rules? Because the first version didn&#39;t, and it broke — twice. Two rate-limit or redirect rules matching the same or overlapping traffic on one path always have exactly one that actually wins, whichever sits at the lower priority number, and fixing one collision this way can silently create a new one elsewhere. It happened four separate times in this project before the pattern was obvious enough to fix permanently, for every rule, not just the one currently broken.</p><h3>🎯 Capabilities, In the Order They Were Actually Tested</h3><p>Listed in the real order testing happened, not a curated “logical” order:</p><ol><li><strong>HTTPS and domain setup</strong> — self-signed to Google-managed cert</li><li><strong>The priority-10 bug</strong> — an allow-all rule silently bypassing every other rule in the policy</li><li><strong>Logging, instance-group, and line-ending fixes</strong> — infrastructure had to be stable before attack testing could start</li><li><strong>SQL injection and XSS</strong> — 4 distinct payload shapes, 4 different CRS rule IDs</li><li><strong>Rate limiting and bans</strong> — throttle and hard-ban, both confirmed with real thresholds</li><li><strong>Geo-blocking</strong> — from a real temporary us-central1 VM, not simulated</li><li><strong>JA3/JA4 TLS fingerprinting</strong> — real browser-vs-curl independence confirmed</li><li><strong>Redirects and preview mode</strong> — including a reCAPTCHA rule confirmed inert without Enterprise</li><li><strong>Regional and edge policy precedence</strong> — edge deny confirmed to win before backend is evaluated</li><li><strong>Corrected assumptions</strong> — user_ip_request_headers, logging verbosity, WAF sensitivity, field exclusions</li><li><strong>CI/CD</strong> — six real bugs, Workload Identity Federation, working end to end</li><li><strong>Automated regression testing</strong> — caught a real bug on its first scheduled run</li><li><strong>Monitoring, BigQuery export, incident runbook</strong></li></ol><p>The list above is the compact version. Here’s the same ground covered in full detail — every real error message, every log excerpt, every fix.</p><h3>📖 The Full Build Log — Every Step, In Detail</h3><h4>🏗️ Step 1: HTTPS and Domain Setup</h4><p>The lab started with self-signed certificates — functional, but every browser flags them “Not Secure.” Certificates require domain ownership, not just an IP, so the first real step was pointing real subdomains at the load balancers.</p><p>I extended the https-lb Terraform module to support Google-managed SSL certificates conditionally — self-signed if no domain is supplied, a real managed cert if one is:</p><pre>resource &quot;google_compute_managed_ssl_certificate&quot; &quot;this&quot; {<br>  count   = var.domain_name != null ? 1 : 0<br>  project = var.project_id<br>  name    = &quot;${var.name_prefix}-managed-cert&quot;<br><br>  managed {<br>    domains = [var.domain_name]<br>  }<br>}</pre><p>DNS turned out to be hosted at Hostinger (not a separate parking service, as I first assumed). Adding A records for nginx-lab.&lt;domain&gt; and vulnbank-lab.&lt;domain&gt;, waiting for propagation, and confirming both certificates went ACTIVE in the GCP Console gave the lab real, trusted HTTPS.</p><p><strong>A small but real bug along the way</strong>: nginx’s demo pages started showing mojibake — Cloud Armor Lab â€&quot; nginx backend instead of a proper em-dash. The root cause was a missing UTF-8 charset declaration. Fixed by adding &lt;meta charset=&quot;UTF-8&quot;&gt; to the nginx startup script and, to be safe against further Windows/PowerShell encoding round-trips, switching to plain ASCII hyphens instead of em-dashes entirely.</p><h4>🐛 Step 2: The Bug That Bypassed Every Rule in the Policy</h4><p>This was the first serious finding, and arguably the most important one architecturally.</p><p>The baseline Cloud Armor policy had two rules: a permissive allow-all at <strong>priority 10</strong>, and a catch-all deny at the lowest possible priority (2147483647). The intent was to demonstrate priority ordering. The actual effect: since Cloud Armor evaluates rules in ascending priority order and stops at the first match, <strong>priority 10 beat every single other rule in the policy</strong> — every WAF rule, every rate limit, every path-based rule, all silently bypassed.</p><pre># BEFORE — this rule beat everything<br>{<br>  priority      = 10<br>  action        = &quot;allow&quot;<br>  src_ip_ranges = [&quot;*&quot;]<br>}</pre><p>Removing it initially broke <em>all</em> traffic — the catch-all deny at the bottom took over completely, since nothing else was left to allow legitimate requests. The real fix was adding a proper baseline-allow rule at <strong>priority 9000</strong> — low enough to sit below every genuine rule (SQLi at 1000, path rules at 3000, rate limits at 4000, and so on), but high enough to still be beaten by anything more specific.</p><pre># AFTER<br>{<br>  priority      = 9000<br>  action        = &quot;allow&quot;<br>  description   = &quot;Baseline allow -- explicit default-allow posture&quot;<br>  src_ip_ranges = [&quot;*&quot;]<br>}</pre><p>Lesson: a demo rule meant to <em>illustrate</em> priority ordering became a rule that <em>defeated</em> priority ordering, for every rule that mattered, until it was caught.</p><h4>🔧 Step 3: Three More Real Infrastructure Bugs</h4><p>Before any real attack testing could happen, three more genuine bugs surfaced.</p><p><strong>No logs, despite real denied traffic.</strong> After the priority-10 fix, I ran a deny test and went to check the logs — empty. Completely empty, despite a confirmed 403 response. The cause: Cloud Armor&#39;s own log_level setting on the <em>policy</em> controls verbosity, but doesn&#39;t generate logs at all by itself. The <em>backend service</em> needs its own log_config.enable = true:</p><pre>resource &quot;google_compute_backend_service&quot; &quot;this&quot; {<br>  # ...<br>  log_config {<br>    enable      = true<br>    sample_rate = 1.0<br>  }<br>}</pre><p><strong>“Unconditional drop overload.”</strong> Later, after replacing a VM (a Terraform apply that destroyed and recreated the nginx instance), the load balancer started returning a strange, unfamiliar error: unconditional drop overload. This turned out to be a Google Front End message meaning <strong>zero healthy backends</strong> — not a Cloud Armor block at all.</p><p>The real cause: unmanaged instance groups silently lose membership when the VM behind them gets replaced, and Terraform doesn’t detect this drift, since the group’s instances list argument (a self-link string) doesn&#39;t actually change. The fix was a manual re-add:</p><pre>gcloud compute instance-groups unmanaged add-instances cloud-armor-lab-nginx-ig \<br>  --zone=us-central1-a --instances=cloud-armor-lab-nginx</pre><p>Documented as a known gotcha for anyone rebuilding VMs in this lab.</p><p><strong>Line-ending crash-loop.</strong> The vulnerable banking app’s start.sh kept crash-looping on the VM with exec format error — a classic sign of Windows CRLF line endings (or a stray UTF-8 BOM) in a script meant to run on Linux. Rather than modifying the pinned upstream submodule directly, the fix normalizes line endings in a <strong>temporary copy</strong> at build time, keeping the submodule untouched:</p><pre>Get-ChildItem $TempBuildDir -Filter *.sh -Recurse | ForEach-Object {<br>    $content = Get-Content $_.FullName -Raw<br>    $content = $content -replace &quot;`r`n&quot;, &quot;`n&quot;<br>    [System.IO.File]::WriteAllText($_.FullName, $content, [System.Text.UTF8Encoding]::new($false))<br>}</pre><h4>🎯 Step 4: Attacking It for Real</h4><p>With the infrastructure stable, this is where the actual security testing began — real payloads, real logs, real confirmation.</p><p><strong>SQL injection.</strong> Four distinct SQLi payload shapes were tried across the session, and Cloud Armor’s OWASP preconfigured rule caught all four — but with four <em>different</em> underlying CRS rule IDs, confirming these were genuinely distinct detection signatures, not one rule catching everything:</p><pre>curl -sk -X POST &quot;https://vulnbank-lab.&lt;domain&gt;/login&quot; \<br>  -d &quot;username=admin&#39; UNION SELECT 1,2,3--&amp;password=x&quot; \<br>  -o /dev/null -w &quot;%{http_code}\n&quot;<br># HTTP 403</pre><p>Log confirmation showed the exact matched field and rule:</p><pre>&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;DENY&quot;,<br>  &quot;matchedFieldName&quot;: &quot;username&quot;,<br>  &quot;matchedFieldValue&quot;: &quot;&#39; UNION S&quot;,<br>  &quot;preconfiguredExprIds&quot;: [&quot;owasp-crs-v030301-id942190-sqli&quot;],<br>  &quot;priority&quot;: 1000<br>}</pre><p>Across the session, rule IDs 942100, 942180, 942190, and 942200 all fired against different payload shapes — a real, useful data point about coverage breadth.</p><p><strong>Rate limiting.</strong> Both throttle and hard-ban behavior were confirmed with real threshold tests:</p><pre>Request 1: HTTP 200<br>Request 2: HTTP 200<br>...<br>Request 10: HTTP 200<br>Request 11: HTTP 429   &lt;- throttle threshold hit</pre><p>And separately, a rate-based ban on /transfer:</p><pre>&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;RATE_BASED_BAN&quot;,<br>  &quot;outcome&quot;: &quot;DENY&quot;,<br>  &quot;rateLimitAction&quot;: { &quot;outcome&quot;: &quot;BAN_THRESHOLD_EXCEED&quot; }<br>}</pre><p><strong>Geo-blocking, for real.</strong> Geo-blocking is easy to fake in a demo — most tutorials just claim a rule “would block” traffic from a region without ever testing it. I didn’t want to fake it, so I spun up a temporary Compute Engine VM in us-central1, SSH&#39;d in via IAP, and issued the request from inside actual US-origin infrastructure:</p><pre>user@temp-us-test-vm:~$ curl -sk -o /dev/null -w &quot;%{http_code}\n&quot; https://vulnbank-lab.&lt;domain&gt;/<br>403</pre><p>Confirmed via log: regionCode: &quot;US&quot;, priority: 2020, and the requesting IP genuinely belonged to Google&#39;s own US infrastructure (ASN 15169). The temporary VM was torn down immediately after.</p><p><strong>JA3/JA4 TLS fingerprint rate limiting.</strong> This one needed a real client-diversity test, not just curl. I throttled curl’s own TLS fingerprint against a dedicated path:</p><pre>curl request 1: HTTP 200<br>curl request 2: HTTP 200<br>curl request 3: HTTP 200<br>curl request 4: HTTP 200<br>curl request 5: HTTP 200<br>curl request 6: HTTP 429</pre><p>Then, <strong>immediately</strong>, opened the same URL in a real browser — different TLS handshake, different fingerprint:</p><p>Page loaded normally. VulnBank homepage rendered fully.</p><p>Same real IP, same real connection, same 60-second window — but a genuinely independent rate-limit bucket, because Cloud Armor keys on the TLS fingerprint, not the connection IP. Confirmed for both JA3 and JA4 independently.</p><p><strong>Redirect actions.</strong> An external 302 redirect fired cleanly. A GOOGLE_RECAPTCHA challenge rule, however, turned out to be <strong>completely inert</strong> without an actual reCAPTCHA Enterprise subscription — not &quot;renders without the visual challenge,&quot; but genuinely never fires at all, confirmed by comparing it directly against a working EXTERNAL_302 rule using identical CEL syntax at a higher-precedence priority. The reCAPTCHA rule simply never appeared in the enforcement log; traffic fell through to the next matching rule every time.</p><p><strong>Preview mode.</strong> A rule with preview = true produces a genuinely distinct log field — previewSecurityPolicy — showing exactly what it <em>would</em> have done, separate from the real enforcedSecurityPolicy outcome that actually governed the request:</p><pre>&quot;enforcedSecurityPolicy&quot;: { &quot;configuredAction&quot;: &quot;ALLOW&quot;, &quot;priority&quot;: 9000 },<br>&quot;previewSecurityPolicy&quot;: { &quot;configuredAction&quot;: &quot;DENY&quot;, &quot;preview&quot;: true, &quot;priority&quot;: 6000 }</pre><p>This is a genuinely useful, previously undocumented-for-me detail: if you’re validating a new rule safely, previewSecurityPolicy is the field to watch, not the main enforcement field.</p><p><strong>Regional and edge policies.</strong> Regional backend security policies needed a completely separate LB stack (Regional external Application Load Balancer, including a <strong>proxy-only subnet</strong> — the same requirement internal LBs have). Getting this working surfaced two real provider quirks: google_compute_region_backend_service requires the google-beta provider explicitly for security_policy to be accepted, and it needs an explicit capacity_scaler on its backend block that the global equivalent handles automatically.</p><p>Edge-vs-backend precedence produced the cleanest result of the whole project. A request from an IP matching an edge-policy deny rule got blocked — and the log showed <strong>only</strong> enforcedEdgeSecurityPolicy, with no enforcedSecurityPolicy field at all, meaning the backend policy (which had its own default-allow) was never even evaluated:</p><pre>&quot;enforcedEdgeSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;DENY&quot;,<br>  &quot;outcome&quot;: &quot;DENY&quot;,<br>  &quot;priority&quot;: 1000<br>}</pre><p>Latency on that request: 0.000911s. A genuine front-door check, confirmed.</p><p>I also learned edge policies attached to a <em>regular</em> backend service only support plain IP-range matches — a CEL expression rule gets rejected outright with Expression supported only for Media CDN edge policies.</p><h4>🔍 Step 5: When Testing Corrects the Documentation</h4><p>Some of the most valuable findings weren’t “this works as documented” — they were “this doesn’t work the way I assumed, and here’s what actually happens.”</p><p><strong>user_ip_request_headers — narrower than expected.</strong> The assumption going in: trusting X-Forwarded-For would make IP-based rules (origin.ip, origin.asn, plain src_ip_ranges) evaluate against the spoofed header instead of the real connection IP.</p><p><strong>Real testing disproved this twice</strong> — once with a plain IP-match rule, once with an explicit CEL origin.ip == rule. Both times, spoofing the header to match a denied value had no effect; the log showed the spoofed value recorded separately (securityPolicyRequestData.userIpInfo), while remoteIpInfo — what those rule types actually bind to — kept showing the real connection&#39;s data.</p><p>The real scope, found by isolating the one plausible remaining consumer: rate-limit enforce_on_key = &quot;XFF_IP&quot;. A test with the same real IP but different spoofed header values on each request confirmed each spoofed value got its own independent rate-limit bucket — genuine, confirmed, but far narrower than the original assumption.</p><p><strong>Logging verbosity — no observable difference.</strong> The assumption: VERBOSE logging shows richer detail than NORMAL. Three separate comparisons — two DENY events, one ALLOW event — showed <strong>identical field structure</strong> regardless of the setting. The original documentation claim doesn&#39;t hold up under real inspection, at least not for this policy&#39;s logged output.</p><p><strong>WAF sensitivity 2 — a severity-critical false positive.</strong> This is the most consequential finding in the whole project. Raising WAF sensitivity from 1 to 2 does catch more SQLi payload shapes — confirmed, a tautology payload (OR &#39;1&#39;=&#39;1&#39;) that sensitivity 1 missed got caught cleanly at sensitivity 2.</p><p>But testing also found sensitivity 2 <strong>completely blocks new user registration</strong> — plain values, no special characters at all:</p><pre>{&quot;username&quot;: &quot;testuser1&quot;, &quot;email&quot;: &quot;testuser1@example.com&quot;, &quot;password&quot;: &quot;SimplePass123&quot;}</pre><pre>{&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;DENY&quot;,<br>  &quot;outcome&quot;: &quot;DENY&quot;<br>}</pre><p>No matchedFieldName even appeared in that log entry — because json_parsing was DISABLED, Cloud Armor was scanning the raw, unstructured JSON body as one undifferentiated text blob, with no concept of field boundaries at all. Reverting to sensitivity 1 fixed it immediately; the same registration succeeded.</p><p><strong>This is the finding that decided the lab’s shipped default</strong>: sensitivity 1, not 2, despite the extra coverage — because a WAF that blocks legitimate signups isn’t a WAF you can actually ship.</p><p><strong>Field exclusions — an even more dangerous alternative.</strong> Given the sensitivity-2 problem, the obvious next question: could a scoped field exclusion fix registration while <em>keeping</em> sensitivity 2’s broader coverage? Tested directly — enabling json_parsing = STANDARD and excluding the username field from WAF inspection.</p><p>t worked. Registration succeeded.</p><p>It also broke something else. A real tautology SQLi payload (admin&#39; OR &#39;1&#39;=&#39;1&#39; --) sent to the <strong>login</strong> endpoint — a completely different feature — sailed through with a clean 200, because /login <em>also</em> has a field named username, and the exclusion doesn&#39;t scope to one endpoint. It scopes to the field name, globally, everywhere that name appears.</p><pre>&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;THROTTLE&quot;,<br>  &quot;outcome&quot;: &quot;ACCEPT&quot;<br>}</pre><p>No SQLi rule fired at all for that request. This is a genuinely dangerous, non-obvious risk: excluding a common field name (username, email, password) is dangerous <em>specifically because</em> it&#39;s common — an attacker who finds one excluded endpoint can potentially exploit any other endpoint sharing that field name. The lab ships sensitivity 1 as the safer, correctly-chosen default specifically because of this finding, documented in the repo rather than quietly adopted.</p><h4>🔁 Step 6: The Bug That Kept Coming Back</h4><p>One pattern repeated <strong>four separate times</strong> across the project, in different disguises:</p><p>Two rate-limit/action rules matching overlapping or unconditional traffic on one path always have exactly one that actually matters — whichever sits at the lower priority number — and fixing one collision can silently create a new one elsewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*MYlpTfHK0j8VR9aBTuvtyQ.png" /></figure><p>That fourth one is the best story in the whole project, because I didn’t find it. <strong>A tool I built found it.</strong></p><h4>⚙️ Step 7: Getting GitHub Actions Actually Working</h4><p>CI/CD was written early in the session and never triggered until much later. The first real trigger revealed, one at a time, six genuinely distinct bugs — each one a real lesson, not a typo.</p><p><strong>1. Per-step </strong><strong>env: doesn&#39;t persist.</strong> GitHub Actions env vars set on one step don&#39;t carry to the next step. terraform init had no token, despite the token being set on a <em>different</em> step:</p><pre># BEFORE — token only visible to this one step<br>- name: Setup Terraform<br>  env:<br>    TF_TOKEN_app_terraform_io: ${{ secrets.TF_TOKEN_APP_TERRAFORM_IO }}</pre><p>Fixed by moving env: to the <strong>job</strong> level, where every step inherits it.</p><p><strong>2. A stale HCP Terraform token.</strong> The secret existed, but its value wasn’t good. Regenerated in HCP Terraform, updated the GitHub secret.</p><p><strong>3. </strong><strong>terraform plan hung forever.</strong> Not an error — silence. The workspace runs in <strong>Local execution mode</strong> (chosen earlier because Remote mode couldn&#39;t resolve relative ../../modules paths), and Local mode doesn&#39;t auto-inject HCP Terraform&#39;s stored workspace variables the way Remote mode would. Locally, a gitignored terraform.tfvars supplied project_id; that file obviously doesn&#39;t exist on a fresh CI checkout, so terraform plan sat waiting on an interactive prompt a CI shell can never answer.</p><pre>env:<br>  TF_VAR_project_id: ${{ vars.PROJECT_ID }}<br>  TF_VAR_vulnbank_image_tag: ${{ vars.VULNBANK_IMAGE_TAG }}</pre><p>Also added -input=false everywhere as a permanent safety net — any future missing variable now fails fast and loud instead of hanging silently.</p><p><strong>4. A stale state lock.</strong> Left behind by an earlier cancelled run. The CLI’s own terraform force-unlock &lt;id&gt; kept failing with mismatched lock IDs — a known limitation with the cloud backend, where locking is tracked by HCP Terraform&#39;s own run queue, not a simple file the CLI can force-clear. The real fix was in HCP Terraform&#39;s own UI: the workspace <strong>Overview</strong> page showed &quot;Locked by &lt;user&gt;&quot; with a direct <strong>Unlock</strong> button.</p><p><strong>5. No GCP authentication on the runner, at all.</strong> TF_TOKEN_APP_TERRAFORM_IO only authenticates to HCP Terraform for state storage — a completely separate concern from authenticating the actual google/google-beta Terraform providers to GCP itself:</p><pre>Error: Attempted to load application default credentials...<br>google: could not find default credentials</pre><p>The org this project runs in blocks service account key file creation entirely (constraints/iam.managed.disableServiceAccountKeyCreation) — a good default policy, but it meant a downloaded JSON key was never an option. The real fix: <strong>Workload Identity Federation</strong>, no key file, ever.</p><pre>gcloud iam workload-identity-pools providers create-oidc &quot;github-actions-provider&quot; \<br>  --workload-identity-pool=&quot;github-actions-pool&quot; \<br>  --attribute-mapping=&quot;google.subject=assertion.sub,attribute.repository=assertion.repository&quot; \<br>  --attribute-condition=&quot;assertion.repository==&#39;&lt;owner&gt;/&lt;repo&gt;&#39;&quot; \<br>  --issuer-uri=&quot;https://token.actions.githubusercontent.com&quot;</pre><pre>- uses: google-github-actions/auth@v2<br>  with:<br>    workload_identity_provider: &quot;projects/&lt;num&gt;/locations/global/workloadIdentityPools/github-actions-pool/providers/github-actions-provider&quot;<br>    service_account: &quot;github-actions-ci@&lt;project&gt;.iam.gserviceaccount.com&quot;</pre><p><strong>6. Missing IAM roles, found incrementally.</strong> First, Cloud Resource Manager API has not been used in project ... or it is disabled — needed for google_project_service resources to even check status. Then, once that was enabled, a 403 on managing <em>other</em> service accounts&#39; IAM bindings — resource-specific admin roles like compute.admin don&#39;t include that permission on their own:</p><pre>gcloud projects add-iam-policy-binding &lt;project&gt; \<br>  --member=&quot;serviceAccount:github-actions-ci@&lt;project&gt;.iam.gserviceaccount.com&quot; \<br>  --role=&quot;roles/resourcemanager.projectIamAdmin&quot;</pre><p>After all six fixes, gh pr checks 1 finally showed the words I&#39;d been chasing for a while:</p><pre>All checks were successful<br>0 cancelled, 0 failing, 1 successful, 0 skipped, and 0 pending checks</pre><h4>🤖 Step 8: A Regression Suite That Proved Its Own Value on Day One</h4><p>With CI/CD working, the natural next step was making the manual demo scripts into an automated safety net — running daily, asserting real HTTP responses against the live endpoints:</p><pre>CODE=$(curl -sk -X POST &quot;https://${VULNBANK}/login&quot; \<br>  -d &quot;username=admin&#39; UNION SELECT 1,2,3--&amp;password=x&quot; \<br>  -o /dev/null -w &quot;%{http_code}&quot;)<br>check &quot;UNION-based SQLi on /login still blocked&quot; &quot;403&quot; &quot;$CODE&quot;</pre><p>Wired into a daily scheduled GitHub Actions workflow. First run: <strong>7 passed, 1 failed.</strong></p><p>The failure was the redirect check — HTTP/1.1 200 OK where a 302 was expected. Not a script bug. A <strong>real, previously unnoticed regression</strong>: earlier in the session, retargeting the JA4 rate-limit rule from /transfer to root / (to fix <em>its own</em> collision with the IP-ban rule) had silently created a brand-new collision with an unrelated external-302 redirect rule that also matched root /. JA4 sat at a lower priority number, so it won every time, and the redirect rule simply never got the chance to fire.</p><pre>&quot;enforcedSecurityPolicy&quot;: {<br>  &quot;configuredAction&quot;: &quot;THROTTLE&quot;,<br>  &quot;priority&quot;: 4025<br>}</pre><p>Confirmed via log — priority 4025 (JA4), not 5001 (the redirect). The fix, consistent with the durable pattern established by then: give the redirect rule its own dedicated path too.</p><p>Re-running afterward: <strong>8 passed, 0 failed.</strong></p><p>That’s the whole point of the tool proven in one shot: it caught something a human — me — had genuinely missed, on its very first real execution.</p><h4>📡 Step 9: Monitoring, and Three More Real Errors</h4><p>Building Cloud Monitoring alert policies produced three more genuinely instructive failures, none of them predictable in advance.</p><p><strong>A deny-rate-spike alert repeatedly rejected on creation.</strong> First guess, resource.type=&quot;global&quot;:</p><pre>Error 400: The supplied filter does not specify a valid combination<br>of metric and monitored resource descriptors.</pre><p>Second guess, resource.type=&quot;http_load_balancer&quot; (matching the <em>logging</em> resource type the source logs actually carry):</p><pre>Error 400: The resource name does not represent a known descriptor.</pre><p>Both wrong, for genuinely different reasons. Rather than guess a third time, I queried the Monitoring API directly for a real time series already backed by real deny events:</p><pre>Invoke-RestMethod -Uri $url -Headers @{Authorization = &quot;Bearer $token&quot;}</pre><pre>&quot;resource&quot;: {<br>  &quot;type&quot;: &quot;l7_lb_rule&quot;,<br>  &quot;labels&quot;: { &quot;backend_name&quot;: &quot;nginx-backend&quot;, ... }<br>}</pre><p>l7_lb_rule — Cloud <strong>Monitoring</strong>&#39;s naming for the same underlying data Cloud <strong>Logging</strong> calls http_load_balancer. Two different systems, two different resource-type vocabularies for the identical data. Also worth noting: with two backend services, this metric produces two separate time series, so the alert needed cross_series_reducer = &quot;REDUCE_SUM&quot; to actually watch total traffic rather than one backend&#39;s slice.</p><p><strong>BigQuery rejected a plain integer.</strong> Setting default_table_expiration_ms to 30 days&#39; worth of milliseconds (2,592,000,000) failed with:</p><pre>Error: Attribute must be a whole number, got 2.592e+09</pre><p>floor() didn&#39;t fix it. A string round-trip (format → parseint) didn&#39;t fix it. Even a hardcoded literal, no computation at all, failed identically — which ruled out arithmetic entirely as the cause. The real explanation: 2,592,000,000 sits just above 2,147,483,647, the maximum value for a signed 32-bit integer. This provider version appears to enforce an int32 ceiling on this specific field, even though BigQuery&#39;s real API supports int64. The fix: a retention value safely under the ~24.8-day ceiling.</p><h4>📈 Step 10: BigQuery Export and Multi-Environment Structure</h4><p>All Cloud Armor and load-balancer logs now export to BigQuery for analysis beyond ad-hoc gcloud logging read queries — top blocked IPs, SQLi attempts over time, denies grouped by rule priority, all as example starter queries for a Looker Studio dashboard.</p><p>A staging environment template also exists — same Terraform modules, only the confirmed-safe shipped configuration, monitoring and log export wired in from the start — deliberately <strong>not applied</strong>. Standing up a second full copy of this infrastructure would roughly double real cost for a single-operator lab with no actual second set of users; the structure and documented promotion workflow are the real deliverable.</p><h4>🧯 Step 11: What to Actually Do When an Alert Fires</h4><p>The incident response runbook opens with the single most important lesson of this whole project:</p><p><strong>Don’t assume it’s an attack.</strong> A deny-rate spike can mean a genuine attack, or it can mean a misconfigured rule blocking legitimate users — this project confirmed both, directly. The registration false positive would have looked identical to an attack in monitoring, while actually being a self-inflicted outage.</p><p>From there, the runbook walks through checking which rule fired and against what traffic, deciding between “genuine attack” (tighten a rate limit, add a targeted deny, raise sensitivity carefully) and “false positive” (revert, confirm with the regression suite, root-cause properly rather than just reverting and forgetting) — every step grounded in a finding this project actually confirmed, not generic advice.</p><h3>⚠️ Prerequisites &amp; Reproduction</h3><ul><li>A GCP project with billing enabled</li><li>Terraform &gt;= 1.3</li><li>An HCP Terraform workspace, set to <strong>Local</strong> execution mode (Remote mode can’t resolve this repo’s relative module paths — confirmed the hard way)</li><li>gcloud CLI authenticated</li><li>A domain you control, if you want trusted HTTPS</li></ul><p>📋 <strong>Step 1 — Clone and set up</strong></p><pre>git clone --recurse-submodules https://github.com/bikram-singh/gcp-cloud-armor-waf-ddos-lab.git<br>cd gcp-cloud-armor-waf-ddos-lab</pre><p>📋 <strong>Step 2 — Fill in your real values</strong></p><pre>cd terraform/environments/lab<br># Copy and fill in terraform.tfvars (gitignored) with your<br># project_id, vulnbank_image_tag, and notification_email.</pre><p>📋 <strong>Step 3 — Apply</strong></p><pre>terraform init<br>terraform plan<br>terraform apply</pre><p>📋 <strong>Step 4 — Or let CI do it</strong></p><p>Every change also runs through a gated GitHub Actions pipeline — terraform-plan.yml posts the plan as a PR comment, terraform-apply.yml requires a typed confirmation before touching anything real, authenticated end to end via Workload Identity Federation, no key file involved.</p><p>📋 <strong>Step 5 — Run the actual attacks</strong></p><pre>bash scripts/security-regression-tests.sh</pre><p>Or, individually, anything in scripts/demos/ — each one targets a single confirmed capability.</p><h3>🐛 What a Real Bug Getting Caught Looks Like</h3><pre>#1  Daily security-regression.yml runs, as scheduled<br>    → 6 checks pass immediately: baseline traffic, path rules,<br>      SQLi, XSS, rate limiting<br>    → Check 6 (external redirect) fails:<br>      FAIL: external 302 redirect did not fire (got: &#39;&#39;)<br><br>#2  Investigation<br>    → curl -D - straight against the endpoint: HTTP/1.1 200 OK,<br>      no redirect at all, no error either — just silently absent<br>    → gcloud logging read against the real request:<br>      &quot;enforcedSecurityPolicy&quot;: { &quot;priority&quot;: 4025, &quot;configuredAction&quot;: &quot;THROTTLE&quot; }<br>    → Priority 4025 is the JA4 rate-limit rule. The redirect rule<br>      lives at priority 5001. Lower number wins, every time.<br><br>#3  Root cause<br>    → Earlier in the same project, JA4 had been retargeted from<br>      /transfer to root &quot;/&quot; to fix a DIFFERENT collision with the<br>      IP-based ban rule. Nobody noticed root &quot;/&quot; was also exactly<br>      what the external-302 redirect rule matched.<br>    → terraform apply — gave the redirect its own dedicated path,<br>      /redirect-test, isolated from every other rate-limit rule<br>    → Re-ran the suite: 8 passed, 0 failed.</pre><p>I didn’t find this one. The regression suite did, on its very first real scheduled execution — which is the entire argument for building it in the first place.</p><h3>📊 The Real Numbers</h3><p>Not a self-reported claim — numbers pulled directly from real test output and real log queries during this project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*uZJXFQspk8ylpLj9IAih8Q.png" /></figure><p>None of these are printed once and left stale — the regression suite re-runs daily against live endpoints, so the pass count is only ever as current as this morning’s run.</p><h3>✅ Conclusion</h3><p>✅ Real SQL injection and stored XSS, actually attempted, actually blocked, actually logged ✅ Geo-blocking proven from a real US-origin VM, not simulated ✅ Edge-vs-backend precedence confirmed independently — the backend policy wasn’t even evaluated ✅ Zero service account keys, anywhere — Workload Identity Federation end to end ✅ A daily regression suite that caught a real bug on its first run ✅ Four confirmed corrections to my own starting assumptions, documented as found ✅ Every real bug above found only because real infrastructure, and real attacks, were involved</p><p>The actual lesson: a WAF configuration that looks complete on paper is a different claim from a WAF configuration that’s been proven against a real attack, a real false positive, and a real automation pipeline running on its own. The gap between the two only closes when you actually run the thing — repeatedly, against something real, and watch what breaks.</p><h3>📸 Snapshots</h3><p><strong>HTTPS &amp; Domain</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4FqjwIaMSpqHepB7DoiX2Q.png" /></figure><p><strong>Attack Testing</strong></p><p><strong>SQL Injection (via Login form)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qjHIZ3_nc5Z5iEVOGHi3OA.png" /></figure><p><strong>Badpath</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*CF6-kekCk_oJ7ACeqjtgbA.png" /></figure><p><strong>Brute force / rate limiting (via Login form, repeated attempts)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*uE98p4w17STMw05Vau5Swg.png" /></figure><h3>🔗 Repository</h3><p>The full source code is at:</p><p><a href="https://github.com/bikram-singh/gcp-cloud-armor-waf-ddos-lab"><strong>gcp-cloud-armor-waf-ddos-lab</strong></a><strong> </strong>— Cloud Armor WAF &amp; DDoS Protection Lab · Terraform · Live Attack Testing · Real Findings</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bc525af4186" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>