<?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 ThankGod Chibugwum Obobo on Medium]]></title>
        <description><![CDATA[Stories by ThankGod Chibugwum Obobo on Medium]]></description>
        <link>https://medium.com/@actocodes?source=rss-8ce15fc09a3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rjgtfvPVyBjPY6ydtY0BmQ.jpeg</url>
            <title>Stories by ThankGod Chibugwum Obobo on Medium</title>
            <link>https://medium.com/@actocodes?source=rss-8ce15fc09a3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:15:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@actocodes/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[Platform Engineering with Spacelift: Building a Self-Service Infrastructure Platform]]></title>
            <link>https://actocodes.medium.com/platform-engineering-with-spacelift-building-a-self-service-infrastructure-platform-42cfa4f43ecf?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/42cfa4f43ecf</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[spacelift]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 17:01:03 GMT</pubDate>
            <atom:updated>2026-07-26T17:01:03.163Z</atom:updated>
            <content:encoded><![CDATA[<p>Platform engineering has emerged as the discipline that sits between DevOps tooling and the application teams that consume it. Its goal is deceptively simple, make it easy for developers to do the right thing, provision infrastructure, deploy services, manage environments, without requiring deep infrastructure expertise or opening a ticket to a platform team.</p><p>The gap between that goal and reality is often filled by a patchwork of CI/CD pipelines, manual approvals, Slack messages, and Terraform scripts that only two people understand. Developer experience suffers. Compliance and security controls exist only in documentation that nobody reads. Infrastructure sprawls across environments with no consistent enforcement.</p><p><strong>Spacelift</strong> is a platform engineering tool designed specifically to close this gap, providing a collaborative, policy-driven, GitOps-native control plane for Terraform, OpenTofu, Pulumi, Ansible, and Kubernetes. It sits above your IaC tooling and gives platform teams the controls they need to enforce standards, while giving application teams the self-service access they need to move fast without breaking things.</p><p>This guide covers how to build a self-service infrastructure platform with Spacelift, from stack architecture and policy enforcement to drift detection, module registries, and the developer experience patterns that make platform engineering actually deliver on its promise.</p><h3>What Makes Spacelift Different</h3><p>Before diving into implementation, it helps to understand what Spacelift provides that raw CI/CD pipelines don’t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*RBbJpaH2ky-_jeJHQ177bg.png" /></figure><p>The fundamental difference is intent, CI/CD pipelines are general-purpose automation. Spacelift is purpose-built infrastructure orchestration, with the safety, compliance, and developer experience features that platform engineering requires.</p><h3>Core Concepts</h3><p>Before building, understand Spacelift’s key abstractions:</p><p><strong>Stack</strong>, the fundamental unit in Spacelift. A stack wraps a single IaC configuration (a Terraform root module, a Pulumi program, an Ansible playbook) with its state backend, environment variables, policies, and deployment settings. One stack equals one deployable infrastructure unit.</p><p><strong>Space</strong>, a hierarchical namespace for grouping and access-controlling stacks. Spaces mirror your organizational structure: root → platform → team-a, root → platform → team-b. Policies and access rules defined at a parent space are inherited by child spaces.</p><p><strong>Policy</strong>, an OPA (Open Policy Agent) Rego rule that governs stack behavior. Spacelift ships four policy types: plan (approve or reject based on plan output), access (control who can do what), trigger (control when stacks run), and git push (control which commits trigger runs).</p><p><strong>Module</strong>, a versioned, reusable Terraform module published to Spacelift’s built-in registry. Modules are the mechanism through which platform teams publish approved, tested infrastructure patterns that application teams consume via self-service.</p><p><strong>Run</strong>, a single execution of a stack’s IaC code. Every run is tracked with full input context, plan output, policy decisions, approval state, and apply output, providing an immutable audit trail.</p><h3>Step 1 — Repository and Stack Architecture</h3><p>Design your repository structure before creating stacks. A common pattern for multi-team platform engineering:</p><pre>/infrastructure<br>  /platform           ← platform team owns this<br>    /networking<br>      main.tf         ← VPCs, subnets, TGW<br>    /security<br>      main.tf         ← IAM roles, security groups, KMS keys<br>    /eks<br>      main.tf         ← shared EKS clusters<br>  /modules            ← approved module library<br>    /vpc<br>    /rds<br>    /s3-secure<br>    /eks-nodegroup<br>  /teams              ← application teams own this (self-service)<br>    /team-alpha<br>      /staging<br>        main.tf<br>      /production<br>        main.tf<br>    /team-beta<br>      /staging<br>        main.tf<br>      /production<br>        main.tf<br>  /policies           ← Spacelift policies as code<br>    plan-enforce-tagging.rego<br>    plan-cost-guard.rego<br>    access-team-boundaries.rego<br>    trigger-dependency-chain.rego</pre><p>This structure enforces a clear ownership boundary, the platform team manages foundational infrastructure and approved modules. Application teams self-service within /teams/{team-name}, constrained by policies that prevent them from touching what they shouldn&#39;t.</p><h3>Step 2 — Creating and Configuring Stacks</h3><p>Create stacks programmatically using the Spacelift Terraform provider, treating your platform configuration as code:</p><pre># spacelift/stacks/platform-networking.tf<br>resource &quot;spacelift_stack&quot; &quot;platform_networking&quot; {<br>  name        = &quot;platform-networking&quot;<br>  description = &quot;Core VPC and network infrastructure&quot;<br>  space_id    = spacelift_space.platform.id<br><br>  repository   = &quot;your-org/infrastructure&quot;<br>  branch       = &quot;main&quot;<br>  project_root = &quot;platform/networking&quot;<br><br>  terraform_version = &quot;1.6.0&quot;<br><br>  autodeploy         = false    # require explicit approval for platform changes<br>  protect_from_deletion = true<br><br>  labels = [&quot;platform&quot;, &quot;networking&quot;, &quot;critical&quot;]<br>}<br><br>resource &quot;spacelift_stack&quot; &quot;team_alpha_staging&quot; {<br>  name        = &quot;team-alpha-staging&quot;<br>  description = &quot;Team Alpha staging environment&quot;<br>  space_id    = spacelift_space.team_alpha.id<br><br>  repository   = &quot;your-org/infrastructure&quot;<br>  branch       = &quot;main&quot;<br>  project_root = &quot;teams/team-alpha/staging&quot;<br><br>  terraform_version = &quot;1.6.0&quot;<br><br>  autodeploy = true    # staging auto-deploys on merge<br>  labels     = [&quot;team-alpha&quot;, &quot;staging&quot;]<br>}</pre><p>Configure environment variables and secret injection per stack:</p><pre># Environment variables, non-sensitive configuration<br>resource &quot;spacelift_environment_variable&quot; &quot;team_alpha_region&quot; {<br>  stack_id  = spacelift_stack.team_alpha_staging.id<br>  name      = &quot;AWS_DEFAULT_REGION&quot;<br>  value     = &quot;us-east-1&quot;<br>  write_only = false<br>}<br><br># Secret injection from AWS Secrets Manager via Spacelift context<br>resource &quot;spacelift_context&quot; &quot;aws_credentials&quot; {<br>  name        = &quot;aws-production-credentials&quot;<br>  description = &quot;AWS credentials for production deployments&quot;<br>  space_id    = spacelift_space.platform.id<br>}<br><br>resource &quot;spacelift_context_attachment&quot; &quot;team_alpha_prod&quot; {<br>  context_id = spacelift_context.aws_credentials.id<br>  stack_id   = spacelift_stack.team_alpha_staging.id<br>  priority   = 1<br>}</pre><p><strong>Contexts</strong> are the Spacelift equivalent of shared environment variable sets, define credentials once at the platform level, attach to any number of stacks, and rotate in one place.</p><h3>Step 3 — Policies as Code with OPA</h3><p>Policies are where platform engineering leverage lives. A policy written once enforces a standard across every stack in your platform, no per-team configuration, no tribal knowledge, no exceptions that slip through code review.</p><h3>Plan Policy — Enforce Resource Tagging</h3><p>Reject any Terraform plan that creates resources without mandatory tags:</p><pre># policies/plan-enforce-tagging.rego<br>package spacelift<br><br># Required tags for all resources in production<br>required_tags := {&quot;Environment&quot;, &quot;Team&quot;, &quot;CostCenter&quot;, &quot;ManagedBy&quot;}<br><br># Deny if any resource is missing required tags<br>deny[sprintf(&quot;Resource &#39;%s&#39; is missing required tags: %v&quot;, [resource.address, missing])] {<br>  resource := input.terraform.resource_changes[_]<br>  resource.change.actions[_] == &quot;create&quot;<br><br>  # Identify which required tags are missing<br>  provided_tags := {tag | resource.change.after.tags[tag]}<br>  missing := required_tags - provided_tags<br>  count(missing) &gt; 0<br>}<br><br># Warn if tags exist but Environment doesn&#39;t match a known value<br>warn[sprintf(&quot;Resource &#39;%s&#39; has unrecognized Environment tag: &#39;%s&#39;&quot;, [resource.address, env])] {<br>  resource := input.terraform.resource_changes[_]<br>  env := resource.change.after.tags.Environment<br>  not env in {&quot;staging&quot;, &quot;production&quot;, &quot;development&quot;}<br>}</pre><h3>Plan Policy — Cost Guard</h3><p>Reject plans that would exceed a per-run cost threshold:</p><pre># policies/plan-cost-guard.rego<br>package spacelift<br><br># Block plans with monthly cost increase above $500<br>deny[&quot;Monthly cost increase exceeds $500 threshold — escalate to platform team for approval&quot;] {<br>  input.spacelift.run.cost_estimate.monthly_cost_increase &gt; 500<br>}<br><br>warn[&quot;Monthly cost increase above $100 — ensure this is expected&quot;] {<br>  input.spacelift.run.cost_estimate.monthly_cost_increase &gt; 100<br>  input.spacelift.run.cost_estimate.monthly_cost_increase &lt;= 500<br>}</pre><h3>Access Policy — Team Boundary Enforcement</h3><p>Prevent teams from reading or modifying stacks they don’t own:</p><pre># policies/access-team-boundaries.rego<br>package spacelift<br><br># Extract team from the user&#39;s IdP groups<br>user_teams := {team |<br>  group := input.session.teams[_]<br>  team := trim_prefix(group, &quot;team-&quot;)<br>}<br><br># Allow access only to stacks labeled with the user&#39;s team<br>allow {<br>  stack_team := input.stack.labels[_]<br>  stack_team in user_teams<br>}<br><br># Platform team members have access to all stacks<br>allow {<br>  &quot;platform&quot; in input.session.teams<br>}<br><br># Block all other access<br>deny {<br>  not allow<br>}</pre><h3>Trigger Policy — Stack Dependency Chains</h3><p>Automatically trigger downstream stacks when upstream infrastructure changes:</p><pre># policies/trigger-dependency-chain.rego<br>package spacelift<br><br># When platform-networking applies successfully, trigger EKS stack<br>trigger[&quot;platform-eks&quot;] {<br>  input.run.stack.id == &quot;platform-networking&quot;<br>  input.run.state == &quot;FINISHED&quot;<br>  input.run.type == &quot;TRACKED&quot;<br>}<br><br># When platform-eks applies successfully, trigger team stacks<br>trigger[&quot;team-alpha-staging&quot;] {<br>  input.run.stack.id == &quot;platform-eks&quot;<br>  input.run.state == &quot;FINISHED&quot;<br>}</pre><p>Attach policies to stacks or spaces:</p><pre>resource &quot;spacelift_policy&quot; &quot;enforce_tagging&quot; {<br>  name = &quot;enforce-resource-tagging&quot;<br>  type = &quot;PLAN&quot;<br>  body = file(&quot;policies/plan-enforce-tagging.rego&quot;)<br>}<br><br># Attach to the entire platform space — all child stacks inherit<br>resource &quot;spacelift_policy_attachment&quot; &quot;enforce_tagging_platform&quot; {<br>  policy_id = spacelift_policy.enforce_tagging.id<br>  stack_id  = &quot;*&quot;<br>  space_id  = spacelift_space.platform.id<br>}</pre><h3>Step 4 — Module Registry for Self-Service</h3><p>The Spacelift module registry is the mechanism through which platform teams publish approved infrastructure patterns for self-service consumption. A module published to the registry is versioned, tested, and policy-compliant by definition, application teams consume it without needing to understand the underlying infrastructure design.</p><p>Publish a module to Spacelift’s registry:</p><pre># spacelift/modules/rds-module.tf<br>resource &quot;spacelift_module&quot; &quot;rds_postgres&quot; {<br>  name           = &quot;rds-postgres&quot;<br>  space_id       = spacelift_space.platform.id<br>  repository     = &quot;your-org/infrastructure&quot;<br>  project_root   = &quot;modules/rds&quot;<br>  branch         = &quot;main&quot;<br>  description    = &quot;Production-grade PostgreSQL RDS with encryption, backups, and parameter group&quot;<br><br>  terraform_provider = &quot;aws&quot;<br><br>  labels = [&quot;database&quot;, &quot;postgres&quot;, &quot;approved&quot;]<br>}</pre><p>Application teams consume it in their stacks like any Terraform module:</p><pre># teams/team-alpha/staging/main.tf<br>module &quot;orders_database&quot; {<br>  source  = &quot;spacelift.io/your-org/rds-postgres/aws&quot;<br>  version = &quot;~&gt; 2.0&quot;<br><br>  identifier        = &quot;orders-staging&quot;<br>  instance_class    = &quot;db.t3.medium&quot;<br>  allocated_storage = 20<br>  environment       = &quot;staging&quot;<br>  team              = &quot;team-alpha&quot;<br>}</pre><p>The version constraint (~&gt; 2.0) means Team Alpha gets patch updates automatically but won&#39;t be silently upgraded to a breaking major version. The platform team controls what&#39;s published, application teams control what version they pin to.</p><h3>Step 5 — Drift Detection</h3><p>Infrastructure drift, the gap between what Terraform’s state says exists and what actually exists in your cloud account, is one of the most persistent operational problems in IaC. Manual changes through the AWS console, emergency hotfixes applied directly, or race conditions between concurrent applies all cause drift.</p><p>Spacelift’s built-in drift detection runs Terraform plan on a schedule and alerts when the live state diverges from the declared state:</p><pre>resource &quot;spacelift_stack&quot; &quot;platform_networking&quot; {<br>  # ... other config ...<br><br>  # Run drift detection daily at 2am UTC<br>  drift_detection {<br>    enabled   = true<br>    reconcile = false    # alert on drift but don&#39;t auto-remediate — require human review<br>    schedule  = [&quot;0 2 * * *&quot;]<br>  }<br>}</pre><p>For non-critical stacks where auto-remediation is safe:</p><pre>drift_detection {<br>  enabled   = true<br>  reconcile = true     # automatically apply to reconcile drift<br>  schedule  = [&quot;0 */6 * * *&quot;]  # every 6 hours<br>}</pre><p>Configure Slack or PagerDuty notifications for drift alerts:</p><pre>resource &quot;spacelift_webhook&quot; &quot;drift_alert&quot; {<br>  stack_id = spacelift_stack.platform_networking.id<br>  endpoint = var.slack_webhook_url<br>  enabled  = true<br><br>  # Trigger on drift detection and failed reconciliation<br>  secret = var.webhook_secret<br>}</pre><h3>Step 6 — Self-Service Developer Experience</h3><p>The final layer is the developer experience that makes self-service actually self-service. Spacelift’s <strong>self-service catalog</strong> (Spaces + module registry + approval workflows) lets application teams provision infrastructure through a UI or API without opening tickets:</p><p><strong>For application teams:</strong> a curated list of available modules (RDS, S3, SQS, ElastiCache) with a form-based provisioning interface, no Terraform knowledge required.</p><p><strong>For platform teams:</strong> full visibility into what every team has provisioned, policy enforcement that fires automatically, drift detection that runs continuously, and an audit trail that captures every change with the identity of who made it and what the plan output was.</p><p>Connect Spacelift to your IdP (Okta, GitHub, Google) to enforce team boundaries automatically via SSO group membership, the access policies defined in Step 3 apply automatically as team membership changes.</p><h3>Step 7 — CI/CD Integration</h3><p>Spacelift integrates with GitHub, GitLab, Bitbucket, and Azure DevOps for Git-driven runs. A push to main in the infrastructure repo triggers plan runs on affected stacks automatically:</p><pre># .github/workflows/spacelift-preview.yml<br>name: Spacelift Plan Preview<br><br>on: [pull_request]<br><br>jobs:<br>  plan-preview:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Comment plan output on PR<br>        uses: spacelift-io/spacelift-pull-request-action@v1<br>        with:<br>          spacelift-api-key-id: ${{ secrets.SPACELIFT_API_KEY_ID }}<br>          spacelift-api-key-secret: ${{ secrets.SPACELIFT_API_KEY_SECRET }}</pre><p>For stacks with autodeploy: false, Spacelift posts the plan output as a PR comment, requiring a human to review and approve before the apply runs. For stacks with autodeploy: true (staging environments), the apply runs automatically on merge to main.</p><h3>Common Pitfalls to Avoid</h3><p><strong>Flat space hierarchy.</strong> A single space for all stacks gives no access boundary between teams. Design your space hierarchy to mirror your team structure from day one, retrofitting access controls onto a flat hierarchy is painful.</p><p><strong>Policies without testing.</strong> A deny policy that fires incorrectly can block all deployments across your entire platform. Test policies against representative plan inputs using OPA&#39;s opa eval before attaching them to production stacks.</p><p><strong>Auto-reconciling critical infrastructure.</strong> Drift auto-remediation is powerful but dangerous for foundational infrastructure. Networking, security groups, and IAM roles should alert on drift and require human review, not automatically apply. Reserve auto-reconciliation for stateless, idempotent resource sets.</p><p><strong>No module versioning discipline.</strong> Publishing a breaking change to a module and expecting all consumers to upgrade simultaneously doesn’t scale. Adopt semantic versioning for modules and maintain at least one prior major version while teams migrate.</p><h3>Conclusion</h3><p>Platform engineering is not about giving developers access to infrastructure tooling, it’s about designing guardrails and self-service patterns so that developers can provision what they need safely, consistently, and without creating operational debt for the platform team.</p><p><strong>Spacelift</strong> makes this achievable by providing a purpose-built control plane for IaC, policy enforcement that fires at plan time, a module registry that codifies approved patterns, drift detection that catches manual changes, and a space hierarchy that enforces team boundaries without manual intervention.</p><p>The platform team’s job evolves from running infrastructure to building the platform that lets others run theirs safely, at scale, and with a complete audit trail.</p><p><em>Running OpenTofu instead of Terraform, or mixing Pulumi with Ansible? Spacelift’s multi-IaC support handles heterogeneous toolchains in the same platform all under the same policy and audit model. Drop your stack in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42cfa4f43ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing mTLS in Kubernetes: How to Secure Service-to-Service Communication]]></title>
            <link>https://actocodes.medium.com/implementing-mtls-in-kubernetes-how-to-secure-service-to-service-communication-ce96ed6541f2?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce96ed6541f2</guid>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[tlm]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[linkerd]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-07-19T17:01:02.797Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In a microservices architecture running on Kubernetes, services communicate constantly, the orders-service calls the users-service, the payments-service calls the fraud-detection-service, and the API gateway routes to a dozen downstream services. By default, most of this traffic travels unencrypted inside the cluster, authenticated only by the fact that the caller has network access.</p><p>That assumption that anything inside the cluster boundary is trustworthy, is the network-level equivalent of leaving every internal door unlocked because the building has a lock on the front entrance. A single compromised pod, a misconfigured network policy, or a lateral movement attack can reach any service in the cluster with no additional authentication required.</p><p><strong>Mutual TLS (mTLS)</strong> closes this gap. Unlike standard TLS where only the server presents a certificate, mTLS requires both parties, client and server, to present and verify certificates before any data is exchanged. Every service-to-service connection is cryptographically authenticated. A compromised pod cannot impersonate payments-service to fraud-detection-service because it cannot produce a valid certificate for that identity.</p><p>This guide covers how to implement mTLS in Kubernetes using a service mesh, comparing Istio and Linkerd, configuring automatic certificate issuance, enforcing strict mTLS policies, and validating that your network is actually secured.</p><h3>How mTLS Works in Kubernetes</h3><p>Standard TLS in a web context works like this: the client (browser) verifies the server’s certificate, establishing that the server is who it claims to be, but the server accepts any client. mTLS adds the reverse, the server also verifies the client’s certificate, establishing mutual identity before the connection proceeds.</p><p>In Kubernetes, the mechanics are:</p><ol><li>Each service is issued a certificate tied to its <strong>SPIFFE identity</strong>, a URI in the format spiffe://cluster.local/ns/{namespace}/sa/{service-account}.</li><li>When orders-service connects to users-service, both services present their certificates.</li><li>The receiving service verifies the caller’s certificate against the cluster’s trust anchor (a root CA).</li><li>If verification passes, the connection proceeds. If not, wrong identity, expired certificate, or untrusted issuer, the connection is rejected at the TLS layer, before any application code runs.</li></ol><p>The critical operational property: <strong>certificates are automatically rotated</strong> by the service mesh control plane, typically every 24 hours. No manual certificate management, no expiry incidents, no long-lived credentials.</p><h3>Choosing a Service Mesh: Istio vs. Linkerd</h3><p>Both Istio and Linkerd implement mTLS via sidecar proxies injected into each pod. The proxies intercept all inbound and outbound traffic, transparently handling TLS without requiring application code changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*zGTLlUA5g8f9R-lgUfG4RA.png" /></figure><p><strong>Choose Istio</strong> if you need advanced traffic management (canary deployments, fault injection, circuit breaking), rich observability, or WebAssembly-based policy extensibility.</p><p><strong>Choose Linkerd</strong> if you prioritize simplicity, low resource overhead, and want mTLS with strong defaults out of the box with minimal configuration.</p><p>This guide covers both installation and policy configuration for each.</p><h3>Approach 1 — mTLS with Istio</h3><h3>Step 1 — Install Istio</h3><p>Install Istio using the istioctl CLI with the minimal production profile:</p><pre># Install istioctl<br>curl -L https://istio.io/downloadIstio | sh -<br>export PATH=$PWD/istio-*/bin:$PATH<br><br># Install Istio with production profile<br>istioctl install --set profile=default \<br>  --set values.pilot.env.PILOT_ENABLE_WORKLOAD_ENTRY_AUTOREGISTRATION=true \<br>  -y<br><br># Verify installation<br>istioctl verify-install</pre><h3>Step 2 — Enable Automatic Sidecar Injection</h3><p>Label namespaces where you want mTLS enforced. Istio automatically injects the Envoy sidecar proxy into every pod in labeled namespaces:</p><pre># Enable sidecar injection for your application namespaces<br>kubectl label namespace orders-service istio-injection=enabled<br>kubectl label namespace users-service istio-injection=enabled<br>kubectl label namespace payments-service istio-injection=enabled<br><br># Verify injection is active<br>kubectl get namespace -L istio-injection</pre><p>Rolling restart existing deployments to pick up sidecar injection:</p><pre>kubectl rollout restart deployment -n orders-service<br>kubectl rollout restart deployment -n users-service<br>kubectl rollout restart deployment -n payments-service</pre><p>Verify sidecars are injected, each pod should now show 2/2 containers (application + Envoy proxy):</p><pre>kubectl get pods -n orders-service<br># NAME                             READY   STATUS    RESTARTS   AGE<br># orders-api-7d8b9f5c4-xk2pq      2/2     Running   0          45s</pre><h3>Step 3 — Configure PeerAuthentication for Strict mTLS</h3><p>By default, Istio operates in <strong>permissive mode</strong>, it accepts both plaintext and mTLS traffic. This is safe for migration but provides no security guarantee. Switch to <strong>strict mode</strong> to enforce mTLS and reject all plaintext traffic:</p><pre># istio/peer-authentication-strict.yaml<br>apiVersion: security.istio.io/v1beta1<br>kind: PeerAuthentication<br>metadata:<br>  name: default<br>  namespace: istio-system   # mesh-wide policy<br>spec:<br>  mtls:<br>    mode: STRICT</pre><pre>kubectl apply -f istio/peer-authentication-strict.yaml</pre><p>This single resource enforces mTLS for all service-to-service communication across the entire mesh. Any pod that attempts to connect to another pod without a valid certificate, including debug containers, legacy services without sidecars, or external probes, will have their connection rejected.</p><h3>Step 4 — AuthorizationPolicy for Fine-Grained Access Control</h3><p>mTLS establishes <em>who</em> a caller is. AuthorizationPolicy controls <em>what</em> authenticated identities are allowed to do, combining mTLS identity with RBAC-style rules:</p><pre># istio/authorization-payments.yaml<br>apiVersion: security.istio.io/v1beta1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: payments-service-policy<br>  namespace: payments-service<br>spec:<br>  selector:<br>    matchLabels:<br>      app: payments-service<br>  action: ALLOW<br>  rules:<br>    - from:<br>        - source:<br>            principals:<br>              # Only orders-service can call payments-service<br>              - &quot;cluster.local/ns/orders-service/sa/orders-service-sa&quot;<br>      to:<br>        - operation:<br>            methods: [&quot;POST&quot;]<br>            paths: [&quot;/payments/charge&quot;, &quot;/payments/refund&quot;]</pre><pre># Deny all traffic not explicitly allowed, defense in depth<br>apiVersion: security.istio.io/v1beta1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: deny-all<br>  namespace: payments-service<br>spec:<br>  {}  # Empty spec = deny all by default</pre><p>Apply deny-all first, then layer specific ALLOW policies on top. This is the zero-trust principle applied at the service level: every inter-service call must be explicitly authorized.</p><h3>Step 5 — Verify mTLS is Active with Kiali</h3><p>Kiali, Istio’s observability console, provides a visual confirmation of mTLS status:</p><pre># Install Kiali and supporting tools<br>kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.20/samples/addons/kiali.yaml<br>kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.20/samples/addons/prometheus.yaml<br><br># Access Kiali dashboard<br>istioctl dashboard kiali</pre><p>In Kiali’s service graph, a <strong>padlock icon</strong> on each edge confirms mTLS is active on that connection. Missing padlocks indicate a service communicating without mTLS, a misconfiguration or missing sidecar.</p><h3>Approach 2 — mTLS with Linkerd</h3><h3>Step 1 — Install Linkerd</h3><pre># Install Linkerd CLI<br>curl --proto &#39;=https&#39; --tlsv1.2 -sSfL https://run.linkerd.io/install | sh<br><br># Validate cluster compatibility<br>linkerd check --pre<br><br># Install Linkerd control plane<br>linkerd install --crds | kubectl apply -f -<br>linkerd install | kubectl apply -f -<br><br># Verify installation<br>linkerd check</pre><h3>Step 2 — Inject Linkerd Proxy into Namespaces</h3><pre># Annotate namespaces for automatic injection<br>kubectl annotate namespace orders-service linkerd.io/inject=enabled<br>kubectl annotate namespace users-service linkerd.io/inject=enabled<br>kubectl annotate namespace payments-service linkerd.io/inject=enabled<br><br># Restart deployments to pick up proxy injection<br>kubectl rollout restart deployment -n orders-service<br>kubectl rollout restart deployment -n users-service<br>kubectl rollout restart deployment -n payments-service</pre><h3>Step 3 — Enforce mTLS with Server Policies</h3><p>Linkerd enables mTLS by default in injected namespaces. To enforce <strong>authenticated traffic only</strong> (equivalent to Istio’s strict mode), configure Server policies:</p><pre># linkerd/server-policy-payments.yaml<br>apiVersion: policy.linkerd.io/v1beta2<br>kind: Server<br>metadata:<br>  name: payments-server<br>  namespace: payments-service<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: payments-service<br>  port: 8080<br>  proxyProtocol: HTTP/2<br><br><br>apiVersion: policy.linkerd.io/v1beta2<br>kind: ServerAuthorization<br>metadata:<br>  name: payments-authz<br>  namespace: payments-service<br>spec:<br>  server:<br>    name: payments-server<br>  client:<br>    meshTLS:<br>      serviceAccounts:<br>        - name: orders-service-sa<br>          namespace: orders-service</pre><pre>kubectl apply -f linkerd/server-policy-payments.yaml<br><br># Verify mTLS is active on connections<br>linkerd viz edges deployment -n orders-service<br># Shows which connections are secured with mTLS (✓) vs plaintext (✗)</pre><h3>Certificate Management with cert-manager</h3><p>Both Istio and Linkerd can integrate with <strong>cert-manager</strong> for certificate issuance, enabling integration with external CAs (HashiCorp Vault, AWS ACM PCA, Let’s Encrypt) rather than relying solely on the mesh’s built-in CA.</p><pre># cert-manager/cluster-issuer-vault.yaml<br>apiVersion: cert-manager.io/v1<br>kind: ClusterIssuer<br>metadata:<br>  name: vault-issuer<br>spec:<br>  vault:<br>    server: https://vault.internal:8200<br>    path: pki/sign/kubernetes-mesh<br>    auth:<br>      kubernetes:<br>        mountPath: /v1/auth/kubernetes<br>        role: cert-manager<br>        secretRef:<br>          name: cert-manager-vault-token<br>          key: token</pre><p>For Istio, plug the external CA into the control plane:</p><pre># Use cert-manager as Istio&#39;s certificate provider<br>istioctl install --set profile=default \<br>  --set values.pilot.env.EXTERNAL_CA=true \<br>  --set values.pilot.env.K8S_SIGNER=cert-manager.io/cluster-issuer/vault-issuer</pre><p>External CA integration provides:</p><ul><li><strong>Centralized audit trail</strong> of every certificate issuance across your mesh</li><li><strong>Cross-cluster trust</strong> using a shared root CA for multi-cluster mTLS</li><li><strong>Compliance alignment</strong> with PKI policies already in use in your organization</li></ul><h3>Migrating to Strict mTLS Without Downtime</h3><p>Flipping directly to strict mode on a production cluster breaks any service that doesn’t yet have a sidecar. Use a phased migration:</p><p><strong>Phase 1 — Permissive mode (baseline).</strong> Install the mesh with mTLS in permissive mode. All traffic is accepted, both plaintext and mTLS. Use Kiali or linkerd viz to identify which connections are NOT using mTLS.</p><p><strong>Phase 2 — Namespace-by-namespace injection.</strong> Enable sidecar injection one namespace at a time. Verify each namespace’s workloads after injection before proceeding.</p><p><strong>Phase 3 — Strict mode per namespace.</strong> Apply PeerAuthentication or Server policies with strict enforcement to already-injected namespaces:</p><pre># Namespace-scoped strict policy (safer than mesh-wide during migration)<br>apiVersion: security.istio.io/v1beta1<br>kind: PeerAuthentication<br>metadata:<br>  name: strict-mtls<br>  namespace: payments-service   # scoped to one namespace<br>spec:<br>  mtls:<br>    mode: STRICT</pre><p><strong>Phase 4 — Mesh-wide strict enforcement.</strong> Once all namespaces are injected and verified, apply the mesh-wide PeerAuthentication in istio-system and remove namespace-scoped policies.</p><p>This phased approach takes longer but eliminates the risk of a mesh-wide strict enforcement breaking services that weren’t ready.</p><h3>Validating mTLS Enforcement</h3><p>After enabling strict mode, validate it is actually enforced, don’t assume:</p><pre># Attempt to connect to payments-service from a pod WITHOUT a sidecar<br>kubectl run debug-pod --image=curlimages/curl --restart=Never -- \<br>  curl -s http://payments-service.payments-service.svc.cluster.local:8080/health<br><br># Expected result: connection refused or reset, mTLS is enforced<br># Unexpected result: 200 OK, mTLS is NOT enforced, investigate</pre><pre># Verify certificate details on an active connection<br>kubectl exec -n orders-service deployment/orders-api -c istio-proxy -- \<br>  openssl s_client \<br>    -connect payments-service.payments-service.svc.cluster.local:8080 \<br>    -showcerts 2&gt;/dev/null | grep -A2 &quot;subject=&quot;<br><br># Expected output shows SPIFFE URI:<br># subject=URI:spiffe://cluster.local/ns/payments-service/sa/payments-service-sa</pre><pre># Check Istio&#39;s view of mTLS status per service<br>istioctl x describe service payments-service.payments-service<br><br># Output confirms:<br># mTLS: yes<br># Policy: STRICT</pre><h3>Observability and Troubleshooting</h3><p>mTLS adds authentication at the network layer, but it also adds debugging complexity. Keep these tools in your operational toolkit:</p><p><strong>Istio proxy logs</strong> reveal TLS handshake failures with specific error codes:</p><pre># View Envoy access logs for a specific pod<br>kubectl logs -n orders-service deployment/orders-api -c istio-proxy | \<br>  grep -E &quot;UF|UC|UH&quot;  # Upstream connection failure codes</pre><p><strong>Linkerd tap</strong> provides real-time traffic inspection with mTLS status:</p><pre>linkerd viz tap deployment/orders-api -n orders-service \<br>  --to deployment/payments-service -n payments-service</pre><p><strong>Certificate expiry monitoring</strong> even with automatic rotation, monitor certificate validity as a health signal:</p><pre># Prometheus alert for certificates expiring within 24 hours<br>- alert: MeshCertificateExpiringSoon<br>  expr: |<br>    (citadel_server_csr_count - citadel_server_success_cert_issuance_count) &gt; 0<br>  for: 5m<br>  labels:<br>    severity: high<br>  annotations:<br>    summary: &quot;Certificate issuance failures in Istio CA&quot;</pre><h3>Common Pitfalls to Avoid</h3><p><strong>Enabling strict mode before all services have sidecars.</strong> Services without sidecars cannot participate in mTLS and will have their connections rejected in strict mode. Always verify 100% sidecar coverage before enabling mesh-wide strict enforcement.</p><p><strong>Forgetting health check probes.</strong> Kubernetes liveness and readiness probes originate from the kubelet, outside the mesh. Configure Istio to rewrite probe URLs or exclude probe ports from mTLS enforcement:</p><pre># Exclude health check port from mTLS, kubelet doesn&#39;t have a sidecar<br>spec:<br>  mtls:<br>    mode: STRICT<br>  portLevelMtls:<br>    8081:          # health check port<br>      mode: DISABLE</pre><p><strong>Not testing </strong><strong>AuthorizationPolicy before applying.</strong> A misconfigured deny-all policy can cut off legitimate service traffic in production. Test policies in a staging environment first, and use Istio&#39;s AUDIT action mode to log would-be denials before enforcing them.</p><p><strong>Ignoring certificate rotation failures.</strong> The automatic certificate rotation is the operational backbone of mesh mTLS. Monitor certificate issuance metrics, a rotation failure that goes undetected leads to widespread connection failures when certificates expire.</p><h3>Conclusion</h3><p>Mutual TLS in Kubernetes transforms your cluster’s internal network from an implicit trust zone into a zero-trust environment where every connection is cryptographically authenticated and explicitly authorized. A compromised pod cannot impersonate a legitimate service. A lateral movement attack cannot freely reach payment processing or user data services. Every inter-service call is auditable.</p><p>The operational cost, a service mesh, sidecar overhead, policy management, is real. But for systems where data sensitivity, regulatory requirements, or blast-radius concerns justify it, mTLS via a service mesh is the most complete implementation of zero-trust networking currently available for Kubernetes workloads.</p><p>Start with permissive mode, inject sidecars namespace by namespace, validate mTLS coverage with your mesh’s observability tools, and graduate to strict enforcement once you’re confident in coverage. The security guarantee at the end is worth the careful migration.</p><p><em>Running a multi-cluster Kubernetes setup? Extending mTLS across cluster boundaries with Istio’s multi-cluster federation or Linkerd’s cluster linking uses the same SPIFFE identity model, but adds a trust bundle exchange step between clusters.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce96ed6541f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DRY Infrastructure: How to Architect Modular Ansible Playbooks for Next.js]]></title>
            <link>https://actocodes.medium.com/dry-infrastructure-how-to-architect-modular-ansible-playbooks-for-next-js-b1b99d8ecda0?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1b99d8ecda0</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-07-12T17:01:02.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Infrastructure code suffers from the same antipatterns as application code, duplication, tight coupling, undocumented assumptions, and a growing resistance to change. A playbook written for one environment gets copy-pasted for the next, variables get hardcoded, and six months later you have five slightly different versions of the same deployment logic, each drifting independently and none of them trustworthy.</p><p>The <strong>DRY (Don’t Repeat Yourself) principle</strong> applies to infrastructure as directly as it does to software. In Ansible, DRY infrastructure means <strong>roles</strong> for reusable task logic, <strong>variable hierarchies</strong> for environment-specific overrides, <strong>handlers</strong> for event-driven operations, and a <strong>playbook composition</strong> pattern that assembles production-grade deployments from interchangeable, independently testable units.</p><p>For <strong>Next.js</strong>, with its hybrid rendering modes, standalone server output, static asset optimization, and Node.js runtime requirements, a modular Ansible approach gives you a repeatable, environment-aware provisioning and deployment pipeline that works consistently from local staging to production at scale.</p><p>This guide covers how to design and implement a modular Ansible architecture for Next.js from the ground up.</p><h3>Why Ansible for Next.js Infrastructure</h3><p>Before diving into structure, it’s worth addressing why Ansible fits Next.js provisioning well, especially alongside more modern IaC tools:</p><p><strong>Ansible excels at configuration management and application deployment</strong>, the layer between raw infrastructure (where Terraform lives) and application orchestration (where Kubernetes lives). For teams running Next.js on VMs, bare metal, or alongside a lightweight container setup, Ansible bridges that gap cleanly.</p><p>Specifically for Next.js:</p><ul><li><strong>Node.js runtime management</strong> (version pinning, nvm, process managers)</li><li><strong>Build artifact deployment</strong> (transferring .next/standalone output, managing static assets to CDN)</li><li><strong>Nginx reverse proxy configuration</strong> (SSL termination, caching headers, compression)</li><li><strong>Environment variable injection</strong> (.env files templated from Vault or group vars)</li><li><strong>PM2 or systemd process management</strong> (zero-downtime restarts, health checks)</li><li><strong>Log rotation and monitoring agent configuration</strong></li></ul><p>This is precisely where Ansible’s agentless, SSH-based, idempotent task execution shines.</p><h3>Step 1 — Project Structure for Modular Playbooks</h3><p>Start with a structure that enforces separation of concerns from day one:</p><pre>/ansible<br>  /inventories<br>    /staging<br>      hosts.yml<br>      group_vars/<br>        all.yml<br>        nextjs_servers.yml<br>    /production<br>      hosts.yml<br>      group_vars/<br>        all.yml<br>        nextjs_servers.yml<br>  /roles<br>    /common           ← base system configuration<br>    /nodejs           ← Node.js runtime installation and management<br>    /nextjs-app       ← Next.js application deployment<br>    /nginx            ← Nginx configuration and SSL<br>    /pm2              ← PM2 process management<br>    /monitoring       ← monitoring agent setup<br>    /logrotate        ← log rotation configuration<br>  /playbooks<br>    site.yml          ← master playbook (composes all roles)<br>    provision.yml     ← first-time server provisioning<br>    deploy.yml        ← application deployment only<br>    rollback.yml      ← rollback to previous release<br>  /group_vars<br>    all.yml           ← variables shared across all environments<br>  ansible.cfg</pre><p>This structure reflects three key design decisions:</p><p><strong>Separate provisioning from deployment.</strong> provision.yml runs once (or rarely) to set up a server. deploy.yml runs on every release. Conflating them means every deployment re-runs expensive provisioning tasks unnecessarily.</p><p><strong>Separate inventories per environment.</strong> Staging and production are entirely isolated inventory trees, different hosts, different group vars, no risk of accidentally running a production playbook against staging or vice versa.</p><p><strong>Roles are the unit of reuse.</strong> Every discrete concern is a role. Roles are independently versioned, testable with Molecule, and composable in any playbook.</p><h3>Step 2 — Ansible Configuration</h3><pre># ansible.cfg<br>[defaults]<br>inventory          = ./inventories<br>roles_path         = ./roles<br>host_key_checking  = False<br>retry_files_enabled = False<br>stdout_callback    = yaml<br>interpreter_python = auto_silent<br>forks              = 10<br><br>[ssh_connection]<br>ssh_args           = -o ControlMaster=auto -o ControlPersist=60s<br>pipelining         = True   # significant performance improvement</pre><p>pipelining = True reduces the number of SSH connections per task, one of the most impactful performance improvements for large fleets. It requires requiretty to be disabled in sudoers on your target hosts.</p><h3>Step 3 — Variable Hierarchy and Environment Overlays</h3><p>Ansible’s variable precedence is the mechanism for DRY environment-specific configuration. Define defaults at the broadest scope, override only what differs per environment:</p><pre># group_vars/all.yml - shared across ALL environments<br>nodejs_version: &quot;20.11.0&quot;<br>app_user: &quot;nextjs&quot;<br>app_group: &quot;nextjs&quot;<br>app_base_dir: &quot;/opt/nextjs&quot;<br>releases_to_keep: 5<br>pm2_instances: &quot;max&quot;<br>nginx_worker_processes: &quot;auto&quot;</pre><pre># inventories/staging/group_vars/nextjs_servers.yml - staging overrides<br>app_environment: &quot;staging&quot;<br>app_port: 3000<br>next_public_api_url: &quot;https://api.staging.your-domain.com&quot;<br>pm2_instances: 2                  # fewer instances on smaller staging servers<br>nginx_ssl_certificate: &quot;/etc/letsencrypt/live/staging.your-domain.com/fullchain.pem&quot;<br>nginx_ssl_key: &quot;/etc/letsencrypt/live/staging.your-domain.com/privkey.pem&quot;<br>app_releases_dir: &quot;{{ app_base_dir }}/releases&quot;</pre><pre># inventories/production/group_vars/nextjs_servers.yml - production overrides<br>app_environment: &quot;production&quot;<br>app_port: 3000<br>next_public_api_url: &quot;https://api.your-domain.com&quot;<br>pm2_instances: &quot;max&quot;              # use all available CPU cores<br>nginx_ssl_certificate: &quot;/etc/letsencrypt/live/your-domain.com/fullchain.pem&quot;<br>nginx_ssl_key: &quot;/etc/letsencrypt/live/your-domain.com/privkey.pem&quot;<br>app_releases_dir: &quot;{{ app_base_dir }}/releases&quot;</pre><p>Sensitive values (database URLs, API keys, secrets) should <strong>never</strong> appear in group vars. Use <strong>Ansible Vault</strong> for sensitive variable encryption or integrate with HashiCorp Vault for dynamic secret injection, as covered in our guide on replacing hardcoded credentials with Vault and GitHub OIDC.</p><h3>Step 4 — The Node.js Role</h3><p>The Node.js role manages runtime installation via nvm, ensuring version pinning and easy upgrades without system package manager conflicts:</p><pre>roles/nodejs/<br>  tasks/<br>    main.yml<br>  defaults/<br>    main.yml<br>  handlers/<br>    main.yml</pre><pre># roles/nodejs/defaults/main.yml<br>nodejs_version: &quot;20.11.0&quot;<br>nvm_version: &quot;0.39.7&quot;<br>nvm_dir: &quot;/home/{{ app_user }}/.nvm&quot;<br>npm_global_packages:<br>  - pm2<br>  - typescript</pre><pre># roles/nodejs/tasks/main.yml<br>---<br>- name: Create application user<br>  ansible.builtin.user:<br>    name: &quot;{{ app_user }}&quot;<br>    group: &quot;{{ app_group }}&quot;<br>    system: true<br>    shell: /bin/bash<br>    home: &quot;/home/{{ app_user }}&quot;<br>    create_home: true<br>  tags: [nodejs, user]<br><br>- name: Check if nvm is installed<br>  ansible.builtin.stat:<br>    path: &quot;{{ nvm_dir }}/nvm.sh&quot;<br>  register: nvm_stat<br>  tags: [nodejs, nvm]<br><br>- name: Install nvm<br>  ansible.builtin.shell:<br>    cmd: &gt;<br>      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v{{ nvm_version }}/install.sh | bash<br>  become: true<br>  become_user: &quot;{{ app_user }}&quot;<br>  when: not nvm_stat.stat.exists<br>  tags: [nodejs, nvm]<br><br>- name: Install Node.js via nvm<br>  ansible.builtin.shell:<br>    cmd: &gt;<br>      source {{ nvm_dir }}/nvm.sh &amp;&amp;<br>      nvm install {{ nodejs_version }} &amp;&amp;<br>      nvm alias default {{ nodejs_version }}<br>  args:<br>    executable: /bin/bash<br>  become: true<br>  become_user: &quot;{{ app_user }}&quot;<br>  tags: [nodejs]<br><br>- name: Install global npm packages<br>  ansible.builtin.shell:<br>    cmd: &gt;<br>      source {{ nvm_dir }}/nvm.sh &amp;&amp;<br>      npm install -g {{ item }}<br>  args:<br>    executable: /bin/bash<br>  become: true<br>  become_user: &quot;{{ app_user }}&quot;<br>  loop: &quot;{{ npm_global_packages }}&quot;<br>  tags: [nodejs, npm]</pre><h3>Step 5 — The Next.js Application Role</h3><p>The Next.js role implements a <strong>release directory pattern</strong> — the key mechanism for zero-downtime deployments and fast rollbacks:</p><pre>roles/nextjs-app/<br>  tasks/<br>    main.yml<br>    deploy.yml<br>    rollback.yml<br>    cleanup.yml<br>  templates/<br>    env.j2            ← .env.local template<br>    pm2.config.js.j2  ← PM2 ecosystem config template<br>  handlers/<br>    main.yml<br>  defaults/<br>    main.yml</pre><pre># roles/nextjs-app/tasks/deploy.yml<br>- name: Generate release timestamp<br>  ansible.builtin.set_fact:<br>    release_timestamp: &quot;{{ ansible_date_time.epoch }}&quot;<br>  tags: [deploy]<br><br>- name: Create release directory<br>  ansible.builtin.file:<br>    path: &quot;{{ app_releases_dir }}/{{ release_timestamp }}&quot;<br>    state: directory<br>    owner: &quot;{{ app_user }}&quot;<br>    group: &quot;{{ app_group }}&quot;<br>    mode: &quot;0755&quot;<br>  tags: [deploy]<br><br>- name: Upload Next.js standalone build<br>  ansible.builtin.synchronize:<br>    src: &quot;{{ local_build_path }}/.next/standalone/&quot;<br>    dest: &quot;{{ app_releases_dir }}/{{ release_timestamp }}&quot;<br>    delete: true<br>    rsync_opts:<br>      - &quot;--exclude=.git&quot;<br>  tags: [deploy]<br><br>- name: Upload static assets<br>  ansible.builtin.synchronize:<br>    src: &quot;{{ local_build_path }}/.next/static/&quot;<br>    dest: &quot;{{ app_releases_dir }}/{{ release_timestamp }}/.next/static/&quot;<br>  tags: [deploy]<br><br>- name: Template environment file<br>  ansible.builtin.template:<br>    src: env.j2<br>    dest: &quot;{{ app_releases_dir }}/{{ release_timestamp }}/.env.local&quot;<br>    owner: &quot;{{ app_user }}&quot;<br>    group: &quot;{{ app_group }}&quot;<br>    mode: &quot;0640&quot;           # restrict read to app user only<br>  tags: [deploy]<br><br>- name: Update current symlink atomically<br>  ansible.builtin.file:<br>    src: &quot;{{ app_releases_dir }}/{{ release_timestamp }}&quot;<br>    dest: &quot;{{ app_base_dir }}/current&quot;<br>    state: link<br>    owner: &quot;{{ app_user }}&quot;<br>    group: &quot;{{ app_group }}&quot;<br>  notify: Reload PM2<br>  tags: [deploy]</pre><p>The atomic symlink swap (current → new release) is the mechanism that makes zero-downtime deployments possible. PM2 reloads against the new current directory; if the reload fails, the symlink points back to the previous release.</p><pre># roles/nextjs-app/tasks/rollback.yml<br>- name: List available releases<br>  ansible.builtin.find:<br>    paths: &quot;{{ app_releases_dir }}&quot;<br>    file_type: directory<br>  register: available_releases<br>  tags: [rollback]<br><br>- name: Identify previous release<br>  ansible.builtin.set_fact:<br>    previous_release: &gt;-<br>      {{<br>        available_releases.files<br>        | sort(attribute=&#39;mtime&#39;, reverse=True)<br>        | map(attribute=&#39;path&#39;)<br>        | list<br>        | nth(1)<br>      }}<br>  tags: [rollback]<br><br>- name: Rollback symlink to previous release<br>  ansible.builtin.file:<br>    src: &quot;{{ previous_release }}&quot;<br>    dest: &quot;{{ app_base_dir }}/current&quot;<br>    state: link<br>  notify: Reload PM2<br>  tags: [rollback]<br><br>- name: Report rollback target<br>  ansible.builtin.debug:<br>    msg: &quot;Rolled back to: {{ previous_release }}&quot;<br>  tags: [rollback]</pre><h3>Step 6 — The Nginx Role</h3><pre># roles/nginx/templates/nextjs.conf.j2<br>upstream nextjs_upstream {<br>  server 127.0.0.1:{{ app_port }};<br>  keepalive 64;<br>}<br><br>server {<br>  listen 80;<br>  server_name {{ nginx_server_name }};<br>  return 301 https://$host$request_uri;<br>}<br><br>server {<br>  listen 443 ssl http2;<br>  server_name {{ nginx_server_name }};<br><br>  ssl_certificate     {{ nginx_ssl_certificate }};<br>  ssl_certificate_key {{ nginx_ssl_key }};<br>  ssl_protocols       TLSv1.2 TLSv1.3;<br>  ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;<br>  ssl_prefer_server_ciphers off;<br><br>  # Next.js static assets, long-lived cache with content hashing<br>  location /_next/static/ {<br>    alias {{ app_base_dir }}/current/.next/static/;<br>    expires 1y;<br>    add_header Cache-Control &quot;public, immutable&quot;;<br>  }<br><br>  # Public assets<br>  location /public/ {<br>    alias {{ app_base_dir }}/current/public/;<br>    expires 30d;<br>    add_header Cache-Control &quot;public&quot;;<br>  }<br><br>  # Next.js server<br>  location / {<br>    proxy_pass         http://nextjs_upstream;<br>    proxy_http_version 1.1;<br>    proxy_set_header   Upgrade $http_upgrade;<br>    proxy_set_header   Connection &#39;upgrade&#39;;<br>    proxy_set_header   Host $host;<br>    proxy_set_header   X-Real-IP $remote_addr;<br>    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_set_header   X-Forwarded-Proto $scheme;<br>    proxy_cache_bypass $http_upgrade;<br>  }<br>}</pre><pre># roles/nginx/tasks/main.yml<br>- name: Install Nginx<br>  ansible.builtin.apt:<br>    name: nginx<br>    state: present<br>    update_cache: true<br>  tags: [nginx]<br><br>- name: Template Next.js site configuration<br>  ansible.builtin.template:<br>    src: nextjs.conf.j2<br>    dest: /etc/nginx/sites-available/nextjs<br>    owner: root<br>    group: root<br>    mode: &quot;0644&quot;<br>  notify: Reload Nginx<br>  tags: [nginx]<br><br>- name: Enable site<br>  ansible.builtin.file:<br>    src: /etc/nginx/sites-available/nextjs<br>    dest: /etc/nginx/sites-enabled/nextjs<br>    state: link<br>  notify: Reload Nginx<br>  tags: [nginx]</pre><pre># roles/nginx/handlers/main.yml<br>- name: Reload Nginx<br>  ansible.builtin.service:<br>    name: nginx<br>    state: reloaded<br>  listen: Reload Nginx</pre><h3>Step 7 — Composing Playbooks</h3><p>With roles defined, playbooks become thin composition layers:</p><pre># playbooks/provision.yml - run once to set up new servers<br>- name: Provision Next.js servers<br>  hosts: nextjs_servers<br>  become: true<br>  roles:<br>    - role: common<br>      tags: [common]<br>    - role: nodejs<br>      tags: [nodejs]<br>    - role: nginx<br>      tags: [nginx]<br>    - role: pm2<br>      tags: [pm2]<br>    - role: logrotate<br>      tags: [logrotate]<br>    - role: monitoring<br>      tags: [monitoring]</pre><pre># playbooks/deploy.yml - run on every release<br>- name: Deploy Next.js application<br>  hosts: nextjs_servers<br>  become: true<br>  vars:<br>    local_build_path: &quot;{{ lookup(&#39;env&#39;, &#39;NEXT_BUILD_PATH&#39;) }}&quot;<br><br>  pre_tasks:<br>    - name: Validate build artifact exists<br>      ansible.builtin.stat:<br>        path: &quot;{{ local_build_path }}/.next/standalone&quot;<br>      delegate_to: localhost<br>      register: build_stat<br>      failed_when: not build_stat.stat.exists<br><br>  roles:<br>    - role: nextjs-app<br>      tags: [deploy]<br><br>  post_tasks:<br>    - name: Verify application is healthy<br>      ansible.builtin.uri:<br>        url: &quot;https://{{ nginx_server_name }}/api/health&quot;<br>        status_code: 200<br>        timeout: 30<br>      retries: 5<br>      delay: 10<br>      register: health_check<br>      until: health_check.status == 200</pre><pre># playbooks/rollback.yml<br>- name: Rollback Next.js to previous release<br>  hosts: nextjs_servers<br>  become: true<br>  tasks:<br>    - name: Execute rollback<br>      ansible.builtin.include_role:<br>        name: nextjs-app<br>        tasks_from: rollback</pre><h3>Step 8 — CI/CD Integration</h3><pre># .github/workflows/deploy-nextjs.yml<br>name: Deploy Next.js<br><br>on:<br>  push:<br>    branches: [main]<br><br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br>          cache: &#39;npm&#39;<br><br>      - name: Install and build<br>        run: |<br>          npm ci<br>          npm run build<br><br>      - name: Install Ansible<br>        run: pip install ansible ansible-lint --break-system-packages<br><br>      - name: Configure SSH<br>        run: |<br>          mkdir -p ~/.ssh<br>          echo &quot;${{ secrets.DEPLOY_SSH_KEY }}&quot; &gt; ~/.ssh/deploy_key<br>          chmod 600 ~/.ssh/deploy_key<br>          echo &quot;StrictHostKeyChecking no&quot; &gt;&gt; ~/.ssh/config<br><br>      - name: Deploy to production<br>        run: |<br>          ansible-playbook playbooks/deploy.yml \<br>            -i inventories/production/hosts.yml \<br>            --private-key ~/.ssh/deploy_key \<br>            -e &quot;NEXT_BUILD_PATH=${{ github.workspace }}&quot;<br>        env:<br>          ANSIBLE_HOST_KEY_CHECKING: &quot;False&quot;</pre><h3>Common Pitfalls to Avoid</h3><p><strong>Using </strong><strong>shell tasks where native modules exist.</strong> ansible.builtin.shell bypasses idempotency, it runs every time regardless of whether the state has changed. Always prefer native modules (apt, copy, template, service) and fall back to shell only when no native module covers the task.</p><p><strong>Hardcoding environment-specific values in roles.</strong> Role defaults should be genuinely sensible defaults, not production values masquerading as defaults. Production specifics belong in inventory group_vars.</p><p><strong>Not cleaning up old releases.</strong> The release directory pattern accumulates historical deployments. Add a cleanup task to retain only {{ releases_to_keep }} releases, the rest is disk usage with no operational value.</p><p><strong>Skipping the health check post-task.</strong> A deploy playbook that doesn’t verify the application is healthy after deployment is incomplete. The health check is the difference between a successful deploy and an undetected outage.</p><h3>Conclusion</h3><p>Modular Ansible playbooks are not just a style preference, they are an operational necessity at any scale beyond a single server. Roles as units of reuse, variable hierarchies for environment overlays, the release directory pattern for zero-downtime deployments, and thin playbooks for composition give you an infrastructure codebase that is maintainable, testable, and genuinely DRY.</p><p>For Next.js specifically, this architecture handles the full lifecycle, provisioning the Node.js runtime, deploying standalone build artifacts, configuring Nginx for optimal caching of static assets, managing PM2 for process reliability, and providing a one-command rollback when things go wrong.</p><p>Infrastructure code that can’t be understood, changed, and trusted by the team that operates it is a liability. Infrastructure code built to the same quality standards as your application code is a competitive advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1b99d8ecda0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Basics: How to Build a Multi-Region EKS Cluster with Terraform]]></title>
            <link>https://actocodes.medium.com/beyond-the-basics-how-to-build-a-multi-region-eks-cluster-with-terraform-d37e1d42a676?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37e1d42a676</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 16:44:39 GMT</pubDate>
            <atom:updated>2026-07-05T17:06:00.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CKxpeH8ISZefDXCW.png" /></figure><p>A single-region Kubernetes cluster is a liability in disguise. When AWS experiences a regional outage, and every major cloud provider does periodically, your entire application goes with it. For systems where availability is a business-critical requirement, a single region is not a deployment strategy, it’s a single point of failure at planetary scale.</p><p><strong>Multi-region EKS</strong> distributes your workloads across two or more AWS regions, giving you geographic redundancy, reduced latency for globally distributed users, and the ability to survive a regional failure without a production incident. But the operational complexity is real, managing two clusters, synchronizing deployments, routing traffic intelligently, and designing for state consistency across regions requires deliberate architecture.</p><p><strong>Terraform</strong> makes this complexity manageable. With its provider aliasing, module composition, and remote state capabilities, you can define your entire multi-region infrastructure as version-controlled, reviewable, reproducible code.</p><p>This guide covers how to architect and implement a multi-region EKS cluster with Terraform, from VPC design and cluster provisioning to cross-region traffic routing, state management, and disaster recovery patterns.</p><h3>Architectural Overview</h3><p>Before writing configuration, establish the target architecture. A production multi-region EKS setup typically follows one of two patterns:</p><p><strong>Active-Active:</strong> Both regions serve production traffic simultaneously. Traffic is load-balanced across regions via a global load balancer (AWS Global Accelerator or Route 53 latency routing). Each region is a full deployment of your application stack. This maximizes availability and minimizes latency but requires careful state synchronization between regions.</p><p><strong>Active-Passive (Warm Standby):</strong> One region handles all production traffic, the second region runs a scaled-down but fully deployed replica, ready to receive traffic within minutes of a failover. Simpler to operate than active-active, at the cost of idle capacity in the passive region.</p><p>For this guide, we’ll implement <strong>active-passive with warm standby</strong>, the more achievable starting point for most teams, with a clear upgrade path to active-active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*eciGMwuVViUEj0SyW6Razw.png" /></figure><h3>Step 1 — Repository and Terraform Structure</h3><p>Organize your Terraform repository to support multi-region deployments without duplication:</p><pre>/infrastructure<br>  /modules<br>    /vpc              ← reusable VPC module<br>    /eks              ← reusable EKS module<br>    /rds              ← reusable RDS module<br>    /alb              ← reusable ALB module<br>  /regions<br>    /eu-east-1        ← primary region configuration<br>      main.tf<br>      variables.tf<br>      outputs.tf<br>      backend.tf<br>    /eu-west-1        ← standby region configuration<br>      main.tf<br>      variables.tf<br>      outputs.tf<br>      backend.tf<br>  /global             ← cross-region resources (Route 53, Global Accelerator, IAM)<br>    main.tf<br>    variables.tf<br>    outputs.tf</pre><p>Each region directory consumes shared modules with region-specific variable overrides. The global directory manages resources that span regions and depends on outputs from both regional deployments.</p><h3>Step 2 — Configure Terraform Providers with Aliases</h3><p>Multi-region Terraform requires <strong>provider aliasing</strong>, defining multiple AWS provider configurations, one per region:</p><pre># infrastructure/global/providers.tf<br>terraform {<br>  required_version = &quot;&gt;= 1.6.0&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>    kubernetes = {<br>      source  = &quot;hashicorp/kubernetes&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>    helm = {<br>      source  = &quot;hashicorp/helm&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>  }<br>}</pre><pre># infrastructure/regions/eu-east-1/providers.tf<br>provider &quot;aws&quot; {<br>  alias   = &quot;primary&quot;<br>  region  = &quot;eu-east-1&quot;<br><br>  default_tags {<br>    tags = {<br>      ManagedBy   = &quot;terraform&quot;<br>      Environment = var.environment<br>      Region      = &quot;eu-east-1&quot;<br>      Role        = &quot;primary&quot;<br>    }<br>  }<br>}</pre><pre># infrastructure/regions/eu-west-1/providers.tf<br>provider &quot;aws&quot; {<br>  alias   = &quot;standby&quot;<br>  region  = &quot;eu-west-1&quot;<br><br>  default_tags {<br>    tags = {<br>      ManagedBy   = &quot;terraform&quot;<br>      Environment = var.environment<br>      Region      = &quot;eu-west-1&quot;<br>      Role        = &quot;standby&quot;<br>    }<br>  }<br>}</pre><p>The default_tags block applies consistent tagging to every resource in each region, critical for cost attribution and operational clarity when managing multi-region infrastructure.</p><h3>Step 3 — VPC Module Design</h3><p>The VPC module provisions the network foundation. Both regions use the same module with non-overlapping CIDR ranges, a requirement for VPC peering or Transit Gateway connectivity:</p><pre># infrastructure/modules/vpc/main.tf<br>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;~&gt; 5.0&quot;<br><br>  name = &quot;${var.cluster_name}-vpc&quot;<br>  cidr = var.vpc_cidr<br><br>  azs             = var.availability_zones<br>  private_subnets = var.private_subnet_cidrs<br>  public_subnets  = var.public_subnet_cidrs<br><br>  enable_nat_gateway     = true<br>  single_nat_gateway     = false       # one NAT gateway per AZ for HA<br>  enable_dns_hostnames   = true<br>  enable_dns_support     = true<br><br>  # Required tags for EKS to discover subnets<br>  private_subnet_tags = {<br>    &quot;kubernetes.io/role/internal-elb&quot;             = &quot;1&quot;<br>    &quot;kubernetes.io/cluster/${var.cluster_name}&quot;   = &quot;owned&quot;<br>  }<br><br>  public_subnet_tags = {<br>    &quot;kubernetes.io/role/elb&quot;                      = &quot;1&quot;<br>    &quot;kubernetes.io/cluster/${var.cluster_name}&quot;   = &quot;owned&quot;<br>  }<br>}</pre><pre># infrastructure/regions/eu-east-1/main.tf<br>module &quot;vpc_primary&quot; {<br>  source = &quot;../../modules/vpc&quot;<br>  providers = { aws = aws.primary }<br><br>  cluster_name         = &quot;prod-eu-east-1&quot;<br>  vpc_cidr             = &quot;10.0.0.0/16&quot;       # primary CIDR range<br>  availability_zones   = [&quot;eu-east-1a&quot;, &quot;eu-east-1b&quot;, &quot;eu-east-1c&quot;]<br>  private_subnet_cidrs = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;, &quot;10.0.3.0/24&quot;]<br>  public_subnet_cidrs  = [&quot;10.0.101.0/24&quot;, &quot;10.0.102.0/24&quot;, &quot;10.0.103.0/24&quot;]<br>}</pre><pre># infrastructure/regions/eu-west-1/main.tf<br>module &quot;vpc_standby&quot; {<br>  source = &quot;../../modules/vpc&quot;<br>  providers = { aws = aws.standby }<br><br>  cluster_name         = &quot;prod-eu-west-1&quot;<br>  vpc_cidr             = &quot;10.1.0.0/16&quot;       # non-overlapping CIDR range<br>  availability_zones   = [&quot;eu-west-1a&quot;, &quot;eu-west-1b&quot;, &quot;eu-west-1c&quot;]<br>  private_subnet_cidrs = [&quot;10.1.1.0/24&quot;, &quot;10.1.2.0/24&quot;, &quot;10.1.3.0/24&quot;]<br>  public_subnet_cidrs  = [&quot;10.1.101.0/24&quot;, &quot;10.1.102.0/24&quot;, &quot;10.1.103.0/24&quot;]<br>}</pre><p>Non-overlapping CIDRs (10.0.x.x for primary, 10.1.x.x for standby) are mandatory. Overlapping ranges prevent VPC peering and Transit Gateway routing between regions.</p><h3>Step 4 — EKS Cluster Module</h3><p>The EKS module provisions the control plane and managed node groups:</p><pre># infrastructure/modules/eks/main.tf<br>module &quot;eks&quot; {<br>  source  = &quot;terraform-aws-modules/eks/aws&quot;<br>  version = &quot;~&gt; 20.0&quot;<br><br>  cluster_name    = var.cluster_name<br>  cluster_version = var.kubernetes_version<br><br>  vpc_id                         = var.vpc_id<br>  subnet_ids                     = var.private_subnet_ids<br>  cluster_endpoint_public_access = false          # private endpoint only<br>  cluster_endpoint_private_access = true<br><br>  cluster_addons = {<br>    coredns    = { most_recent = true }<br>    kube-proxy = { most_recent = true }<br>    vpc-cni    = { most_recent = true }<br>    aws-ebs-csi-driver = { most_recent = true }<br>  }<br><br>  eks_managed_node_groups = {<br>    system = {<br>      name           = &quot;${var.cluster_name}-system&quot;<br>      instance_types = [&quot;m6i.large&quot;]<br>      min_size       = 2<br>      max_size       = 4<br>      desired_size   = 2<br><br>      labels = { role = &quot;system&quot; }<br>      taints = [{<br>        key    = &quot;CriticalAddonsOnly&quot;<br>        value  = &quot;true&quot;<br>        effect = &quot;NO_SCHEDULE&quot;<br>      }]<br>    }<br><br>    application = {<br>      name           = &quot;${var.cluster_name}-application&quot;<br>      instance_types = [&quot;m6i.xlarge&quot;, &quot;m6i.2xlarge&quot;]<br>      min_size       = var.min_app_nodes<br>      max_size       = var.max_app_nodes<br>      desired_size   = var.desired_app_nodes<br><br>      labels = { role = &quot;application&quot; }<br>    }<br>  }<br><br>  # Enable IRSA for pod-level IAM roles<br>  enable_irsa = true<br>}</pre><p>In the standby region, pass reduced node counts to minimize idle capacity costs:</p><pre># infrastructure/regions/eu-west-1/main.tf - standby node counts<br>module &quot;eks_standby&quot; {<br>  source = &quot;../../modules/eks&quot;<br>  providers = { aws = aws.standby }<br><br>  cluster_name        = &quot;prod-eu-west-1&quot;<br>  kubernetes_version  = &quot;1.29&quot;<br>  vpc_id              = module.vpc_standby.vpc_id<br>  private_subnet_ids  = module.vpc_standby.private_subnets<br><br>  # Warm standby — minimum viable footprint, scales up on failover<br>  min_app_nodes     = 1<br>  max_app_nodes     = 20      # headroom for failover traffic burst<br>  desired_app_nodes = 2<br>}</pre><h3>Step 5 — Remote State Configuration and Cross-Region References</h3><p>Each region’s Terraform state is stored independently in S3. The global configuration reads outputs from both regional states:</p><pre># infrastructure/regions/eu-east-1/backend.tf<br>```hcl<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;your-org-terraform-state&quot;<br>    key            = &quot;eks/eu-east-1/terraform.tfstate&quot;<br>    region         = &quot;eu-east-1&quot;<br>    encrypt        = true<br>    dynamodb_table = &quot;terraform-state-lock&quot;<br>  }<br>}</pre><pre># infrastructure/global/main.tf - reading cross-region outputs<br>data &quot;terraform_remote_state&quot; &quot;primary&quot; {<br>  backend = &quot;s3&quot;<br>  config = {<br>    bucket = &quot;your-org-terraform-state&quot;<br>    key    = &quot;eks/eu-east-1/terraform.tfstate&quot;<br>    region = &quot;eu-east-1&quot;<br>  }<br>}<br><br>data &quot;terraform_remote_state&quot; &quot;standby&quot; {<br>  backend = &quot;s3&quot;<br>  config = {<br>    bucket = &quot;your-org-terraform-state&quot;<br>    key    = &quot;eks/eu-west-1/terraform.tfstate&quot;<br>    region = &quot;eu-east-1&quot;   # state bucket is in primary region; key points to standby state<br>  }<br>}</pre><p>Remote state data sources allow your global configuration to consume the ALB DNS names, cluster endpoint ARNs, and VPC IDs from both regions, enabling Route 53 health-check-based failover configuration without manual copy-pasting.</p><h3>Step 6 — Cross-Region Traffic Routing with Route 53</h3><p>Configure Route 53 health-check-based failover routing, automatically switching traffic to the standby region when the primary region’s health check fails:</p><pre># infrastructure/global/route53.tf<br># Health check against primary region ALB<br>resource &quot;aws_route53_health_check&quot; &quot;primary&quot; {<br>  fqdn              = data.terraform_remote_state.primary.outputs.alb_dns_name<br>  port              = 443<br>  type              = &quot;HTTPS&quot;<br>  resource_path     = &quot;/health&quot;<br>  failure_threshold = 3<br>  request_interval  = 30<br><br>  tags = { Name = &quot;primary-health-check&quot; }<br>}<br><br># Primary record - active under normal conditions<br>resource &quot;aws_route53_record&quot; &quot;primary&quot; {<br>  zone_id = var.route53_zone_id<br>  name    = &quot;api.your-domain.com&quot;<br>  type    = &quot;A&quot;<br><br>  failover_routing_policy {<br>    type = &quot;PRIMARY&quot;<br>  }<br><br>  set_identifier  = &quot;primary&quot;<br>  health_check_id = aws_route53_health_check.primary.id<br><br>  alias {<br>    name                   = data.terraform_remote_state.primary.outputs.alb_dns_name<br>    zone_id                = data.terraform_remote_state.primary.outputs.alb_zone_id<br>    evaluate_target_health = true<br>  }<br>}<br><br># Standby record - receives traffic when primary health check fails<br>resource &quot;aws_route53_record&quot; &quot;standby&quot; {<br>  zone_id = var.route53_zone_id<br>  name    = &quot;api.your-domain.com&quot;<br>  type    = &quot;A&quot;<br><br>  failover_routing_policy {<br>    type = &quot;SECONDARY&quot;<br>  }<br><br>  set_identifier = &quot;standby&quot;<br><br>  alias {<br>    name                   = data.terraform_remote_state.standby.outputs.alb_dns_name<br>    zone_id                = data.terraform_remote_state.standby.outputs.alb_zone_id<br>    evaluate_target_health = true<br>  }<br>}</pre><p>With this configuration, Route 53 continuously polls the primary region’s health check endpoint. If three consecutive checks fail (90 seconds), DNS failover to the standby region initiates automatically, no human intervention required.</p><h3>Step 7 — GitOps Deployment with Flux Across Regions</h3><p>Managing application deployments across two clusters requires a GitOps controller in each region pulling from the same source of truth. <strong>Flux CD</strong> is purpose-built for this:</p><pre># gitops/clusters/eu-east-1/flux-system/kustomization.yaml<br>apiVersion: kustomize.toolkit.fluxcd.io/v1<br>kind: Kustomization<br>metadata:<br>  name: apps<br>  namespace: flux-system<br>spec:<br>  interval: 5m<br>  path: ./gitops/apps/production<br>  prune: true<br>  sourceRef:<br>    kind: GitRepository<br>    name: fleet-repository</pre><pre># gitops/clusters/eu-west-1/flux-system/kustomization.yaml<br>apiVersion: kustomize.toolkit.fluxcd.io/v1<br>kind: Kustomization<br>metadata:<br>  name: apps<br>  namespace: flux-system<br>spec:<br>  interval: 5m<br>  path: ./gitops/apps/production   # same app manifests, different cluster<br>  prune: true<br>  sourceRef:<br>    kind: GitRepository<br>    name: fleet-repository</pre><p>Both Flux instances reconcile against the same gitops/apps/production path in your Git repository. A single push to main deploys to both regions, maintaining configuration parity automatically without manual multi-cluster kubectl commands.</p><h3>Step 8 — Database Strategy for Multi-Region</h3><p>Application state is the hardest problem in multi-region architecture. For PostgreSQL:</p><pre># infrastructure/modules/rds/main.tf - primary RDS instance<br>resource &quot;aws_db_instance&quot; &quot;primary&quot; {<br>  provider               = aws.primary<br>  identifier             = &quot;${var.cluster_name}-primary&quot;<br>  engine                 = &quot;postgres&quot;<br>  engine_version         = &quot;16.1&quot;<br>  instance_class         = &quot;db.r6g.xlarge&quot;<br>  allocated_storage      = 100<br>  storage_encrypted      = true<br><br>  backup_retention_period = 7<br>  backup_window           = &quot;03:00-04:00&quot;<br><br>  # Enable automated backups to S3 for cross-region restore<br>  enabled_cloudwatch_logs_exports = [&quot;postgresql&quot;]<br>}<br><br># Cross-region read replica in standby region<br>resource &quot;aws_db_instance&quot; &quot;standby_replica&quot; {<br>  provider            = aws.standby<br>  identifier          = &quot;${var.cluster_name}-standby-replica&quot;<br>  replicate_source_db = aws_db_instance.primary.arn   # cross-region replication<br>  instance_class      = &quot;db.r6g.large&quot;                # smaller read-only in standby<br>  storage_encrypted   = true<br><br>  # Replica can be promoted to primary during failover<br>  # Promotion is a manual or automated operational step, not instantaneous<br>}</pre><p>The read replica in the standby region receives continuous replication from the primary, typically with 1–5 seconds of replication lag. During a failover, promoting the replica to a standalone primary takes several minutes, during which write operations are unavailable. Design your application’s failover behavior (queuing writes, surfacing a maintenance page) around this window.</p><h3>CI/CD Integration</h3><pre># .github/workflows/terraform-deploy.yml<br>name: Terraform Multi-Region Deploy<br><br>on:<br>  push:<br>    branches: [main]<br>    paths: [&#39;infrastructure/**&#39;]<br><br>jobs:<br>  deploy-primary:<br>    runs-on: ubuntu-latest<br>    environment: production<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: hashicorp/setup-terraform@v3<br><br>      - name: Terraform Apply - eu-east-1<br>        working-directory: infrastructure/regions/eu-east-1<br>        run: |<br>          terraform init<br>          terraform apply -auto-approve<br>        env:<br>          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br><br>  deploy-standby:<br>    runs-on: ubuntu-latest<br>    needs: deploy-primary       # apply standby after primary succeeds<br>    environment: production<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: hashicorp/setup-terraform@v3<br><br>      - name: Terraform Apply — eu-west-1<br>        working-directory: infrastructure/regions/eu-west-1<br>        run: |<br>          terraform init<br>          terraform apply -auto-approve<br>        env:<br>          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br><br>  deploy-global:<br>    runs-on: ubuntu-latest<br>    needs: [deploy-primary, deploy-standby]   # global depends on both regions<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: hashicorp/setup-terraform@v3<br><br>      - name: Terraform Apply — global<br>        working-directory: infrastructure/global<br>        run: |<br>          terraform init<br>          terraform apply -auto-approve</pre><p>The needs dependency chain ensures the global configuration (Route 53 failover) is applied only after both regional clusters are provisioned and their outputs are available in remote state.</p><h3>Common Pitfalls to Avoid</h3><p><strong>Overlapping CIDR ranges.</strong> The most common setup mistake, and the one that forces a complete VPC rebuild to fix. Plan your IP address space before writing any Terraform.</p><p><strong>Single NAT gateway per region.</strong> Using one NAT gateway per region (instead of one per AZ) is cheaper but creates an availability zone as a single point of failure. Use single_nat_gateway = false in production.</p><p><strong>Not testing failover.</strong> A failover procedure that has never been practiced will fail under pressure. Schedule a quarterly failover drill, redirect traffic to the standby region, validate application behavior, then cut back.</p><p><strong>Treating the standby as truly passive.</strong> A warm standby that receives no real traffic is also receiving no validation that it works. Consider routing a small percentage of read traffic (5–10%) to the standby region to continuously validate its health.</p><p><strong>State drift between regions.</strong> Without GitOps enforcing parity, application deployments to the primary region can drift from the standby. Flux or ArgoCD reconciliation against a single Git source is the most reliable prevention.</p><h3>Conclusion</h3><p>Building a multi-region EKS cluster with Terraform is one of the highest-leverage investments a platform team can make in system reliability. It eliminates the single largest uncontrolled failure mode in cloud-native infrastructure, regional availability, and does so in a way that is reproducible, version-controlled, and operationally predictable.</p><p>Start with active-passive. Get the Terraform modules right, validate the Route 53 failover, practice the database promotion procedure, and establish GitOps parity across both clusters. Once that foundation is solid, the path to active-active is an evolution of what you’ve already built, not a rewrite.</p><p>The blueprint takes time to draw. The construction, as always, is where automation earns its keep.</p><p><em>Using GKE or AKS instead of EKS? The multi-region architecture patterns and GitOps strategy in this guide apply directly, the Terraform provider and cluster module differ, but the design is cloud-agnostic. Drop your platform in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37e1d42a676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Blueprint for 2026: Why Architecture Must Precede Automation]]></title>
            <link>https://actocodes.medium.com/the-blueprint-for-2026-why-architecture-must-precede-automation-502b60c84872?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/502b60c84872</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[engineering-leadership]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-06-28T17:01:01.825Z</atom:updated>
            <content:encoded><![CDATA[<p>2026 has brought no shortage of automation tooling, AI coding agents that scaffold entire features, CI/CD pipelines that deploy on every commit, and infrastructure-as-code platforms that provision environments in minutes. The temptation is to treat automation as a substitute for architectural discipline: if the tooling is fast enough, do the underlying design decisions even matter?</p><p>They matter more than ever. Automation amplifies whatever you point it at, including bad architecture. A poorly bounded service automated into a CI/CD pipeline doesn’t become well-bounded, it becomes a poorly bounded service that ships faster and breaks more often. An AI coding agent given a vague, undocumented module doesn’t infer good structure from chaos, it replicates the chaos at speed.</p><p>This article makes the case for a principle that’s easy to state and hard to practice: <strong>architecture must precede automation</strong>. We’ll look at why this ordering matters, what happens when teams get it backward, and how to build the discipline to get it right.</p><h3>Automation Is a Force Multiplier</h3><p>The core insight is simple, automation doesn’t fix structural problems. It multiplies the rate at which those problems manifest.</p><p>Consider a backend system with tangled service boundaries, where orders-service reaches directly into users-service&#39;s database, where business logic is duplicated across three modules, where there&#39;s no clear ownership of shared data models. Without automation, these problems surface slowly, a developer hits friction, works around it, ships anyway. Painful, but contained.</p><p>Now introduce aggressive CI/CD automation, AI-assisted code generation, and infrastructure-as-code into that same system. Deployments that used to take a day now take ten minutes. AI agents generate new endpoints against the tangled data model in seconds. The same structural problems that used to surface occasionally now surface constantly and faster than your team can absorb the friction.</p><p>This is the central danger of automating before architecting: <strong>you don’t remove the bottleneck, you relocate it</strong>, usually to incident response, on-call burden, or a production outage that automation made possible to ship faster but no easier to recover from.</p><h3>What “Architecture First” Actually Means</h3><p>“Architecture first” is not a call to return to multi-month design documents before writing a line of code. In 2026’s engineering environment, that approach is its own form of dysfunction, over-planning that delays value delivery without guaranteeing better outcomes. Architecture-first means something more specific and more practical:</p><p><strong>Define boundaries before you automate across them.</strong> If you don’t know where one service’s responsibility ends and another’s begins, automating deployment, testing, or infrastructure across that ambiguous boundary only makes the ambiguity move faster. Service boundaries, data ownership, and API contracts are architectural decisions that must be made deliberately, not discovered accidentally through automation tooling.</p><p><strong>Establish your domain model before generating code against it.</strong> AI coding agents are remarkably effective at extending an existing, well-structured codebase. They are equally effective at extending a poorly structured one, producing more code that follows the same bad patterns, at a volume no human reviewer can reasonably keep up with.</p><p><strong>Decide your failure model before automating recovery.</strong> Self-healing systems, automated rollbacks, and circuit breakers are powerful, but only if you’ve already decided what failure looks like, what’s recoverable, and what requires human judgment. Automating recovery for a system whose failure modes haven’t been mapped is automating guesswork.</p><p><strong>Choose your data architecture before automating data pipelines.</strong> Once an ETL pipeline, a caching layer, or an event stream is automated and running, the underlying data model becomes extremely expensive to change, every downstream automated process depends on it remaining stable.</p><h3>The 2026 Pressure Toward Automation-First</h3><p>It’s worth naming why this principle is harder to follow now than it was five years ago.</p><p><strong>AI coding agents lower the cost of generating code dramatically</strong>, which makes “just generate it and see” feel like a reasonable substitute for upfront design. The cost of writing code has dropped, the cost of living with the wrong architecture has not.</p><p><strong>CI/CD maturity has made deployment nearly frictionless</strong>, which removes a natural pause point that used to force teams to think before shipping. When deploying took an afternoon of manual steps, teams were implicitly forced to batch decisions and consider them more carefully. When deploying takes ninety seconds, that forcing function disappears.</p><p><strong>Competitive pressure rewards visible velocity</strong> over invisible architectural soundness. Shipping ten features this quarter is visible to leadership. The clean service boundary that made shipping the eleventh feature possible without a rewrite is invisible, until it’s missing.</p><p>None of this means automation is the problem. It means automation has gotten powerful enough that it no longer provides natural friction against bad architectural decisions, that friction now has to be deliberately engineered back in, through team practices and review discipline.</p><h3>What Architecture-First Looks like in Practice</h3><p>This doesn’t require slowing down, it requires sequencing.</p><p><strong>Before automating CI/CD for a new service:</strong> define its API contract, its data ownership boundary, and its failure isolation strategy. This can take an afternoon of focused design discussion, not a quarter of documentation. The output is a lightweight decision record, not a 40-page architecture document.</p><p><strong>Before pointing an AI coding agent at a codebase:</strong> ensure the codebase has clear module boundaries, consistent naming conventions, and a small number of canonical patterns the agent can learn from and extend. An agent given a clean example to follow produces dramatically better output than one given a blank slate or a tangled mess.</p><p><strong>Before automating infrastructure provisioning:</strong> decide your environment topology, your network boundaries, and your secrets management approach (see our guide on replacing hardcoded credentials with Vault and GitHub OIDC). Terraform modules generated against an undefined topology become technical debt the moment they’re applied.</p><p><strong>Before automating test generation:</strong> define what correctness actually means for the system under test, the contracts, the invariants, the edge cases that matter to the business. AI-generated tests against an undefined specification produce tests that pass without verifying anything meaningful.</p><p>The pattern across all of these is, a small deliberate architectural decision made <em>before</em> automation gives the automation something solid to amplify. Skipping that decision gives automation chaos to amplify instead.</p><h3>The Cost of Getting the Order Wrong</h3><p>Teams that automate before architecting tend to discover the cost in a predictable sequence:</p><p><strong>First, velocity feels great.</strong> Automation is shipping fast. Dashboards show high deployment frequency, high PR throughput, high AI-assisted code volume.</p><p><strong>Then, defects compound faster than they can be fixed.</strong> Because the underlying structure was never sound, every new automated change has a wider blast radius than expected. Bugs surface in unexpected places because boundaries were never enforced.</p><p><strong>Then, the team builds automation to manage the automation.</strong> More alerting to catch what the velocity is breaking. More rollback automation to recover from what the velocity is shipping. This is a sign the team is now spending its automation investment compensating for an architectural debt it never paid down, not multiplying genuine engineering leverage.</p><p><strong>Finally, a rewrite becomes the only path forward.</strong> At this point, the team faces the choice no one wants, a costly, risky architectural rewrite, executed under the same time pressure that caused the original problem.</p><p>This sequence is avoidable, not by rejecting automation, but by insisting on the right order of operations.</p><h3>A Practical Framework: The Architecture Gate</h3><p>For teams who want a concrete practice rather than just a principle, introduce an <strong>architecture gate</strong> before any significant automation investment:</p><p>Before automating: [CI/CD pipeline | AI code generation | infra provisioning | test generation]</p><p>Ask:</p><ol><li>Are the relevant service/module boundaries explicitly defined?</li><li>Is data ownership for this domain unambiguous?</li><li>Is there a documented contract (API, schema, interface) the automation will rely on?</li><li>Have failure modes for this component been identified and categorized?</li><li>Is there a clear owner for decisions this automation will encode at scale?</li></ol><p>If any answer is “no”, pause and resolve it first. The fix is usually a focused half-day design discussion, not a lengthy process.</p><p>This isn’t bureaucracy for its own sake. It’s a five-question checklist that takes less time than debugging the first production incident caused by skipping it.</p><h3>Architecture and Automation Are Not in Tension</h3><p>The framing of “architecture vs. automation” is itself a false choice. The most effective engineering organizations in 2026 don’t choose one over the other, they sequence them correctly. Sound architecture is what makes aggressive automation safe. Aggressive automation is what makes sound architecture deliver value at speed.</p><p>A well-bounded microservices architecture (see our guide on migrating from monolith to microservices with NestJS and Postgres) becomes dramatically more valuable once CI/CD, contract testing, and observability are automated around it, because the boundaries hold under the increased velocity rather than buckling.</p><p>The lesson for 2026 is not “slow down.” It’s “decide deliberately, then move fast.” Architecture is the blueprint. Automation is the construction crew. No amount of construction speed compensates for a blueprint that was never drawn.</p><h3>Conclusion</h3><p>As AI tooling and automation platforms continue to compress the time between idea and deployed code, the temptation to skip architectural thinking will only grow stronger, because skipping it no longer feels like it costs anything, in the moment. It does. It simply defers the cost to a less convenient time, at a larger scale, with less context available to fix it.</p><p>The teams that will build the most reliable, adaptable systems in 2026 are not the ones who automate the most. They’re the ones who know precisely what to automate, because they took the time to architect it first.</p><p>Draw the blueprint. Then build fast.</p><p><em>What’s your team’s process for architectural review before adopting new automation tooling? Share your approach in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=502b60c84872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Auditing at Scale: How to Automate Supply Chain Security with Dependabot and Snyk]]></title>
            <link>https://actocodes.medium.com/dependency-auditing-at-scale-how-to-automate-supply-chain-security-with-dependabot-and-snyk-3e5cfbd84972?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5cfbd84972</guid>
            <category><![CDATA[dependabot]]></category>
            <category><![CDATA[snyk]]></category>
            <category><![CDATA[supply-chain-security]]></category>
            <category><![CDATA[vulnerability-management]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 11:19:22 GMT</pubDate>
            <atom:updated>2026-06-21T17:01:02.433Z</atom:updated>
            <content:encoded><![CDATA[<p>The average modern web application depends on hundreds, sometimes thousands, of transitive npm packages. Each one is a potential attack vector, a vulnerability waiting to be disclosed, a maintainer account waiting to be compromised, or a malicious update waiting to be published. Manually tracking the security posture of a dependency tree this large is not just impractical at any meaningful scale, it is impossible.</p><p><strong>Supply chain security</strong> has moved from a niche compliance concern to a top-tier engineering priority, driven by high-profile incidents like the event-stream backdoor, the ua-parser-js compromise, and the XZ Utils backdoor that nearly compromised SSH across major Linux distributions. Attackers have learned that compromising one widely-used package is more efficient than attacking a thousand individual applications.</p><p>This guide covers how to build an automated dependency auditing pipeline using <strong>GitHub Dependabot</strong> and <strong>Snyk</strong>, two complementary tools that, used together, give you continuous vulnerability detection, automated remediation, and CI/CD gates that stop vulnerable code before it ships.</p><h3>Why Manual Dependency Management Doesn’t Scale</h3><p>Consider a mid-sized application with 40 direct dependencies. Each of those typically pulls in 10–30 transitive dependencies of its own, meaning your actual dependency tree can easily exceed 800–1200 packages. Each package:</p><ul><li>Has its own maintainers, release cadence, and security practices</li><li>Can be updated at any time, potentially introducing a vulnerability or malicious code</li><li>May depend on other packages with their own vulnerabilities</li><li>Often includes postinstall scripts that execute arbitrary code on npm install</li></ul><p>Manually monitoring CVE databases, cross-referencing them against your package-lock.json, and tracking remediation status across dozens of services is not a sustainable practice. It requires automation, both for detection and for response.</p><h3>Understanding the Two-Tool Strategy</h3><p><strong>Dependabot</strong> (native to GitHub) and <strong>Snyk</strong> (a dedicated security platform) overlap in purpose but differ in depth and capability. Understanding the distinction helps you use both effectively rather than redundantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*6_SZbppGzJjbvzFTDVOkPA.png" /></figure><p><strong>Recommended approach:</strong> Use Dependabot as your baseline, always-on dependency update mechanism, it’s free, native, and requires minimal setup. Layer Snyk on top for deeper vulnerability intelligence, license compliance, and broader scanning coverage (containers, IaC, code-level issues) across your most critical services.</p><h3>Step 1 — Configure Dependabot</h3><p>Dependabot is configured via a single YAML file per repository. Start with version updates and security updates enabled:</p><pre># .github/dependabot.yml<br>version: 2<br>updates:<br>  - package-ecosystem: &quot;npm&quot;<br>    directory: &quot;/&quot;<br>    schedule:<br>      interval: &quot;weekly&quot;<br>      day: &quot;monday&quot;<br>      time: &quot;09:00&quot;<br>    open-pull-requests-limit: 10<br>    groups:<br>      production-dependencies:<br>        dependency-type: &quot;production&quot;<br>        update-types: [&quot;minor&quot;, &quot;patch&quot;]<br>      development-dependencies:<br>        dependency-type: &quot;development&quot;<br>        update-types: [&quot;minor&quot;, &quot;patch&quot;, &quot;major&quot;]<br>    ignore:<br>      - dependency-name: &quot;legacy-package&quot;<br>        update-types: [&quot;version-update:semver-major&quot;]<br>    labels:<br>      - &quot;dependencies&quot;<br>      - &quot;automated&quot;<br>    reviewers:<br>      - &quot;platform-team&quot;<br>    commit-message:<br>      prefix: &quot;chore(deps)&quot;<br><br>  - package-ecosystem: &quot;docker&quot;<br>    directory: &quot;/&quot;<br>    schedule:<br>      interval: &quot;weekly&quot;<br><br>  - package-ecosystem: &quot;github-actions&quot;<br>    directory: &quot;/.github/workflows&quot;<br>    schedule:<br>      interval: &quot;weekly&quot;</pre><p>Key configuration decisions:</p><ul><li><strong>groups</strong> consolidates multiple minor/patch updates into a single PR, dramatically reducing PR noise for large dependency trees.</li><li><strong>open-pull-requests-limit</strong> prevents Dependabot from overwhelming your review queue.</li><li><strong>Separate ecosystems</strong> (docker, github-actions) ensure your container base images and CI workflow actions are also kept current, both common and overlooked attack surfaces.</li></ul><h3>Enabling Security-Only Updates</h3><p>Security updates are enabled by default once Dependabot alerts are turned on for the repository, and they bypass the schedule, firing immediately when a new vulnerability is disclosed for a dependency you use:</p><pre>Repository → Settings → Code security and analysis <br>Dependabot alerts <br>Dependabot security updates <br>Dependabot version updates</pre><h3>Step 2 — Configure Snyk for Deeper Scanning</h3><p>Install the Snyk GitHub integration and add a .snyk policy file to your repository:</p><pre>npm install -g snyk<br>snyk auth<br>snyk test</pre><p>Generate a baseline .snyk policy file to manage known, accepted-risk vulnerabilities with documented justification:</p><pre># .snyk<br>version: v1.5.0<br>ignore:<br>  SNYK-JS-LODASH-1040724:<br>    - &#39;*&#39;:<br>        reason: &gt;<br>          Vulnerability is in a dev-only build tool, not present in<br>          production bundle. Tracked in JIRA-4521 for upgrade in Q3.<br>        expires: 2026-09-30T00:00:00.000Z<br>patch: {}</pre><p><strong>Never use </strong><strong>.snyk to silently suppress vulnerabilities.</strong> Every ignored entry requires a documented reason and an expiration date, forcing periodic re-evaluation rather than permanent suppression.</p><h3>Snyk CI Integration</h3><pre># .github/workflows/snyk-security.yml<br>name: Snyk Security Scan<br><br>on:<br>  push:<br>    branches: [main, develop]<br>  pull_request:<br><br>jobs:<br>  snyk-dependencies:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Run Snyk to check for vulnerabilities<br>        uses: snyk/actions/node@master<br>        env:<br>          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br>        with:<br>          args: --severity-threshold=high --fail-on=upgradable<br><br>      - name: Run Snyk Code (SAST)<br>        uses: snyk/actions/node@master<br>        env:<br>          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br>        with:<br>          command: code test<br>          args: --severity-threshold=high<br><br>  snyk-container:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Build container image<br>        run: docker build -t app:${{ github.sha }} .<br><br>      - name: Run Snyk Container scan<br>        uses: snyk/actions/docker@master<br>        env:<br>          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br>        with:<br>          image: app:${{ github.sha }}<br>          args: --severity-threshold=high</pre><p>The --fail-on=upgradable flag is important, it only fails the build for vulnerabilities that have an available fix, preventing your pipeline from blocking on issues you currently have no way to remediate.</p><h3>Step 3 — License Compliance Scanning</h3><p>Open source licenses carry legal obligations, some permissive (MIT, Apache 2.0), others restrictive (GPL, AGPL) in ways that can create compliance risk for commercial products. Snyk’s license scanning catches these automatically:</p><pre># Add license policy enforcement<br>- name: Snyk License Compliance<br>  uses: snyk/actions/node@master<br>  env:<br>    SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br>  with:<br>    command: test<br>    args: --severity-threshold=high --fail-on=all<br>            --policy-path=.snyk-license-policy.json</pre><p>Configure license policies in the Snyk dashboard to flag or block specific license types:</p><pre>Disallow:  GPL-3.0, AGPL-3.0, SSPL-1.0<br>Warn:      LGPL-2.1, MPL-2.0<br>Allow:     MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC</pre><p>This is particularly critical for companies building commercial or closed-source products, an AGPL-licensed transitive dependency can create unexpected obligations to release your own source code.</p><h3>Step 4 — Prioritizing Remediation with Risk Scoring</h3><p>Not every vulnerability deserves the same urgency. A critical CVE in a dependency that’s only used in your test suite is lower risk than a medium-severity CVE in a package that processes user input in production.</p><p>Snyk’s <strong>risk scoring</strong> considers exploit maturity, whether the vulnerable code path is actually reachable, and the dependency’s position in your tree (direct vs. transitive) to prioritize remediation:</p><pre># View prioritized vulnerabilities sorted by risk score<br>snyk test --json | snyk-to-html -o report.html<br><br># Or query via API for custom dashboards<br>curl -H &quot;Authorization: token $SNYK_TOKEN&quot; \<br>  &quot;https://api.snyk.io/v1/org/$ORG_ID/projects/$PROJECT_ID/issues&quot;</pre><p>Establish a remediation SLA based on severity and reachability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*z_sy0EAB1eZKXlIWZGmXBw.png" /></figure><h3>Step 5 — Automating Patch PRs and Auto-Merge</h3><p>For low-risk updates, patch and minor version bumps with passing tests, automate the entire remediation loop:</p><pre># .github/workflows/automerge-dependabot.yml<br>name: Auto-merge Dependabot PRs<br><br>on: pull_request<br><br>permissions:<br>  pull-requests: write<br>  contents: write<br><br>jobs:<br>  automerge:<br>    runs-on: ubuntu-latest<br>    if: github.actor == &#39;dependabot[bot]&#39;<br>    steps:<br>      - name: Fetch Dependabot metadata<br>        id: metadata<br>        uses: dependabot/fetch-metadata@v2<br>        with:<br>          github-token: &quot;${{ secrets.GITHUB_TOKEN }}&quot;<br><br>      - name: Auto-approve patch and minor updates<br>        if: steps.metadata.outputs.update-type == &#39;version-update:semver-patch&#39; || steps.metadata.outputs.update-type == &#39;version-update:semver-minor&#39;<br>        run: gh pr review --approve &quot;$PR_URL&quot;<br>        env:<br>          PR_URL: ${{ github.event.pull_request.html_url }}<br>          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}<br><br>      - name: Enable auto-merge<br>        if: steps.metadata.outputs.update-type == &#39;version-update:semver-patch&#39; || steps.metadata.outputs.update-type == &#39;version-update:semver-minor&#39;<br>        run: gh pr merge --auto --squash &quot;$PR_URL&quot;<br>        env:<br>          PR_URL: ${{ github.event.pull_request.html_url }}<br>          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><p>Auto-merge should only apply to patch/minor updates <strong>and</strong> require your full CI suite (tests, linting, security scans) to pass first. gh pr merge --auto waits for all required status checks before merging. Major version updates should always require human review, since they&#39;re more likely to introduce breaking changes.</p><h3>Step 6 — Software Bill of Materials (SBOM) Generation</h3><p>Beyond vulnerability scanning, regulatory and enterprise procurement requirements increasingly demand a <strong>Software Bill of Materials</strong>, a complete inventory of every component in your software supply chain:</p><pre># Generate an SBOM in CycloneDX format using Snyk <br>snyk sbom --format =cyclonedx1.5+json --org = $ORG_ID &gt; sbom.json</pre><pre># .github/workflows/sbom.yml<br>- name: Generate SBOM<br>  run: snyk sbom --format=cyclonedx1.5+json &gt; sbom.json<br>  env:<br>    SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br><br>- name: Upload SBOM as release artifact<br>  uses: actions/upload-artifact@v4<br>  with:<br>    name: sbom<br>    path: sbom.json</pre><p>Store SBOMs alongside each release artifact, they provide auditable proof of exactly what shipped, which is increasingly required for enterprise customers and government contracts (e.g., U.S. Executive Order 14028 compliance).</p><h3>Step 7 — Blocking Malicious Packages Proactively</h3><p>Beyond known CVEs, supply chain attacks often involve packages with no disclosed vulnerability, because the malicious behavior was intentionally introduced by a compromised maintainer account. Snyk and GitHub both maintain databases of known-malicious packages distinct from standard CVE tracking:</p><pre># Block installation of known-malicious packages at install time<br>- name: Check for malicious packages<br>  run: |<br>    npx socket-security audit  # cross-references known malicious package database</pre><p>Combine this with npm ci --ignore-scripts in CI to prevent postinstall scripts from executing arbitrary code during dependency installation, a common vector for credential exfiltration:</p><pre>npm ci --ignore-scripts<br># Run necessary build scripts explicitly and individually instead of trusting postinstall hooks<br>npm run build</pre><h3>Common Pitfalls to Avoid</h3><p><strong>Treating Dependabot PR volume as noise to ignore.</strong> A repository with 60 open Dependabot PRs signals the automation is not being acted on, defeating its purpose. Use grouping and auto-merge for low-risk updates to keep the queue manageable.</p><p><strong>Scanning only direct dependencies.</strong> The majority of real-world vulnerabilities live in transitive dependencies your team has never directly chosen. Ensure your scanning tools traverse the full dependency tree, not just package.json.</p><p><strong>No reachability analysis.</strong> Flagging every CVE in every dependency, even ones whose vulnerable code path is never executed, creates alert fatigue. Use tools with reachability analysis (Snyk Code, Socket) to prioritize what’s actually exploitable in your application.</p><p><strong>Ignoring container and IaC layers.</strong> Application dependencies are only one layer of your supply chain. Base container images and Terraform providers carry their own vulnerabilities and deserve the same scanning rigor.</p><h3>Conclusion</h3><p>Supply chain security at scale cannot be a manual process, the sheer size of modern dependency trees makes that mathematically impossible to sustain. <strong>Dependabot</strong> provides a free, always-on baseline for dependency updates and security patches. <strong>Snyk</strong> adds depth: license compliance, container and IaC scanning reachability-aware risk scoring, and code-level SAST.</p><p>Used together, with auto-merge for low-risk updates, documented exception policies for accepted risk, and SBOM generation for auditability, you transform dependency management from a reactive scramble after each disclosed CVE into a continuous, automated engineering practice.</p><p>The goal isn’t zero vulnerabilities, that’s not achievable in any non-trivial dependency tree. The goal is <strong>continuous visibility, fast remediation for what’s exploitable, and an audit trail for everything else.</strong></p><p><em>Running a polyglot stack with Python, Go, and Java services alongside Node.js? Both Dependabot and Snyk support multi-ecosystem scanning natively — the configuration patterns in this guide apply with ecosystem-specific adjustments. Drop your stack in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5cfbd84972" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secrets Management in CI/CD: How to Replace Hardcoded Credentials with Vault and GitHub OIDC]]></title>
            <link>https://actocodes.medium.com/secrets-management-in-ci-cd-how-to-replace-hardcoded-credentials-with-vault-and-github-oidc-cf89d0beee14?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf89d0beee14</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[management-secrets]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-06-14T17:01:02.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Hardcoded credentials are one of the most persistent and dangerous security vulnerabilities in modern software delivery. Database passwords committed to .env files, AWS access keys stored as long-lived GitHub repository secrets, API tokens embedded in CI configuration, these are not edge cases. They are standard practice at the majority of engineering teams, and they represent a ticking clock.</p><p>When a long-lived credential leaks, through a misconfigured repository, a disgruntled employee, or a supply chain compromise, the window of exposure is measured in the lifetime of the credential, often months or years. The blast radius includes every system that credential has access to.</p><p>The solution is not better secret hygiene on static credentials. It is eliminating static credentials entirely, replacing them with <strong>dynamic, short-lived tokens</strong> issued on demand and automatically expired. <strong>HashiCorp Vault</strong> and <strong>GitHub OIDC</strong> make this achievable without rewriting your CI/CD pipelines from scratch.</p><p>This guide covers how to design and implement a secrets management architecture that removes hardcoded credentials from your CI/CD workflows permanently.</p><h3>Why Static Secrets Are a Structural Problem</h3><p>Static credentials, long-lived API keys, database passwords, and cloud access keys, have three fundamental weaknesses that secret rotation and better storage cannot fully address:</p><p><strong>Broad access scope.</strong> A static AWS access key issued to a CI pipeline typically has fixed permissions. Over time, those permissions accumulate as new capabilities are needed and old ones are never revoked, a textbook case of privilege creep.</p><p><strong>Long exposure windows.</strong> A leaked static credential remains valid until it is manually rotated. Discovery of a leak is rarely immediate, the average time to detect a credential compromise is measured in days to weeks, during which an attacker has unrestricted access.</p><p><strong>No audit trail per workflow run.</strong> When ten pipeline runs use the same static credential, your cloud provider’s access logs show ten identical requests from the same key, making it impossible to attribute access to a specific pipeline, branch, or commit.</p><p>Dynamic secrets solve all three: each pipeline run gets a unique, scoped, time-limited credential, automatically expired when the job completes.</p><h3>The Architecture: GitHub OIDC + HashiCorp Vault</h3><p>The zero-static-credentials architecture has two components working in concert:</p><p><strong>GitHub OIDC (OpenID Connect):</strong> GitHub Actions can generate a signed JWT token, an OIDC token, that cryptographically proves the identity of the workflow that requested it. This token includes claims about the repository, branch, environment, and workflow that generated it. Critically, it requires no pre-shared secret to verify, Vault validates it directly against GitHub’s public JWKS endpoint.</p><p><strong>HashiCorp Vault:</strong> Vault receives the OIDC token from the GitHub Actions runner, validates it, maps it to a role with defined permissions, and issues a short-lived Vault token in return. The pipeline then uses that Vault token to fetch exactly the secrets it needs, no more, no less.</p><p>The request flow looks like this:</p><pre>GitHub Actions Runner<br>        │<br>        │ 1. Request OIDC JWT from GitHub<br>        ▼<br>GitHub OIDC Provider<br>        │<br>        │ 2. Returns signed JWT (claims: repo, branch, workflow, environment)<br>        ▼<br>GitHub Actions Runner<br>        │<br>        │ 3. Exchange JWT for Vault token (POST /auth/jwt/login)<br>        ▼<br>HashiCorp Vault<br>        │<br>        │ 4. Validate JWT against GitHub JWKS, map to role, issue Vault token<br>        ▼<br>GitHub Actions Runner<br>        │<br>        │ 5. Use Vault token to read secrets (GET /secret/data/...)<br>        ▼<br>HashiCorp Vault<br>        │<br>        │ 6. Return scoped, time-limited secret<br>        ▼<br>GitHub Actions Runner<br>        │<br>        │ 7. Use secret in pipeline step (expires when job completes)<br>        ▼<br>     Pipeline Step</pre><p>No hardcoded credential appears anywhere in this flow. The GitHub runner never holds a long-lived secret, only a short-lived Vault token scoped to the secrets needed for that specific job.</p><h3>Step 1 — Configure Vault JWT Authentication</h3><p>Enable and configure the JWT authentication backend in Vault to trust GitHub’s OIDC provider:</p><pre># Enable JWT auth backend<br>vault auth enable jwt<br><br># Configure GitHub as the trusted OIDC provider<br>vault write auth/jwt/config \<br>  oidc_discovery_url=&quot;https://token.actions.githubusercontent.com&quot; \<br>  bound_issuer=&quot;https://token.actions.githubusercontent.com&quot;</pre><p>Vault will automatically fetch and cache GitHub’s public keys from the discovery URL, no manual key management required.</p><h3>Step 2 — Create Vault Policies</h3><p>Vault policies define what secrets a role can access. Apply the <strong>principle of least privilege</strong>, each role gets access only to the secrets its corresponding workflow actually needs:</p><pre># vault/policies/orders-service-deploy.hcl<br>path &quot;secret/data/production/orders-service/*&quot; {<br>  capabilities = [&quot;read&quot;]<br>}<br><br>path &quot;secret/data/production/shared/database&quot; {<br>  capabilities = [&quot;read&quot;]<br>}<br><br># Explicitly deny access to other services&#39; secrets<br>path &quot;secret/data/production/payments-service/*&quot; {<br>  capabilities = [&quot;deny&quot;]<br>}</pre><pre># vault/policies/terraform-plan.hcl<br># Read-only access to infrastructure credentials for planning<br>path &quot;aws/creds/terraform-plan-role&quot; {<br>  capabilities = [&quot;read&quot;]<br>}</pre><pre># Apply policies to Vault<br>vault policy write orders-service-deploy vault/policies/orders-service-deploy.hcl<br>vault policy write terraform-plan vault/policies/terraform-plan.hcl</pre><h3>Step 3 — Create Vault Roles Bound to GitHub Claims</h3><p>Vault roles map GitHub OIDC token claims to Vault policies. This is where you define <em>which</em> GitHub workflows can access <em>which</em> secrets, using the claims in the OIDC token as the binding condition:</p><pre># Role for deploying orders-service from the main branch only<br>vault write auth/jwt/role/orders-service-deploy \<br>  role_type=&quot;jwt&quot; \<br>  bound_audiences=&quot;https://github.com/your-org&quot; \<br>  bound_claims_type=&quot;glob&quot; \<br>  bound_claims=&#39;{<br>    &quot;repository&quot;: &quot;your-org/orders-service&quot;,<br>    &quot;ref&quot;: &quot;refs/heads/main&quot;,<br>    &quot;environment&quot;: &quot;production&quot;<br>  }&#39; \<br>  user_claim=&quot;actor&quot; \<br>  policies=&quot;orders-service-deploy&quot; \<br>  ttl=&quot;15m&quot;                           # Vault token expires in 15 minutes</pre><pre># Role for Terraform planning — any branch, read-only AWS credentials<br>vault write auth/jwt/role/terraform-plan \<br>  role_type=&quot;jwt&quot; \<br>  bound_audiences=&quot;https://github.com/your-org&quot; \<br>  bound_claims=&#39;{<br>    &quot;repository&quot;: &quot;your-org/infrastructure&quot;,<br>    &quot;workflow&quot;: &quot;.github/workflows/terraform-plan.yml&quot;<br>  }&#39; \<br>  user_claim=&quot;actor&quot; \<br>  policies=&quot;terraform-plan&quot; \<br>  ttl=&quot;30m&quot;</pre><p>The bound_claims binding is the critical security control. A workflow from your-org/payments-service requesting the orders-service-deploy role will be rejected, even if it has a valid GitHub OIDC token, because the repository claim doesn&#39;t match.</p><h3>Step 4 — Configure GitHub Actions Workflows</h3><p>With Vault configured, update your GitHub Actions workflows to fetch secrets dynamically:</p><pre># .github/workflows/deploy-orders-service.yml<br>name: Deploy Orders Service<br><br>on:<br>  push:<br>    branches: [main]<br><br>permissions:<br>  id-token: write    # required to request GitHub OIDC token<br>  contents: read<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    environment: production  # must match Vault role&#39;s bound_claims<br><br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Authenticate to Vault via GitHub OIDC<br>        uses: hashicorp/vault-action@v3<br>        id: vault<br>        with:<br>          url: ${{ secrets.VAULT_ADDR }}<br>          method: jwt<br>          role: orders-service-deploy<br>          secrets: |<br>            secret/data/production/orders-service/database  DB_PASSWORD | DATABASE_PASSWORD ;<br>            secret/data/production/orders-service/database  DB_HOST     | DATABASE_HOST ;<br>            secret/data/production/shared/stripe            API_KEY     | STRIPE_API_KEY ;<br><br>      - name: Run database migrations<br>        run: npm run migration:run<br>        env:<br>          DATABASE_URL: postgresql://${{ env.DATABASE_HOST }}:5432/orders?password=${{ env.DATABASE_PASSWORD }}<br><br>      - name: Deploy to Kubernetes<br>        run: kubectl apply -f k8s/<br>        env:<br>          STRIPE_API_KEY: ${{ env.STRIPE_API_KEY }}</pre><p>The hashicorp/vault-action step handles the full OIDC exchange automatically, requesting the GitHub token, authenticating to Vault, and injecting the fetched secrets as environment variables for subsequent steps. The secrets are <strong>masked in logs</strong> and <strong>scoped to the job</strong>, they do not persist beyond the workflow run.</p><h3>Step 5 — Dynamic Database Credentials with Vault</h3><p>For databases, Vault can go further than storing static passwords, it can <strong>generate unique, short-lived database credentials</strong> for each pipeline run using the Vault database secrets engine:</p><pre># Enable the database secrets engine<br>vault secrets enable database<br><br># Configure the PostgreSQL connection<br>vault write database/config/orders-db \<br>  plugin_name=postgresql-database-plugin \<br>  allowed_roles=&quot;orders-service-ci&quot; \<br>  connection_url=&quot;postgresql://{{username}}:{{password}}@db.internal:5432/orders&quot; \<br>  username=&quot;vault-admin&quot; \<br>  password=&quot;$DB_ADMIN_PASSWORD&quot;<br><br># Define a role that generates credentials on demand<br>vault write database/roles/orders-service-ci \<br>  db_name=&quot;orders-db&quot; \<br>  creation_statements=&quot;CREATE ROLE \&quot;{{name}}\&quot; WITH LOGIN PASSWORD &#39;{{password}}&#39; VALID UNTIL &#39;{{expiration}}&#39;;<br>    GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO \&quot;{{name}}\&quot;;&quot; \<br>  revocation_statements=&quot;DROP ROLE IF EXISTS \&quot;{{name}}\&quot;;&quot; \<br>  default_ttl=&quot;30m&quot; \<br>  max_ttl=&quot;1h&quot;</pre><p>Now update the Vault policy to allow reading dynamic credentials:</p><pre># vault/policies/orders-service-ci.hcl<br>path &quot;database/creds/orders-service-ci&quot; {<br>  capabilities = [&quot;read&quot;]<br>}</pre><p>Each CI pipeline run that requests database credentials receives a <strong>unique PostgreSQL role</strong>, created just for that run and automatically dropped when the TTL expires. No two pipeline runs share credentials. A leaked credential from a pipeline run is valid for a maximum of 30 minutes and grants access only to the tables that role needs.</p><h3>Step 6 — Auditing and Monitoring</h3><p>Every Vault operation generates an audit log entry. Enable the file audit backend and ship logs to your SIEM:</p><pre># Enable Vault audit logging<br>vault audit enable file file_path=/var/log/vault/audit.log</pre><p>Each entry records the requesting token, the path accessed, the timestamp, and the response status, giving you a complete, tamper-evident trail of every secret access across all pipeline runs.</p><p>Alert on these patterns in your log aggregator:</p><ul><li>Any access to secret/data/production/* outside of expected workflow hours</li><li>Failed authentication attempts against Vault JWT roles</li><li>Policy violations (denied path access attempts)</li><li>Unusually high secret read volume from a single token</li></ul><h3>Step 7 — Migrating from GitHub Repository Secrets</h3><p>Migrating an existing CI/CD system from static GitHub repository secrets to Vault is a multi-step process. Approach it incrementally:</p><p><strong>Phase 1 — Audit existing secrets.</strong> Inventory every secret in your GitHub organization’s repository and environment settings. Classify each by service, sensitivity, and which workflows consume it.</p><p><strong>Phase 2 — Replicate in Vault.</strong> Write all existing static secrets to Vault under a structured path hierarchy (secret/data/{environment}/{service}/{name}).</p><p><strong>Phase 3 — Migrate non-critical workflows first.</strong> Start with staging and development workflows, lower risk, full learning opportunity. Validate that secret fetching works correctly before touching production.</p><p><strong>Phase 4 — Migrate production workflows.</strong> Roll out Vault integration to production workflows one service at a time, with a rollback plan for each.</p><p><strong>Phase 5 — Retire static secrets.</strong> Once all workflows are migrated and validated, delete the corresponding GitHub repository secrets. Validate that no workflow fails. Revoke access for any remaining long-lived credentials that were part of the old system.</p><h3>Common Pitfalls to Avoid</h3><p><strong>Overly permissive Vault policies.</strong> Granting secret/data/production/* with [&quot;read&quot;] to a deployment role means that role can read every production secret, not just the ones it needs. Always scope policies to specific paths.</p><p><strong>Skipping the </strong><strong>environment claim binding.</strong> Without binding roles to a specific GitHub environment, any workflow in your repository could request production secrets. Always require the environment claim for production roles and protect GitHub environments with required reviewers.</p><p><strong>Not setting TTLs.</strong> A Vault token without a TTL is effectively a long-lived credential, defeating the purpose of the architecture. Always set ttl and max_ttl on roles.</p><p><strong>Logging secret values.</strong> The vault-action step masks secrets in GitHub Actions logs, but custom scripts that echo environment variables will expose them. Audit every workflow step that uses fetched secrets.</p><h3>Conclusion</h3><p>Hardcoded credentials are a solved problem, not by better storage of static secrets, but by eliminating the need for static secrets entirely. The combination of <strong>GitHub OIDC</strong> for cryptographic workflow identity and <strong>HashiCorp Vault</strong> for dynamic, scoped, time-limited secret issuance removes the structural weaknesses of static credentials at their root.</p><p>Every CI/CD pipeline that runs with this architecture gets credentials that are unique to that run, scoped to exactly what it needs, and automatically expired when the job completes. A leaked credential compromises a single pipeline run, not your entire production environment.</p><p>The migration requires upfront investment. But so does recovering from a credential compromise. The difference is that the migration is planned, controlled, and bounded, and the recovery rarely is.</p><p><em>Running workloads on AWS or GCP instead of relying on Vault for cloud credentials? AWS IAM Roles for GitHub Actions and GCP Workload Identity Federation follow the same OIDC pattern, no Vault required for cloud-native secrets.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf89d0beee14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero-trust React: defending against 2026’s AI-powered phishing attacks]]></title>
            <link>https://actocodes.medium.com/zero-trust-react-defending-against-2026s-ai-powered-phishing-attacks-6f36fd29a6b8?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f36fd29a6b8</guid>
            <category><![CDATA[react-security]]></category>
            <category><![CDATA[zero-trust]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[frontenddev]]></category>
            <category><![CDATA[phishing-protection]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-06-07T17:01:01.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Phishing has graduated from clumsy grammar mistakes and suspicious domains to fully automated, AI-synthesized campaigns that clone your login UI pixel-for-pixel, intercept OAuth flows mid-flight, and exfiltrate session tokens before your monitoring pipeline fires its first alert. By mid-2026, the attack surface has expanded dramatically, large language models generate convincing spear-phishing lures at scale, adversarial browser extensions manipulate React’s virtual DOM, and compromised npm packages inject silent keyloggers into your production bundle.</p><p>The perimeter-based security model, “everything inside our domain is trusted”, is dead. Zero-trust architecture, for a long time, a backend and network-layer concern, must now be applied all the way to the browser. This article walks through a concrete zero-trust frontend model for React applications, maps it against the most prevalent 2026 threat vectors, and gives you production-ready patterns you can ship this sprint.</p><h3>The 2026 phishing threat landscape</h3><h3>AI-synthesized clone attacks</h3><p>Generative vision models can now scrape a login page, reproduce its layout with sub-pixel accuracy, register a homograph domain, and serve the clone from a CDN within minutes. The resulting page passes casual visual inspection and, crucially, passes many automated screenshot-diff detectors because the HTML structure is semantically identical to the original.</p><p><strong>What makes React apps particularly vulnerable:</strong> Client-side rendering delays the fully-painted UI by 200–800ms. Attackers exploit that window to perform a “bait-and-switch”, serving a static pre-rendered clone while quietly redirecting the real fetch calls to their collection server.</p><h3>Adversarial browser extension injection</h3><p>Extensions with broad tabs and scripting permissions can patch window.fetch, override React&#39;s synthetic event system, or redefine Element.prototype.addEventListener before your app boots. A compromised extension installed by a single engineer on a shared staging environment has compromised every credential entered on that machine.</p><h3>Supply-chain poisoning via npm</h3><p>The 2025 polyfill.io successor incidents demonstrated that a single transitive dependency update can silently inject credential-harvesting code into millions of React bundles. Attackers now specifically target packages that process form inputs, validation libraries, date-pickers, rich-text editors, because they sit closest to sensitive user data.</p><h3>Adversarial session token exfiltration</h3><p>Modern phishing no longer needs your password. Stealing a valid session cookie or an OAuth access token is sufficient. Techniques include MITM via malicious service workers, cross-origin XHR abuse through misconfigured CORS, and postMessage eavesdropping on misconfigured micro-frontend shells.</p><h3>Zero-trust principles for the frontend</h3><p>Zero-trust in a React context means applying three core axioms continuously:</p><ol><li><strong>Never trust implicitly.</strong> Treat every script, every iframe, every API response, and every user input as potentially hostile, regardless of origin.</li><li><strong>Verify explicitly.</strong> Authenticate and validate at every boundary: script load, DOM mutation, API call, and user interaction.</li><li><strong>Use least-privilege access.</strong> Grant capabilities only for the duration and scope needed. Revoke eagerly.</li></ol><h3>Practical React patterns</h3><h3>1. Content Security Policy with strict-dynamic</h3><p>A well-crafted CSP is your first and strongest defence. The strict-dynamic keyword removes the need for domain whitelists (which grow stale and get abused) by trusting only scripts explicitly granted a nonce by your server.</p><pre>Content-Security-Policy:<br>  default-src &#39;none&#39;;<br>  script-src &#39;nonce-{SERVER_GENERATED_NONCE}&#39; &#39;strict-dynamic&#39;;<br>  style-src &#39;nonce-{SERVER_GENERATED_NONCE}&#39;;<br>  connect-src https://api.yourdomain.com;<br>  img-src &#39;self&#39; data:;<br>  frame-ancestors &#39;none&#39;;<br>  upgrade-insecure-requests;<br>  report-uri /csp-violations;</pre><p>For React apps using webpack or Vite, the csp-html-webpack-plugin and vite-plugin-csp packages inject nonces automatically at build time. The critical discipline is <strong>never using </strong><strong>&#39;unsafe-inline&#39;</strong>, inline event handlers and style attributes should be refactored into external files or CSS Modules.</p><h3>2. Subresource Integrity for every external asset</h3><p>Any third-party script loaded without SRI (Subresource Integrity) is an unconditional trust grant to that CDN. One compromised CDN edge node silently delivers malicious JavaScript to every visitor.</p><pre>&lt;script<br>  src=&quot;https://cdn.example.com/analytics.js&quot;<br>  integrity=&quot;sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC&quot;<br>  crossorigin=&quot;anonymous&quot;<br>&gt;&lt;/script&gt;</pre><p>In your CI pipeline, generate and pin SRI hashes for all third-party resources at build time. Rotate them on every dependency update. Fail the build if any external resource lacks an integrity attribute.</p><h3>3. Trusted Types API</h3><p>The Trusted Types API, now baseline across all major browsers, eliminates DOM XSS sinks at the platform level. Enabling it means no string can be assigned to innerHTML, outerHTML, document.write, or script src without first passing through a registered policy.</p><pre>// vite.config.js / webpack config — add to CSP header<br>// require-trusted-types-for &#39;script&#39;<br><br>// In your React app bootstrap<br>if (window.trustedTypes &amp;&amp; window.trustedTypes.createPolicy) {<br>  const sanitizePolicy = window.trustedTypes.createPolicy(&#39;sanitize-html&#39;, {<br>    createHTML: (input) =&gt; DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: true }),<br>    createScriptURL: (url) =&gt; {<br>      const allowed = [&#39;https://api.yourdomain.com&#39;];<br>      if (!allowed.some(origin =&gt; url.startsWith(origin))) {<br>        throw new TypeError(`Blocked script URL: ${url}`);<br>      }<br>      return url;<br>    }<br>  });<br>}</pre><p>With Trusted Types enforced, injecting arbitrary HTML via a compromised third-party library throws a TypeError rather than silently executing. Combined with DOMPurify, this eliminates the entire class of XSS-via-React-dangerouslySetInnerHTML vulnerabilities.</p><h3>4. Cookie and token hardening</h3><p>HTTP-only, SameSite=Strict, Secure cookies are table stakes in 2026. What separates resilient apps is <strong>token binding</strong> and <strong>short-lived access tokens with silent refresh</strong>.</p><pre>// Short-lived tokens: 5-minute access token, 24-hour refresh token<br>// Silent refresh in a sandboxed Web Worker — keeps tokens out of the main thread<br><br>// auth.worker.js<br>self.addEventListener(&#39;message&#39;, async (event) =&gt; {<br>  if (event.data.type === &#39;REFRESH_TOKEN&#39;) {<br>    const response = await fetch(&#39;/api/auth/refresh&#39;, {<br>      method: &#39;POST&#39;,<br>      credentials: &#39;include&#39;, // HttpOnly refresh cookie handled by browser<br>    });<br>    const { accessToken, expiresIn } = await response.json();<br>    self.postMessage({ type: &#39;TOKEN_REFRESHED&#39;, accessToken, expiresIn });<br>  }<br>});</pre><p>Moving token refresh logic into a dedicated Web Worker isolates it from the main-thread JavaScript context that extension scripts can patch. The access token is never stored in localStorage, it lives in memory inside the Worker and is passed to fetch interceptors as needed.</p><h3>5. Integrity checks on your own bundle</h3><p>Supply-chain attacks often manifest as subtle mutations to your own production bundle, a minified analytics script with an extra fetch() call. Implement a runtime integrity monitor that hashes critical module exports on boot and compares them to known-good values baked in at build time.</p><pre>// build-time: generate hashes of critical exports<br>// runtime: verify on app boot<br><br>async function verifyBundleIntegrity(expectedHashes) {<br>  for (const [moduleId, expectedHash] of Object.entries(expectedHashes)) {<br>    const moduleSource = getModuleSource(moduleId); // your module registry<br>    const buffer = await crypto.subtle.digest(<br>      &#39;SHA-256&#39;,<br>      new TextEncoder().encode(moduleSource)<br>    );<br>    const actualHash = btoa(String.fromCharCode(...new Uint8Array(buffer)));<br>    if (actualHash !== expectedHash) {<br>      reportViolation({ moduleId, expectedHash, actualHash });<br>      throw new Error(`Bundle integrity violation: ${moduleId}`);<br>    }<br>  }<br>}</pre><h3>6. Sandboxed iframes for third-party widgets</h3><p>Any third-party widget, chat bubbles, payment forms, social embeds, should be isolated in a maximally sandboxed iframe. The allow attribute now supports a fine-grained Permission Policy that can revoke access to the camera, clipboard, and geolocation APIs independently.</p><pre>&lt;iframe<br>  src=&quot;https://widget.trusted-partner.com/chat&quot;<br>  sandbox=&quot;allow-scripts allow-same-origin allow-forms&quot;<br>  allow=&quot;camera &#39;none&#39;; microphone &#39;none&#39;; clipboard-read &#39;none&#39;; geolocation &#39;none&#39;&quot;<br>  referrerpolicy=&quot;no-referrer&quot;<br>  loading=&quot;lazy&quot;<br>&gt;&lt;/iframe&gt;</pre><p>Never grant allow-top-navigation to a third-party iframe, it is sufficient for a compromised widget to redirect the parent window to a phishing page.</p><h3>7. Runtime anomaly detection</h3><p>Ship a lightweight, privacy-preserving behavioural monitor that detects tell-tale phishing indicators at runtime:</p><pre>class FrontendAnomalyDetector {<br>  constructor() {<br>    this.baseline = this.captureBaseline();<br>    this.monitor();<br>  }<br><br>  captureBaseline() {<br>    return {<br>      fetchDescriptor: Object.getOwnPropertyDescriptor(window, &#39;fetch&#39;),<br>      addEventListenerDescriptor: Object.getOwnPropertyDescriptor(<br>        EventTarget.prototype, &#39;addEventListener&#39;<br>      ),<br>      documentReferrer: document.referrer,<br>    };<br>  }<br><br>  monitor() {<br>    // Detect fetch monkey-patching (common in extension-based MitM)<br>    const currentFetch = Object.getOwnPropertyDescriptor(window, &#39;fetch&#39;);<br>    if (currentFetch?.value !== this.baseline.fetchDescriptor?.value) {<br>      this.report(&#39;fetch_tampered&#39;);<br>    }<br><br>    // Detect unexpected referrers (clone-site navigation)<br>    const trustedReferrers = [&#39;https://yourdomain.com&#39;, &#39;&#39;];<br>    if (!trustedReferrers.some(r =&gt; document.referrer.startsWith(r))) {<br>      this.report(&#39;suspicious_referrer&#39;, { referrer: document.referrer });<br>    }<br>  }<br><br>  report(type, meta = {}) {<br>    navigator.sendBeacon(&#39;/api/security/report&#39;, JSON.stringify({ type, meta, ts: Date.now() }));<br>  }<br>}</pre><h3>Zero-trust React: implementation checklist</h3><p>Use this checklist as a PR gate for any authentication or payment-adjacent feature:</p><p><strong>Transport and headers</strong></p><ul><li>Content-Security-Policy with strict-dynamic and per-request nonces, no unsafe-inline</li><li>Strict-Transport-Security with includeSubDomains and preload</li><li>X-Frame-Options: DENY and frame-ancestors &#39;none&#39; in CSP</li><li>Permissions-Policy disabling unused browser APIs</li></ul><p><strong>Scripts and assets</strong></p><ul><li>SRI hashes on every third-party &lt;script&gt; and &lt;link&gt;</li><li>require-trusted-types-for &#39;script&#39; enforced in CSP</li><li>DOMPurify with RETURN_TRUSTED_TYPE on all HTML rendering paths</li><li>No dangerouslySetInnerHTML without an explicit Trusted Types policy</li></ul><p><strong>Authentication</strong></p><ul><li>Access tokens live in memory (Web Worker), never in localStorage</li><li>Refresh tokens in HttpOnly, SameSite=Strict, Secure cookies only</li><li>Access token lifetime ≤ 5 minutes with silent refresh</li><li>PKCE enforced for all OAuth flows</li></ul><p><strong>Third-party and supply chain</strong></p><ul><li>All npm dependencies pinned to exact versions with package-lock.json integrity</li><li>Automated dependency audit in CI (npm audit --audit-level=high)</li><li>Third-party widgets isolated in maximally sandboxed iframes</li><li>Runtime monkey-patch detection for fetch and addEventListener</li></ul><p><strong>Monitoring</strong></p><ul><li>CSP violation reports collected and alerted on in real time</li><li>Behavioural anomaly detector deployed and reporting to SIEM</li><li>Bundle integrity hashes verified on every boot</li></ul><h3>Conclusion</h3><p>The 2026 phishing playbook is sophisticated, automated, and specifically engineered to exploit the trust assumptions baked into most React applications. Defending against it requires treating the browser as an untrusted execution environment, because, from a zero-trust perspective, it is.</p><p>None of the patterns above require exotic infrastructure. CSP nonces, Trusted Types, and Web Worker token isolation are all production-ready today. The real investment is discipline: making these controls non-negotiable in code review, enforcing them in CI, and instrumenting violations so your security team learns from near-misses before they become incidents.</p><p>Apply zero-trust at every layer, network, API, and now frontend, and you transform the browser from your weakest link into an active participant in your defence.</p><p><em>Have a question or a pattern to add? Drop it in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f36fd29a6b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Tracing in NestJS: End-to-End Request Visibility with OpenTelemetry]]></title>
            <link>https://actocodes.medium.com/distributed-tracing-in-nestjs-end-to-end-request-visibility-with-opentelemetry-bf2f4fd93b2b?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf2f4fd93b2b</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 17 May 2026 17:01:00 GMT</pubDate>
            <atom:updated>2026-05-17T17:01:00.713Z</atom:updated>
            <content:encoded><![CDATA[<p>In a monolithic application, debugging a slow or failing request is straightforward, you have one codebase, one log stream, and one execution context to reason about. In a microservices architecture, a single user request can touch a dozen services, three databases, and two external APIs before a response is returned. When something goes wrong, where do you look?</p><p>This is the problem <strong>distributed tracing</strong> solves. By attaching a unique trace identifier to every request and propagating it across every service boundary, distributed tracing gives you a complete, chronological map of exactly what happened, which services were called, in what order, how long each took, and where failures occurred.</p><p><strong>OpenTelemetry</strong> is the open-source observability standard that makes this possible across any language and infrastructure. And <strong>NestJS</strong>, with its modular architecture and middleware system, is exceptionally well-suited for clean OpenTelemetry integration.</p><p>This guide walks through setting up distributed tracing in NestJS from scratch, auto-instrumenting HTTP and database calls, creating custom spans for business logic, propagating context across service boundaries, and visualizing traces in Grafana Tempo.</p><h3>How Distributed Tracing Works</h3><p>Before writing code, it helps to understand the core concepts:</p><ul><li><strong>Trace:</strong> the complete journey of a single request across all services. Identified by a traceId.</li><li><strong>Span:</strong> a single unit of work within a trace (e.g., an HTTP handler, a database query, an external API call). Each span has a start time, duration, and status.</li><li><strong>Context Propagation:</strong> the mechanism by which trace and span identifiers are passed between services, typically via HTTP headers (traceparent).</li><li><strong>Exporter:</strong> the component that sends collected spans to a backend (Tempo, Jaeger, Zipkin, Datadog).</li></ul><p>A fully traced request looks like this:</p><pre>Trace: usr_checkout_8f3a2c<br>├── [0ms]   API Gateway          → POST /checkout            (12ms)<br>├── [12ms]  orders-service       → createOrder()             (45ms)<br>│   ├── [14ms]  PostgreSQL       → INSERT orders             (18ms)<br>│   └── [33ms]  payments-service → chargeCard()              (24ms)<br>│       └── [35ms]  Stripe API   → POST /charges             (21ms)<br>└── [57ms]  notifications-service → sendConfirmation()       (8ms)</pre><p>Every box is a span. Every span shares the same traceId. The entire tree is the trace.</p><h3>Step 1 — Install OpenTelemetry Packages</h3><p>NestJS’s OpenTelemetry setup requires the core SDK plus instrumentation libraries for Node.js HTTP, Express (which NestJS runs on), and any databases or HTTP clients your services use:</p><pre>npm install \<br>  @opentelemetry/sdk-node \<br>  @opentelemetry/auto-instrumentations-node \<br>  @opentelemetry/exporter-trace-otlp-http \<br>  @opentelemetry/resources \<br>  @opentelemetry/semantic-conventions \<br>  @opentelemetry/api</pre><h3>Step 2 — Create the Tracing Bootstrap File</h3><p>OpenTelemetry <strong>must</strong> be initialized before any other application code, before NestJS bootstraps, before TypeORM connects, before any modules load. Create a dedicated file for this:</p><pre>// src/tracing.ts<br>import { NodeSDK } from &#39;@opentelemetry/sdk-node&#39;;<br>import { getNodeAutoInstrumentations } from &#39;@opentelemetry/auto-instrumentations-node&#39;;<br>import { OTLPTraceExporter } from &#39;@opentelemetry/exporter-trace-otlp-http&#39;;<br>import { Resource } from &#39;@opentelemetry/resources&#39;;<br>import { SEMRESATTRS_SERVICE_NAME, SEMRESATTRS_SERVICE_VERSION, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT } from &#39;@opentelemetry/semantic-conventions&#39;;<br><br>const exporter = new OTLPTraceExporter({<br>  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? &#39;http://localhost:4318/v1/traces&#39;,<br>});<br><br>const sdk = new NodeSDK({<br>  resource: new Resource({<br>    [SEMRESATTRS_SERVICE_NAME]: process.env.SERVICE_NAME ?? &#39;unknown-service&#39;,<br>    [SEMRESATTRS_SERVICE_VERSION]: process.env.APP_VERSION ?? &#39;1.0.0&#39;,<br>    [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV ?? &#39;development&#39;,<br>  }),<br>  traceExporter: exporter,<br>  instrumentations: [<br>    getNodeAutoInstrumentations({<br>      &#39;@opentelemetry/instrumentation-http&#39;: { enabled: true },<br>      &#39;@opentelemetry/instrumentation-express&#39;: { enabled: true },<br>      &#39;@opentelemetry/instrumentation-pg&#39;: { enabled: true },      // PostgreSQL<br>      &#39;@opentelemetry/instrumentation-redis&#39;: { enabled: true },   // Redis<br>      &#39;@opentelemetry/instrumentation-dns&#39;: { enabled: false },    // too noisy<br>      &#39;@opentelemetry/instrumentation-fs&#39;: { enabled: false },     // too noisy<br>    }),<br>  ],<br>});<br><br>sdk.start();<br><br>process.on(&#39;SIGTERM&#39;, () =&gt; {<br>  sdk.shutdown().finally(() =&gt; process.exit(0));<br>});</pre><p>Then import it as the very first line of your entry point:</p><pre>// src/main.ts<br>import &#39;./tracing&#39;;  // ← must be first, before all other imports<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>With this in place, every inbound HTTP request, outbound HTTP call, and PostgreSQL query is automatically traced, zero additional code required in your controllers or services.</p><h3>Step 3 — Adding Custom Spans for Business Logic</h3><p>Auto-instrumentation covers infrastructure-level operations. <strong>Custom spans</strong> capture business logic that matters to your domain, the operations auto-instrumentation doesn’t know about:</p><pre>// src/orders/orders.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { trace, SpanStatusCode, context } from &#39;@opentelemetry/api&#39;;<br><br>const tracer = trace.getTracer(&#39;orders-service&#39;);<br><br>@Injectable()<br>export class OrdersService {<br><br>  async createOrder(dto: CreateOrderDto): Promise&lt;Order&gt; {<br>    return tracer.startActiveSpan(&#39;orders.createOrder&#39;, async (span) =&gt; {<br>      try {<br>        // Add semantic attributes to the span<br>        span.setAttributes({<br>          &#39;order.customerId&#39;: dto.customerId,<br>          &#39;order.itemCount&#39;: dto.items.length,<br>          &#39;order.currency&#39;: dto.currency,<br>        });<br><br>        const order = await this.processOrder(dto);<br><br>        span.setAttributes({ &#39;order.id&#39;: order.id });<br>        span.setStatus({ code: SpanStatusCode.OK });<br><br>        return order;<br>      } catch (error) {<br>        span.setStatus({<br>          code: SpanStatusCode.ERROR,<br>          message: error instanceof Error ? error.message : &#39;Unknown error&#39;,<br>        });<br>        span.recordException(error as Error);<br>        throw error;<br>      } finally {<br>        span.end(); // always end the span<br>      }<br>    });<br>  }<br><br>  private async processOrder(dto: CreateOrderDto): Promise&lt;Order&gt; {<br>    return tracer.startActiveSpan(&#39;orders.processOrder&#39;, async (span) =&gt; {<br>      try {<br>        // Nested span — appears as a child in the trace tree<br>        const inventory = await this.checkInventory(dto.items);<br>        span.addEvent(&#39;inventory.checked&#39;, { available: inventory.allAvailable });<br><br>        const order = await this.orderRepo.create(dto);<br>        span.addEvent(&#39;order.persisted&#39;, { orderId: order.id });<br><br>        return order;<br>      } finally {<br>        span.end();<br>      }<br>    });<br>  }<br>}</pre><p>Key practices for custom spans:</p><ul><li><strong>Always call </strong><strong>span.end(),</strong> an unclosed span leaks memory and never exports. Use try/finally to guarantee it.</li><li><strong>Use semantic attribute names.</strong> Prefix with your domain (order., user., payment.) for consistent querying.</li><li><strong>Record exceptions</strong> with span.recordException(), this attaches the full stack trace to the span in Tempo.</li><li><strong>Add events</strong> for significant moments within a span (span.addEvent()), they appear as timestamped annotations on the span timeline.</li></ul><h3>Step 4 — Context Propagation Across Services</h3><p>A trace is only useful if it spans service boundaries. When orders-service calls users-service, the trace context must travel with the request via HTTP headers.</p><p><strong>Good news:</strong> if both services use OpenTelemetry with HTTP auto-instrumentation enabled, context propagation happens automatically. The outbound HTTP call from orders-service injects traceparent and tracestate headers, and users-service extracts them, linking the spans into the same trace tree.</p><p>For manual HTTP clients (e.g., Axios without auto-instrumentation), inject headers explicitly:</p><pre>import { propagation, context } from &#39;@opentelemetry/api&#39;;<br>import axios from &#39;axios&#39;;<br><br>async function callUsersService(userId: string) {<br>  const headers: Record&lt;string, string&gt; = {};<br><br>  // Inject current trace context into headers<br>  propagation.inject(context.active(), headers);<br><br>  const response = await axios.get(`${USERS_SERVICE_URL}/users/${userId}`, {<br>    headers,<br>  });<br><br>  return response.data;<br>}</pre><p>For <strong>NestJS microservices</strong> using TCP or message brokers (NATS, RabbitMQ, Kafka), inject trace context into the message payload or metadata:</p><pre>// Injecting context into a NestJS microservice message<br>const carrier: Record&lt;string, string&gt; = {};<br>propagation.inject(context.active(), carrier);<br><br>this.client.emit(&#39;order_placed&#39;, {<br>  ...orderPayload,<br>  _traceContext: carrier, // carry trace headers in the message<br>});</pre><p>On the consumer side, extract and activate the context before processing:</p><pre>@EventPattern(&#39;order_placed&#39;)<br>async handleOrderPlaced(data: OrderPlacedEvent) {<br>  const parentContext = propagation.extract(context.active(), data._traceContext ?? {});<br><br>  await context.with(parentContext, async () =&gt; {<br>    // All spans created here are children of the originating trace<br>    await this.processOrder(data);<br>  });<br>}</pre><h3>Step 5 — Trace-Log Correlation</h3><p>Distributed tracing and structured logging are most powerful when correlated. By injecting the current traceId and spanId into every log entry, you can jump from a log line directly to the corresponding trace in Tempo, and vice versa.</p><pre>// src/common/middleware/trace-context.middleware.ts<br>import { Injectable, NestMiddleware } from &#39;@nestjs/common&#39;;<br>import { Request, Response, NextFunction } from &#39;express&#39;;<br>import { trace, context } from &#39;@opentelemetry/api&#39;;<br>import { PinoLogger } from &#39;nestjs-pino&#39;;<br><br>@Injectable()<br>export class TraceContextMiddleware implements NestMiddleware {<br>  constructor(private readonly logger: PinoLogger) {}<br><br>  use(req: Request, res: Response, next: NextFunction) {<br>    const span = trace.getActiveSpan();<br>    const spanContext = span?.spanContext();<br><br>    if (spanContext) {<br>      // Pino&#39;s child logger binds these fields to every subsequent log in the request<br>      this.logger.assign({<br>        traceId: spanContext.traceId,<br>        spanId: spanContext.spanId,<br>        traceFlags: spanContext.traceFlags,<br>      });<br>    }<br><br>    next();<br>  }<br>}</pre><p>In Grafana, this enables <strong>Loki-to-Tempo linking</strong>, click a traceId in a Loki log query and jump directly to the full distributed trace in Tempo. This is the observability trifecta, logs, traces, and metrics unified in a single investigation workflow.</p><h3>Step 6 — Visualizing Traces in Grafana Tempo</h3><p><strong>Grafana Tempo</strong> is the recommended trace backend for teams already on the Grafana stack (and pairs naturally with Grafana Faro for frontend-to-backend tracing, as covered in the previous article).</p><p>Send spans to Tempo via the OpenTelemetry Collector:</p><pre># otel-collector-config.yaml<br>receivers:<br>  otlp:<br>    protocols:<br>      http:<br>        endpoint: 0.0.0.0:4318<br>      grpc:<br>        endpoint: 0.0.0.0:4317<br><br>exporters:<br>  otlp:<br>    endpoint: tempo:4317<br>    tls:<br>      insecure: true<br><br>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      exporters: [otlp]</pre><p>Once traces are flowing into Tempo, configure Grafana dashboards to:</p><ul><li><strong>Search traces</strong> by service name, operation name, duration, and status</li><li><strong>View flame graphs</strong> showing the time breakdown of every span in a trace</li><li><strong>Set alerts</strong> on p95/p99 latency for critical operations</li><li><strong>Link traces to logs</strong> via traceId in Loki datasource configuration</li></ul><h3>Step 7 — CI/CD and Environment Configuration</h3><p>Manage OpenTelemetry configuration via environment variables, the standard supported by all OTEL SDKs:</p><pre># .env.production<br>SERVICE_NAME=orders-service<br>APP_VERSION=2.4.1<br>NODE_ENV=production<br>OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318/v1/traces<br>OTEL_TRACES_SAMPLER=parentbased_traceidratio<br>OTEL_TRACES_SAMPLER_ARG=0.1   # sample 10% of traces in production</pre><p>Sampling is critical in production. Tracing 100% of requests at scale generates enormous volume and cost. Use <strong>parent-based ratio sampling,</strong> if the upstream service sampled the request, all downstream services honor that decision, keeping traces complete while reducing overall volume.</p><h3>Common Pitfalls to Avoid</h3><p><strong>Initializing OpenTelemetry after NestJS bootstraps:</strong> If tracing.ts is not the first import in main.ts, auto-instrumentation patches won&#39;t apply to already-loaded modules. The SDK must load before any instrumented libraries.</p><p><strong>Forgetting </strong><strong>span.end():</strong> Every span that isn&#39;t explicitly ended leaks memory and never exports. Always use try/finally blocks around custom spans.</p><p><strong>Over-instrumenting:</strong> Not every function needs a custom span. Focus on operations with meaningful duration variance, external calls, database queries, and complex business logic. Instrumenting trivial utility functions adds noise without insight.</p><p><strong>Ignoring sampling in production:</strong> Tracing 100% of requests is expensive. Configure ratio-based sampling early, retrofitting it later requires changes across every service.</p><p><strong>Not propagating context through message brokers:</strong> Context propagation via HTTP headers is automatic, but message broker propagation requires manual injection and extraction. Skipping it breaks the trace tree at every async boundary.</p><h3>Conclusion</h3><p>Distributed tracing with <strong>OpenTelemetry</strong> and <strong>NestJS</strong> transforms debugging in microservices from guesswork into a precise, evidence-based workflow. A single traceId gives you the complete story of any request, every service it touched, every database query it triggered, every external call it made, and exactly where time was spent or errors occurred.</p><p>Set up auto-instrumentation first for immediate value with zero code changes, layer in custom spans for your critical business operations, enforce context propagation across all service boundaries, and correlate traces with your structured logs. Combined with Grafana Faro for frontend traces, you achieve the observability holy grail: end-to-end request visibility from the user’s click to the database and back.</p><p><em>Running NestJS microservices on Kubernetes? OpenTelemetry’s Kubernetes operator can inject the collector as a sidecar automatically, no per-pod configuration required. More on that in a future post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf2f4fd93b2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Observability with Grafana Faro: Real User Monitoring for Production Web Apps]]></title>
            <link>https://actocodes.medium.com/frontend-observability-with-grafana-faro-real-user-monitoring-for-production-web-apps-a6e4eb88f44b?source=rss-8ce15fc09a3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6e4eb88f44b</guid>
            <category><![CDATA[real-user-monitoring]]></category>
            <category><![CDATA[frontendobservability]]></category>
            <category><![CDATA[grafana-faro]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[ThankGod Chibugwum Obobo]]></dc:creator>
            <pubDate>Sun, 10 May 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-05-10T17:01:02.980Z</atom:updated>
            <content:encoded><![CDATA[<p>Backend observability is a solved problem for most mature engineering teams. Structured logs, distributed traces, and metrics dashboards are standard practice. But the moment a user opens your web app, you lose visibility. JavaScript exceptions, slow renders, failed API calls, and broken user flows happen entirely in the browser, invisible to your backend monitoring stack.</p><p><strong>Frontend observability</strong> closes this gap. And <strong>Grafana Faro</strong> is one of the most capable open-source tools for doing it. Purpose-built to collect Real User Monitoring (RUM) data, JavaScript errors, performance metrics, and custom events directly from the browser, and feed them into the same Grafana stack your backend already uses.</p><p>This guide covers what Grafana Faro is, how to set it up in a React application, what to instrument, and how to connect frontend signals to your existing Grafana Cloud dashboards for end-to-end observability.</p><h3>What Is Frontend Observability?</h3><p>Frontend observability is the practice of collecting, correlating, and analyzing signals from real users’ browsers in production. It covers four primary signal types:</p><p>SignalWhat It Captures<strong>Errors</strong>JavaScript exceptions, unhandled promise rejections, network errors<strong>Performance</strong>Core Web Vitals, page load times, resource timing, long tasks<strong>Traces</strong>User session flows, distributed traces linking frontend calls to backend spans<strong>Logs</strong>Custom application events, user interactions, feature flag evaluations</p><p>Traditional Application Performance Monitoring (APM) tools cover backend services. Real User Monitoring (RUM) covers the actual experience of real users on real devices and networks, capturing variance that synthetic testing in CI simply cannot reproduce.</p><h3>What Is Grafana Faro?</h3><p><strong>Grafana Faro</strong> is an open-source Web SDK and collector designed specifically for frontend observability. Released by Grafana Labs, it integrates natively with the broader Grafana observability stack:</p><ul><li><strong>Grafana Faro Web SDK</strong> — the browser-side agent that collects signals</li><li><strong>Grafana Agent / Faro Collector</strong> — receives signals from the browser and forwards them to Grafana Cloud</li><li><strong>Grafana Cloud</strong> — stores and visualizes the data in Loki (logs), Tempo (traces), and Prometheus (metrics)</li></ul><p>The key advantage over standalone RUM tools like Sentry or Datadog RUM is <strong>unified observability</strong>, a single frontend error in Faro can be correlated with the corresponding backend trace in Tempo, giving you a complete picture of what the user experienced and why.</p><h3>Step 1 — Installation and Basic Setup</h3><p>Install the Faro Web SDK:</p><pre>npm install @grafana/faro-web-sdk @grafana/faro-web-tracing</pre><p>Initialize Faro as early as possible in your application, before any other imports, to capture errors that occur during startup:</p><pre>// src/instrumentation.ts  ← import this first in main.tsx/index.tsx<br>import { initializeFaro, getWebInstrumentations } from &#39;@grafana/faro-web-sdk&#39;;<br>import { TracingInstrumentation } from &#39;@grafana/faro-web-tracing&#39;;<br><br>export const faro = initializeFaro({<br>  url: process.env.VITE_FARO_COLLECTOR_URL!, // your Grafana Agent endpoint<br>  app: {<br>    name: &#39;my-web-app&#39;,<br>    version: process.env.VITE_APP_VERSION ?? &#39;1.0.0&#39;,<br>    environment: process.env.NODE_ENV,<br>  },<br>  instrumentations: [<br>    ...getWebInstrumentations({<br>      captureConsole: true,          // capture console.error and console.warn<br>      captureConsoleDisabledLevels: [&#39;log&#39;, &#39;debug&#39;], // skip noisy levels<br>    }),<br>    new TracingInstrumentation(),    // distributed tracing for fetch/XHR<br>  ],<br>});</pre><p>Then in your entry point:</p><pre>// src/main.tsx<br>import &#39;./instrumentation&#39;;         // must be first<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(&lt;App /&gt;);</pre><p>With this alone, Faro will automatically collect:</p><ul><li>Unhandled JavaScript errors and promise rejections</li><li>Browser console errors and warnings</li><li>Core Web Vitals (LCP, CLS, INP)</li><li>Navigation and resource timing</li><li>Distributed trace headers on all fetch and XHR requests</li></ul><h3>Step 2 — Setting Up the Grafana Agent Collector</h3><p>The Faro SDK sends signals to a <strong>collector endpoint</strong>, not directly to Grafana Cloud. The collector receives, batches, and forwards signals to the appropriate backends.</p><p>For local development, run the Grafana Agent via Docker:</p><pre># docker-compose.yml<br>services:<br>  grafana-agent:<br>    image: grafana/agent:latest<br>    ports:<br>      - &quot;12347:12347&quot;   # Faro receiver port<br>    volumes:<br>      - ./grafana-agent.yaml:/etc/agent/agent.yaml<br>    command: -config.file=/etc/agent/agent.yaml</pre><p>Configure the agent to receive Faro signals and forward to Grafana Cloud:</p><pre># grafana-agent.yaml<br>faro:<br>  server:<br>    listen_address: 0.0.0.0:12347<br>    cors_allowed_origins:<br>      - &quot;http://localhost:5173&quot;<br>      - &quot;https://your-production-domain.com&quot;<br><br>logs:<br>  configs:<br>    - name: faro-logs<br>      clients:<br>        - url: https://logs-prod-eu-west-0.grafana.net/loki/api/v1/push<br>          basic_auth:<br>            username: YOUR_GRAFANA_CLOUD_USER_ID<br>            password: YOUR_GRAFANA_CLOUD_API_KEY<br><br>traces:<br>  configs:<br>    - name: faro-traces<br>      receivers:<br>        otlp:<br>          protocols:<br>            grpc:<br>      remote_write:<br>        - endpoint: tempo-prod-eu-west-0.grafana.net:443<br>          basic_auth:<br>            username: YOUR_TEMPO_USER_ID<br>            password: YOUR_GRAFANA_CLOUD_API_KEY</pre><p>Store all credentials as environment variables or secrets, never hardcode them in configuration files committed to version control.</p><h3>Step 3 — Identifying Users and Sessions</h3><p>Raw error logs are difficult to act on without user context. Attach user identity and session metadata to every Faro signal:</p><pre>// After user authentication succeeds<br>import { faro } from &#39;./instrumentation&#39;;<br><br>function onUserAuthenticated(user: { id: string; email: string; plan: string }) {<br>  faro.api.setUser({<br>    id: user.id,<br>    email: user.email,          // only if your privacy policy permits<br>    attributes: {<br>      plan: user.plan,<br>      region: user.region,<br>    },<br>  });<br>}<br><br>function onUserLoggedOut() {<br>  faro.api.resetUser();<br>}</pre><p>Faro automatically generates a <strong>session ID</strong> per browser session. Combined with the user ID, you can reconstruct the complete sequence of events that led to an error, page navigations, API calls, user interactions, all directly in Grafana.</p><h3>Step 4 — Custom Events and Manual Instrumentation</h3><p>Automatic instrumentation captures infrastructure-level signals. <strong>Custom events</strong> capture business-level signals, the actions that matter to your product:</p><pre>import { faro } from &#39;./instrumentation&#39;;<br><br>// Track a significant user action<br>function onCheckoutCompleted(orderId: string, total: number) {<br>  faro.api.pushEvent(&#39;checkout_completed&#39;, {<br>    orderId,<br>    total: total.toString(),<br>    currency: &#39;USD&#39;,<br>  });<br>}<br><br>// Track feature flag evaluations<br>function onFeatureFlagEvaluated(flagKey: string, value: boolean) {<br>  faro.api.pushEvent(&#39;feature_flag_evaluated&#39;, {<br>    flagKey,<br>    value: value.toString(),<br>  });<br>}<br><br>// Push a custom log entry<br>function onPaymentRetry(attempt: number, reason: string) {<br>  faro.api.pushLog([`Payment retry attempt ${attempt}: ${reason}`], {<br>    level: LogLevel.WARN,<br>    context: { attempt: attempt.toString(), reason },<br>  });<br>}</pre><p>Custom events are queryable in Grafana Loki using LogQL, you can build dashboards showing checkout conversion rates, feature flag adoption, or payment retry frequency directly from frontend signals.</p><h3>Step 5 — Error Boundary Integration</h3><p>React’s Error Boundaries catch rendering errors that Faro’s automatic instrumentation misses. Integrate Faro into your error boundary to capture them with full component context:</p><pre>// src/components/ErrorBoundary.tsx<br>import React, { Component, ErrorInfo, ReactNode } from &#39;react&#39;;<br>import { faro } from &#39;../instrumentation&#39;;<br><br>interface Props {<br>  children: ReactNode;<br>  fallback: ReactNode;<br>}<br><br>interface State {<br>  hasError: boolean;<br>}<br><br>export class ErrorBoundary extends Component&lt;Props, State&gt; {<br>  state: State = { hasError: false };<br><br>  static getDerivedStateFromError(): State {<br>    return { hasError: true };<br>  }<br><br>  componentDidCatch(error: Error, info: ErrorInfo) {<br>    faro.api.pushError(error, {<br>      type: &#39;ReactRenderError&#39;,<br>      context: {<br>        componentStack: info.componentStack ?? &#39;&#39;,<br>      },<br>    });<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      return this.props.fallback;<br>    }<br>    return this.props.children;<br>  }<br>}</pre><p>Wrap critical sections of your UI dashboards, checkout flows, data-heavy views, with dedicated error boundaries so rendering failures are captured with component stack context, not just as generic JavaScript errors.</p><h3>Step 6 — Distributed Tracing: Connecting Frontend to Backend</h3><p>The most powerful feature of Grafana Faro is <strong>distributed tracing</strong>. When TracingInstrumentation is enabled, Faro automatically injects OpenTelemetry trace headers (traceparent) into every fetch and XMLHttpRequest call.</p><p>If your backend is also instrumented with OpenTelemetry, the frontend and backend spans are linked. A single user action that triggers an API call produces a trace that spans both the browser and the server.</p><p>To ensure your backend accepts and propagates these headers, configure CORS to allow traceparent and tracestate:</p><pre>// NestJS main.ts<br>app.enableCors({<br>  origin: process.env.FRONTEND_URL,<br>  allowedHeaders: [&#39;Content-Type&#39;, &#39;Authorization&#39;, &#39;traceparent&#39;, &#39;tracestate&#39;],<br>});</pre><p>In Grafana Tempo, you can then view a single trace that shows the full lifecycle of a user request: the browser fetch initiating at 0ms, the API gateway receiving at 12ms, the database query completing at 45ms, and the response rendering in the browser at 67ms, in one unified view.</p><h3>Step 7 — Performance Monitoring and Core Web Vitals</h3><p>Faro automatically collects <strong>Core Web Vitals</strong>, the metrics Google uses to evaluate page experience:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*S7FJ0MdnTOyNodbqLgs6XA.png" /></figure><p>These metrics are collected from real users across real devices and network conditions, far more representative than Lighthouse scores in CI. Build Grafana dashboards that segment Web Vitals by:</p><ul><li><strong>Device type</strong> (mobile vs. desktop)</li><li><strong>Geographic region</strong></li><li><strong>Page route</strong> (which pages are slowest)</li><li><strong>App version</strong> (did the latest deployment improve or degrade performance?)</li></ul><p>Performance regressions caught by real user data are the ones that actually affect your users, not synthetic benchmarks.</p><h3>Privacy and Data Minimization</h3><p>Frontend observability collects data from real users, which means privacy is non-negotiable:</p><p><strong>Redact PII before it reaches Faro.</strong> Never push user email addresses, payment details, or health data as custom event attributes.</p><p><strong>Respect consent.</strong> Initialize Faro only after the user has accepted analytics cookies if your jurisdiction requires it (GDPR, CCPA).</p><p><strong>Configure sampling rates.</strong> For high-traffic applications, collecting 100% of traces is unnecessary and costly. Configure Faro to sample a representative percentage:</p><pre>initializeFaro({<br>  // ...<br>  sessionTracking: {<br>    samplingRate: 0.1, // collect sessions from 10% of users<br>  },<br>});</pre><p><strong>Use data retention policies.</strong> Configure Loki and Tempo retention to match your compliance requirements, frontend traces rarely need to be kept longer than 30–90 days.</p><h3>Conclusion</h3><p>Backend monitoring tells you when your services are struggling. Frontend observability with <strong>Grafana Faro</strong> tells you when your <em>users</em> are struggling and in production, those are often very different things. A backend that’s perfectly healthy can still deliver a broken experience if a JavaScript error blocks checkout, a slow render degrades a dashboard, or a failed fetch leaves a user staring at a spinner.</p><p>By integrating Faro into your React application, connecting it to Grafana Cloud, and correlating frontend traces with backend spans, you achieve true end-to-end observability, a single pane of glass from the user’s click to the database query and back.</p><p>Start with automatic instrumentation, add user context and custom events for your critical flows, and build dashboards around the metrics that reflect real user experience. Observability is only complete when it includes the user.</p><p><em>Using Vue, Angular, or a meta-framework like Next.js? Grafana Faro’s Web SDK is framework-agnostic, the setup differs slightly but the instrumentation API is identical. Drop your stack in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e4eb88f44b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>