<?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 Sidhu Sangani on Medium]]></title>
        <description><![CDATA[Stories by Sidhu Sangani on Medium]]></description>
        <link>https://medium.com/@sidhusangani?source=rss-fc0d411a7f1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IfOyL--tBOm9QyGV</url>
            <title>Stories by Sidhu Sangani on Medium</title>
            <link>https://medium.com/@sidhusangani?source=rss-fc0d411a7f1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:45:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sidhusangani/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[“Mapla, Cluster CA Expire Aagidum!” — A DevOps Engineer’s Diary on GKE Credential Rotation]]></title>
            <link>https://medium.com/@sidhusangani/mapla-cluster-ca-expire-aagidum-a-devops-engineers-diary-on-gke-credential-rotation-0e285679ce59?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e285679ce59</guid>
            <category><![CDATA[gke-credential-rotation]]></category>
            <category><![CDATA[certificate-rotation]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 07:25:55 GMT</pubDate>
            <atom:updated>2026-07-03T07:25:55.811Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Or: How I learned that GCP notifications deserve more respect than my college attendance</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4631bu2Ex5ofyDWhGKmrA.png" /></figure><h3>The Notification Nobody Reads (Until It’s Too Late)</h3><p>You know that feeling when you open GCP console and there’s a banner sitting quietly at the top, and you just… scroll past it? Yeah. That was me, for a few weeks.</p><p>Then one fine Cloud Shell session, while doing something completely unrelated, I decided to actually read it:</p><blockquote>“The cluster certificate authority will expire on 2026–08–01. You must rotate the cluster credentials before its expiry to prevent cluster outage. If no action is taken, Google will attempt to rotate the cluster credentials within 30 days of expiry as a last resort to keep the cluster operational.”</blockquote><p>Konjam bayam vandhuchu da. Production cluster. Multiple business-critical applications. A CA that’s been quietly aging since 2021.</p><pre>gcloud container clusters describe &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --format &quot;value(masterAuth.clusterCaCertificate)&quot; \<br>  | base64 --decode \<br>  | openssl x509 -noout -dates</pre><pre>notBefore=Aug  2 13:32:06 2021 GMT<br>notAfter=Aug  1 14:32:06 2026 GMT</pre><p>Five years. The CA was issued back when this cluster was a baby. Now it’s basically a teenager about to lose its passport.</p><h3>Wait, Why Does a Kubernetes Cluster Even Have an Expiring Certificate?</h3><p>If you’re new to this (like I had to re-learn, ironically), here’s the simplified mental model:</p><p>Think of your cluster’s <strong>Certificate Authority</strong> as the <strong>Passport Office</strong> of your Kubernetes world. It issues “passports” (certificates) to:</p><ul><li>The <strong>API server</strong> — proving it’s the legitimate control plane</li><li>Every <strong>node’s kubelet</strong> — proving it’s a legitimate part of the cluster</li><li><strong>Your kubectl client</strong> — proving you’re an authorized admin</li></ul><p>When the CA expires, it’s like the Passport Office shutting down overnight. Every passport it ever issued becomes invalid simultaneously. Nobody can prove who they are anymore. The cluster doesn’t crash exactly — it just stops trusting <em>anyone</em>, which functionally amounts to the same thing.</p><p>Clusters created before October 2021 got a 5-year CA lifetime. Newer ones get 30 years. Bad luck if your cluster, like mine, falls just on the wrong side of that line.</p><h3>July 2nd &gt; August 1st (The Date That Actually Mattered)</h3><p>Here’s the twist that changed my entire urgency calculation. The real deadline wasn’t August 1st — it was <strong>30 days before expiry</strong>.</p><pre>June 23 ──────── July 2 ──────── July 25 ──── Aug 1<br>   │                 │                │            │<br> TODAY        Google starts        DEGRADED     CA DEAD<br>              auto-rotation        state        💀<br>              (ignores YOUR<br>              maintenance window)</pre><p>After July 2nd, if I hadn’t rotated manually, <strong>Google would do it for me — on Google’s schedule, not mine.</strong> Ignoring my maintenance windows. Ignoring my exclusions. Just doing it whenever, to keep the cluster from dying.</p><p>That’s the moment “I’ll get to it next sprint” turned into “I’m doing this tonight.”</p><h3>Step 1: Build a Safety Net (Because Production Doesn’t Forgive)</h3><p>Before touching anything on the live cluster, I made a decision that probably saved me a few grey hairs: <strong>build a full replica cluster as a backup</strong>, parallel, in the same VPC.</p><p>The idea was simple — if rotation goes sideways at any point, I flip DNS and traffic flows to a fully functional twin cluster instead. No “let’s hope it works” energy allowed in production.</p><h3>What this actually involved</h3><p><strong>New GKE cluster</strong>, same VPC, same subnet (reusing the primary IP range — there were 230+ free addresses sitting unused), but with <strong>new secondary IP ranges</strong> for pods and services, since GKE flatly refuses to let two clusters share a Service CIDR.</p><pre>gcloud compute networks subnets update &lt;subnet-name&gt; \<br>  --region &lt;region&gt; \<br>  --add-secondary-ranges &lt;pod-range-name&gt;=&lt;new-pod-cidr&gt; \<br>  --add-secondary-ranges &lt;svc-range-name&gt;=&lt;new-svc-cidr&gt;</pre><p><strong>New node pool</strong>, matched exactly to production specs — same machine type, same disk config, same autoscaling bounds, same surge upgrade strategy. I went line by line through gcloud container clusters describe output on the live cluster and replicated every relevant field.</p><p><strong>Image pull secrets, Workload Identity bindings, Kubernetes ServiceAccounts</strong> — all recreated and re-annotated for the new cluster, because none of this carries over automatically.</p><p><strong>A separate static external IP</strong> for the new ingress, because the original one was already bound to the live load balancer.</p><p><strong>All 8 production applications</strong> redeployed via dedicated Jenkins pipelines pointing at the backup cluster — separate jobs per service, separate manifests, same image tags as production for parity.</p><p>By the time I was done, I had a fully functioning twin cluster sitting quietly in the same network, ready to take traffic if needed. Total overkill for a routine cert rotation? Maybe. But “maybe” isn’t a word I wanted anywhere near production that night.</p><h3>The Night of the Activity</h3><p>With the safety net built, stakeholders informed, and a clear runbook in hand, the actual rotation night was almost anticlimactic — which is exactly how you want production changes to feel.</p><p>Official documentation: <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/credential-rotation">https://cloud.google.com/kubernetes-engine/docs/how-to/credential-rotation</a></p><h3>Step 0 — Confirm your CA expiry</h3><pre>gcloud container clusters describe &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --format &quot;value(masterAuth.clusterCaCertificate)&quot; \<br>  | base64 --decode \<br>  | openssl x509 -noout -dates</pre><p>Output:</p><pre>notBefore=Aug  2 13:32:06 2021 GMT<br>notAfter=Aug  1 14:32:06 2026 GMT</pre><p>Also check for static SA tokens — these become invalid after rotation:</p><pre>kubectl get secrets --all-namespaces \<br>  --field-selector type=kubernetes.io/service-account-token \<br>  -o custom-columns=&#39;NAMESPACE:.metadata.namespace,NAME:.metadata.name&#39;</pre><p>If output is empty — you’re good. No static tokens to worry about.</p><h3>Step 1 — Start the rotation</h3><p>The control plane starts serving on a new IP address in addition to the original. New credentials are issued to workloads and the control plane.</p><pre>gcloud container clusters update &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --start-credential-rotation</pre><p>⚠️ <strong>Zonal Standard clusters (single control plane node) will experience brief API server downtime here.</strong> kubectl will be unavailable for ~1–2 minutes — don’t panic, it comes back automatically.</p><p>After this completes, check pod logs for x509 errors — if found, restart the affected system pods:</p><pre>kubectl logs -n kube-system deployment/metrics-server --tail=50 | grep -i &quot;x509&quot;<br>kubectl logs -n kube-system deployment/konnectivity-agent --tail=50 | grep -i &quot;x509&quot;</pre><pre># Only if errors found<br>kubectl rollout restart deployment metrics-server -n kube-system<br>kubectl rollout restart deployment konnectivity-agent -n kube-system</pre><h3>Step 2 — Recreate nodes</h3><p>GKE recreates cluster nodes so that the nodes use the new IP address and credentials, respecting availability from maintenance windows.</p><blockquote><strong><em>Important:</em></strong><em> If you have a maintenance window configured, nodes will NOT recreate until the next window opens. To force immediate recreation, manually trigger a node pool upgrade to the same version:</em></blockquote><pre>gcloud container clusters upgrade &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --node-pool &lt;node-pool-name&gt;</pre><p>Monitor progress:</p><pre># Get the operation ID<br>gcloud container operations list \<br>  --filter=&quot;operationType=UPGRADE_NODES AND status=RUNNING&quot; \<br>  --format=&quot;value(name)&quot;</pre><pre># Poll the operation<br>gcloud container operations wait &lt;OPERATION_ID&gt;</pre><p>Watch nodes cycle through NotReady → Ready:</p><pre>watch -n 10 kubectl get nodes</pre><p><strong>Do not proceed to Step 3 until ALL nodes show Ready.</strong></p><h3>Step 3 — Update API clients</h3><p>After node recreation, update all API clients outside the cluster (kubectl on developer machines, CI/CD systems) to communicate with the new control plane IP:</p><pre>gcloud container clusters get-credentials &lt;cluster-name&gt; \<br>  --zone &lt;zone&gt; \<br>  --project &lt;project-id&gt;</pre><pre># Verify<br>kubectl get nodes</pre><h3>Step 4 — Complete the rotation</h3><p>The control plane stops serving on the old IP. Old CA and old credentials are revoked.</p><pre>gcloud container clusters update &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --complete-credential-rotation</pre><p>⚠️ <strong>Brief API server downtime again for zonal clusters</strong> — same as Step 1, ~1–2 minutes.</p><p><strong>If this fails with a 400 error:</strong></p><pre>ERROR: (gcloud.container.clusters.update) ResponseError: code=400,<br>message=Node pool &quot;&lt;pool-name&gt;&quot; requires recreation.</pre><p>Run the node pool upgrade again, then retry complete:</p><pre>gcloud container clusters upgrade &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --node-pool &lt;node-pool-name&gt;</pre><pre>gcloud container clusters update &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --complete-credential-rotation</pre><h3>Step 5 — Verify</h3><pre>gcloud container clusters describe &lt;cluster-name&gt; \<br>  --location &lt;zone&gt; \<br>  --format &quot;value(masterAuth.clusterCaCertificate)&quot; \<br>  | base64 --decode \<br>  | openssl x509 -noout -dates</pre><p>Expected output:</p><pre>notBefore=Jun 28 2026 GMT<br>notAfter=Jun 20 2056 GMT  ✅</pre><p>Thirty years. I will, statistically speaking, not be the one rotating this CA next time.</p><blockquote><strong><em>Note:</em></strong><em> The GCP console recommendation banner may persist for up to 36 hours after completion — this is expected and will resolve automatically. From official docs: </em>“Once the credential rotation has completed it can take up to 36 hours for the insight and recommendation to resolve.”</blockquote><h3>The Curveball Nobody Warned Me About</h3><p>Just when I thought it was a clean wrap, one of the services started throwing 404s on a background Slack-alerting call:</p><pre>Your Kubernetes service account (&lt;namespace&gt;/default) is not annotated <br>with a target Google service account, which is a requirement for <br>retrieving Identity Tokens using Workload Identity.</pre><p>Now here’s the part that actually made me pause and question reality: <strong>this pod had been running fine for years without that annotation.</strong> Why would it suddenly break <em>after</em> a credential rotation?</p><p>The honest answer, after digging through logs: I don’t have 100% documented certainty on the exact mechanism, but the circumstantial evidence pointed at the node version bump that comes bundled with credential rotation (GKE recreates nodes on the <em>same</em> version they’re running, but in this case a patch version had quietly moved forward too). Something about the fresh metadata server on the new nodes started strictly enforcing Workload Identity annotation requirements where the old nodes may have been more permissive.</p><p>Rather than chase ghosts, I did the only honest thing: I checked Cloud Logging for the exact error signature <em>before</em> the rotation timestamp. No matches. The fix was straightforward regardless of root cause — properly annotate the service account with the correct IAM-bound GSA, redeploy, done.</p><pre>kubectl annotate serviceaccount &lt;sa-name&gt; \<br>  --namespace &lt;namespace&gt; \<br>  iam.gke.io/gcp-service-account=&lt;gsa-email&gt; \<br>  --overwrite</pre><p>Lesson learned: even a “routine” infra operation can surface dormant configuration debt that’s been quietly working by accident for years.</p><h3>What I’d Tell Past-Me (and You)</h3><p><strong>Read the GCP notifications.</strong> Genuinely. They’re not decoration.</p><p><strong>The “soft deadline” is earlier than the hard deadline.</strong> Google’s 30-day auto-rotation window matters more than the actual expiry date, because it determines whether <em>you</em> control the timing or <em>Google</em> does.</p><p><strong>Build a backup before you touch production</strong>, even if it feels excessive. The hours spent replicating a cluster are cheaper than the hours spent firefighting an outage at 2 AM.</p><p><strong>loadBalancerSourceRanges ≠ load balancer IP.</strong> Don&#39;t let unfamiliar fields make you more nervous than they should — but also, verify from official docs before patching anything live. &quot;Probably fine&quot; and &quot;confirmed from documentation&quot; are different confidence levels.</p><p><strong>Force node recreation manually if you’re not waiting for a maintenance window.</strong> Don’t assume the rotation will move at the pace you expect.</p><p><strong>Even successful operations can surface old, unrelated bugs.</strong> Don’t assume every new error post-change is <em>caused by</em> the change — but don’t dismiss it either. Check the logs, get the timestamp, get the truth.</p><h3>Final Status</h3><pre>✅ CA rotated — valid until 2056<br>✅ Zero unplanned downtime<br>✅ Backup cluster proved its worth as a safety net (even if unused for failover)<br>✅ One dormant Workload Identity bug surfaced and fixed<br>✅ Stakeholders informed at every step<br>✅ Sleep schedule: mildly disrupted, fully recovered</pre><p>Production infra work is 10% commands and 90% making sure you’ve thought through every “what if” before you press enter. Tonight, the “what ifs” mostly stayed hypothetical — and that’s exactly the kind of boring outcome you want when you’re holding the keys to a production Kubernetes cluster.</p><p><em>If you’re sitting on a GKE cluster older than a few years and haven’t checked your CA expiry — go check it now. Don’t wait for the notification to read itself.</em></p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e285679ce59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Migrated from Promtail to Grafana Alloy on an EC2]]></title>
            <link>https://medium.com/@sidhusangani/how-i-migrated-from-promtail-to-grafana-alloy-on-an-ec2-b77e975c81b9?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b77e975c81b9</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[alloy]]></category>
            <category><![CDATA[promtail]]></category>
            <category><![CDATA[loki]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 09:31:19 GMT</pubDate>
            <atom:updated>2026-04-28T05:24:41.594Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Promtail is dead. Here’s how I replaced it with Grafana Alloy on a Ubuntu VM shipping systemd journal logs to Loki — with zero downtime and zero dashboard changes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7neXAXPQGtgCzF4HxmSFKA.png" /></figure><h3>Why This Post Exists</h3><p>If you’ve been running Grafana Loki in production, you’ve almost certainly been using Promtail to ship logs into it. It’s been the default log collector in the Grafana ecosystem for years — simple, reliable, and YAML-configured.</p><p>But as of <strong>March 2, 2026, Promtail has officially reached end-of-life</strong>. No more security patches, no bug fixes, no improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*TVVXbusd-v1tM48bh7_xXw.gif" /><figcaption>irru da irru, ennaku bhayama dhan da irruku</figcaption></figure><p>For anyone running Promtail in production, this isn’t a “nice to have” migration — it’s a compliance and security requirement. Grafana’s recommended replacement is <strong>Grafana Alloy</strong>.</p><h3>Why Grafana Alloy? (The Short Version)</h3><p>For years, the Grafana observability stack required juggling multiple collectors — Promtail for shipping logs to Loki, Prometheus’s built-in scraper for pulling metrics, and the OpenTelemetry Collector for receiving traces destined for Tempo. Three binaries, three config formats, three things to upgrade, monitor, and secure.</p><p>Grafana Alloy consolidates all three into a <strong>single collector</strong> with one unified configuration language called <strong>River</strong> (now officially “Alloy syntax”). It’s not a rewrite — Alloy embeds the actual Promtail, Prometheus, and OpenTelemetry Collector code as components, exposed through a clean component-graph model where outputs of one component flow into inputs of another.</p><p>The result is one agent that can collect logs, metrics, traces, and even continuous profiles, ship them to their respective backends, and give you a live debugging UI on port 12345 to inspect the pipeline as it runs.</p><h3>Collectors vs Backends — The Critical Distinction</h3><p>This is the part that confused me initially: <strong>Loki, Prometheus, and Tempo are not going anywhere</strong>. They remain the storage and query engines for logs, metrics, and traces respectively. Alloy simply ships data to them the same way the old collectors did.</p><p>The deprecation story is only about <strong>collectors</strong>:</p><p>Old Collector Replaced By Ships Data To Promtail (logs) Alloy Loki (unchanged) Prometheus scraper (metrics) Alloy Prometheus / Mimir (unchanged) OTel Collector (traces) Alloy Tempo / Jaeger (unchanged)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*jPaWhwgJaOFdvkIwyoPcaA.gif" /><figcaption>vare vare alloy dhan , mathum collectors close</figcaption></figure><p>Three collectors collapsing into one. Backends are untouched. Your dashboards, LogQL queries, and alerting rules — all stay exactly the same.</p><h3>My Setup Before Migration</h3><p>Here’s what I was working with on the dev environment:</p><ul><li><strong>VM</strong>: Ubuntu 24.04 on AWS EC2, part of an Auto Scaling Group</li><li><strong>Services running</strong>: Application running as systemd service</li><li><strong>Log source</strong>: systemd journal (/var/log/journal)</li><li><strong>Collector</strong>: Promtail, installed as a binary, running as a systemd service</li><li><strong>Destination</strong>: Loki, running in EKS behind an internal ALB</li></ul><h3>The Promtail Config I Was Replacing</h3><pre># promtail-config.yaml<br>server:<br>  http_listen_port: 9082<br>  grpc_listen_port: 0</pre><pre>positions:<br>  filename: /home/ubuntu/logs/positions.yaml</pre><pre>clients:<br>  - url: http://&lt;loki-internal-alb&gt;/loki/api/v1/push</pre><pre>scrape_configs:<br>  - job_name: name_of_job<br>    journal:<br>      max_age: 10m<br>      path: /var/log/journal<br>      labels:<br>        service: service_name<br>        hostname: ${host_name}<br>        mid: ${machine_id}<br>    relabel_configs:<br>      - source_labels: [&#39;__syslog_connection_hostname&#39;]<br>        target_label: &#39;host&#39;<br>      - source_labels: [&#39;__journal__systemd_unit&#39;]<br>        target_label: &#39;unit&#39;</pre><h3>The Template Trick (ASG-Friendly Promtail)</h3><p>Notice the ${host_name} and ${machine_id} placeholders? Promtail doesn&#39;t support environment variable substitution natively, so we used a <strong>two-file pattern</strong>:</p><ol><li><strong>promtail-config-template.yaml</strong> — baked into the AMI with ${host_name} placeholders</li><li><strong>promtail-config.yaml</strong> — generated at service start by envsubst, with real hostname and machine-id</li></ol><p>The systemd service orchestrated this dance:</p><pre>[Service]<br>Environment=host_name=%H<br>Environment=machine_id=%m<br>ExecStartPre=/bin/bash -c &#39;rm -f promtail-config.yaml&#39;<br>ExecStartPre=/bin/bash -c &#39;envsubst &lt; promtail-config-template.yaml &gt; promtail-config.yaml&#39;<br>ExecStart=/bin/bash -c &#39;sudo promtail -config.file promtail-config.yaml&#39;</pre><p>Every time the service starts, systemd expands %H (hostname) and %m (machine-id) into environment variables, envsubst substitutes them into the template, and Promtail starts with the rendered config. Clever pattern, but fragile — two config files, envsubst as a dependency, running as root via sudo. Alloy improves on all of these.</p><h3>Step-by-Step Migration</h3><h3>Step 1: Install Alloy</h3><pre>sudo mkdir -p /etc/apt/keyrings<br>sudo wget -O /etc/apt/keyrings/grafana.asc https://apt.grafana.com/gpg-full.key<br>sudo chmod 644 /etc/apt/keyrings/grafana.asc<br>echo &quot;deb [signed-by=/etc/apt/keyrings/grafana.asc] https://apt.grafana.com stable main&quot; \<br>  | sudo tee /etc/apt/sources.list.d/grafana.list<br>sudo apt-get update<br>sudo apt-get install -y alloy</pre><p>This installs the alloy binary, creates a systemd unit file, and sets up the default config at /etc/alloy/config.alloy. <strong>Don&#39;t start it yet</strong> — we need to configure it first.</p><blockquote><strong><em>Note for RHEL/CentOS/Amazon Linux users</em></strong><em>: The Alloy config file location is the same (</em><em>/etc/alloy/config.alloy), but the service environment file is at </em><em>/etc/sysconfig/alloy instead of Ubuntu&#39;s </em><em>/etc/default/alloy.</em></blockquote><h3>Step 2: Stop Promtail</h3><pre>sudo systemctl stop promtail<br>sudo systemctl disable promtail</pre><p>Don’t uninstall it yet — keep it around as a rollback option for 48 hours.</p><h3>Step 3: Convert the Promtail Config</h3><p>This is the magic command that makes the whole migration tractable:</p><pre>sudo alloy convert \<br>  --source-format=promtail \<br>  --output=/home/ubuntu/logs/converted-config.alloy \<br>  /home/ubuntu/logs/promtail-config.yaml</pre><p>The converter reads your Promtail YAML and produces Alloy’s River syntax. Here’s what it generated:</p><pre>discovery.relabel &quot;abc&quot; {<br>    targets = []<br>    rule {<br>        source_labels = [&quot;__syslog_connection_hostname&quot;]<br>        target_label  = &quot;host&quot;<br>    }<br>    rule {<br>        source_labels = [&quot;__journal__systemd_unit&quot;]<br>        target_label  = &quot;unit&quot;<br>    }<br>}</pre><pre>loki.source.journal &quot;abc&quot; {<br>    max_age       = &quot;10m0s&quot;<br>    path          = &quot;/var/log/journal&quot;<br>    relabel_rules = discovery.relabel.CBD.rules<br>    forward_to    = [loki.write.default.receiver]<br>    labels        = {<br>        hostname = &quot;ip_of_host&quot;,<br>        mid      = &quot;&quot;,<br>        service  = &quot;abc&quot;,<br>    }<br>}</pre><pre>loki.write &quot;default&quot; {<br>    endpoint {<br>        url = &quot;http://&lt;loki-internal-alb&gt;/loki/api/v1/push&quot;<br>    }<br>    external_labels = {}<br>}</pre><p>Zero errors, zero warnings. Clean translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*VTCZ4fIyQaBJ2N9wt75cQw.gif" /></figure><h3>Understanding the Converted Config</h3><p>If you’re seeing River syntax for the first time, here’s how Promtail concepts map to Alloy components:</p><p>Promtail YAML Alloy River What It Does server: (handled by launch flags) HTTP server settings positions: --storage.path flag Bookmark/cursor tracking clients: loki.write &quot;name&quot; { } Where to push logs scrape_configs[].journal: loki.source.journal &quot;name&quot; { } Read from journald relabel_configs: discovery.relabel &quot;name&quot; { } Transform labels job_name: The &quot;name&quot; after component type Human-readable identifier (implicit wiring) forward_to = [...] Explicit pipeline connections</p><p>The key difference: in Promtail, the wiring between components is implicit — all scrape configs share the same clients: block. In Alloy, the wiring is <strong>explicit</strong> — forward_to = [loki.write.default.receiver] is literally an arrow in the component graph.</p><h3>Step 4: Improve the Config (Kill the Template Pattern)</h3><p>The converter produced hardcoded hostname and machine-id values. That works for one VM, but breaks the ASG pattern where each instance needs its own identity.</p><p>Alloy has a built-in sys.env() function that reads environment variables <strong>at runtime</strong>. No envsubst, no template file, no two-file dance.</p><p>The final config written to /etc/alloy/config.alloy:</p><pre>discovery.relabel &quot;CBD&quot; {<br>    targets = []<br>    rule {<br>        source_labels = [&quot;__syslog_connection_hostname&quot;]<br>        target_label  = &quot;host&quot;<br>    }<br>    rule {<br>        source_labels = [&quot;__journal__systemd_unit&quot;]<br>        target_label  = &quot;unit&quot;<br>    }<br>}</pre><pre>loki.source.journal &quot;abc&quot; {<br>    max_age       = &quot;10m0s&quot;<br>    path          = &quot;/var/log/journal&quot;<br>    relabel_rules = discovery.relabel.CBD.rules<br>    forward_to    = [loki.write.default.receiver]<br>    labels        = {<br>        hostname = sys.env(&quot;HOSTNAME&quot;),<br>        mid      = sys.env(&quot;MACHINE_ID&quot;),<br>        service  = &quot;CBD&quot;,<br>    }<br>}</pre><pre>loki.write &quot;default&quot; {<br>    endpoint {<br>        url = &quot;http://&lt;loki-internal-alb&gt;/loki/api/v1/push&quot;<br>    }<br>    external_labels = {}<br>}</pre><p><strong>One config file. Works on every ASG instance. No templating engine needed.</strong></p><h3>Step 5: Set Up the Systemd Drop-In</h3><p>The HOSTNAME variable is already provided by Alloy&#39;s default systemd unit (Environment=HOSTNAME=%H). But MACHINE_ID isn&#39;t, so I added a drop-in override:</p><pre>sudo mkdir -p /etc/systemd/system/alloy.service.d<br>sudo tee /etc/systemd/system/alloy.service.d/override.conf &lt;&lt;&#39;EOF&#39;<br>[Service]<br>Environment=MACHINE_ID=%m<br>EOF</pre><blockquote><strong><em>Why a drop-in instead of editing the main service file?</em></strong><em> Because </em><em>apt upgrade alloy may overwrite the main unit file. Drop-ins survive package upgrades. This is the Debian/Ubuntu recommended pattern for customizing packaged services.</em></blockquote><h3>Step 6: Grant Journal Access (Critical Gotcha! ⚠️)</h3><p><strong>This is the #1 gotcha for Promtail-to-Alloy migrations.</strong></p><p>Promtail in my setup ran as <strong>root</strong> (via sudo in the ExecStart). Alloy runs as a dedicated alloy user with minimal privileges. The systemd journal directory is owned by root:systemd-journal and is only readable by group members. Without this step, Alloy starts fine but <strong>silently fails to read any logs</strong>:</p><pre>sudo usermod -aG systemd-journal alloy</pre><p>If you skip this, you’ll be staring at Loki with zero logs and no error message anywhere. Ask me how I know.</p><h3>Step 7: Start Alloy and Verify</h3><pre>sudo systemctl daemon-reload<br>sudo systemctl enable alloy<br>sudo systemctl restart alloy<br>sudo systemctl status alloy</pre><p>Output:</p><pre>● alloy.service - Vendor-agnostic OpenTelemetry Collector distribution<br>     Loaded: loaded (/usr/lib/systemd/system/alloy.service; enabled; preset: enabled)<br>    Drop-In: /etc/systemd/system/alloy.service.d<br>             └─override.conf<br>     Active: active (running) since Sat 2026-04-25 06:43:18 UTC<br>   Main PID: 1274547 (alloy)<br>     Memory: 69.7M (peak: 70.7M)</pre><p>Key things to check:</p><ul><li><strong>Drop-In: override.conf</strong> — systemd is reading our env var override ✅</li><li><strong>Active: active (running)</strong> — Alloy is up ✅</li><li><strong>Memory: 69.7M</strong> — baseline footprint (Promtail was ~20–30 MB; Alloy is heavier) ✅</li></ul><p>Verify the environment variables resolved correctly:</p><pre>sudo cat /proc/$(pgrep alloy)/environ | tr &#39;\0&#39; &#39;\n&#39; | grep -E &quot;HOSTNAME|MACHINE_ID&quot;</pre><pre>HOSTNAME=ip-10-2-112-131<br>MACHINE_ID=ec29c1a2fd3cb84fb914f74ad48e9afc</pre><p>Both resolved. Now check Grafana — query Loki with:</p><pre>{service=&quot;CBD&quot;, hostname=&quot;ip-10-2-112-131&quot;}</pre><p><strong>Logs flowing. All three services visible. Labels correct. Migration complete.</strong></p><h3>What Changed vs What Stayed the Same</h3><p>Aspect Before (Promtail) After (Alloy) Config files 2 (template + rendered) 1 Config language YAML River (Alloy syntax) Templating envsubst (external tool) sys.env() (built-in) Systemd unit Full custom unit with ExecStartPre hacks Package default + 2-line drop-in Runs as root (via sudo) alloy user (least privilege) Positions/bookmarks positions.yaml (manual config) --storage.path (automatic) Debug UI None Port 12345 with component graph Loki endpoint Same Same LogQL queries Same Same Grafana dashboards Same Same Labels on logs Same Same</p><p>The critical point: <strong>everything downstream is identical</strong>. Loki, Grafana, dashboards, alerts — completely unchanged. Only the collector changed.</p><h3>Gotchas and Lessons Learned</h3><h3>1. Journal Permissions = Silent Failure</h3><p>If Alloy can’t read /var/log/journal, it starts successfully but ships zero logs. No error in systemctl status, no crash. You only notice when you check Loki and see nothing. Always run sudo usermod -aG systemd-journal alloy before starting the service.</p><h3>2. Positions Don’t Migrate</h3><p>Promtail’s positions.yaml (journal cursors) and Alloy&#39;s internal state (/var/lib/alloy/data/) are incompatible formats. On first start, Alloy re-ships the last 10 minutes of journal logs (due to max_age). Loki handles deduplication, so it&#39;s harmless.</p><h3>3. The Converter Is Good, Not Perfect</h3><p>alloy convert --source-format=promtail handled my config flawlessly, but it produces a literal translation — hardcoded values, no sys.env() optimization. Always review and improve the output, especially for ASG/fleet scenarios.</p><h3>4. Memory Footprint Is Higher</h3><p>Promtail at idle: ~20–30 MB. Alloy at idle with the same log-only config: ~70 MB. Alloy bundles Prometheus scraper and OTel Collector code even if you’re only using the log pipeline. At scale, this delta adds up.</p><h3>5. Don’t Remove Promtail Immediately</h3><p>Keep Promtail installed but disabled for 48 hours. If anything goes wrong:</p><pre>sudo systemctl stop alloy<br>sudo systemctl start promtail</pre><p>Instant rollback. Remove Promtail only after verified stability.</p><h3>6. Ubuntu vs RHEL Config Paths</h3><p>The Alloy River config file is at /etc/alloy/config.alloy on both distros. But the systemd service environment file differs: /etc/default/alloy on Ubuntu/Debian, /etc/sysconfig/alloy on RHEL/CentOS/Amazon Linux. Easy to miss when writing cross-distro runbooks.</p><h3>The Bigger Picture</h3><p>This migration was <strong>Phase 1</strong> — logs only, like-for-like replacement, zero changes to Prometheus or anything else. I tested it on a dev environment first before planning the production rollout.</p><p>Alloy <em>can</em> also replace Prometheus scraping (via prometheus.scrape + prometheus.remote_write) and serve as an OTel Collector for traces (via otelcol.receiver.otlp), but those are separate conversations for separate quarters.</p><p>The discipline is: <strong>swap one component, verify it works, document it, then move on.</strong> Don’t let scope creep tempt you into consolidating your entire observability stack just because Alloy can do it all.</p><p>For teams running Promtail on VMs, the migration path is clear:</p><ol><li>Install Alloy from the Grafana APT/YUM repo</li><li>Run alloy convert on your existing Promtail config</li><li>Clean up the output (replace hardcoded values with sys.env() if needed)</li><li>Grant journal permissions to the alloy user</li><li>Stop Promtail, start Alloy, verify in Loki</li><li>Keep Promtail as a rollback for 48 hours</li></ol><p>Total time: <strong>under an hour</strong> for the first host. Minutes for subsequent hosts once you have the pattern also i have implemented this via ansible.</p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><p><em>In the next post, I’ll cover deploying Alloy as a sidecar on EKS — the Kubernetes migration path, with Downward API for pod metadata, River ConfigMaps, and the debug UI that makes it all worth it. Stay tuned!</em></p><p><strong>Tags</strong>: #grafana #alloy #promtail #loki #devops #observability #migration #aws #kubernetes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b77e975c81b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Implementing DORA Metrics with Apache DevLake on AWS EKS]]></title>
            <link>https://medium.com/@sidhusangani/implementing-dora-metrics-with-apache-devlake-on-aws-eks-af3a5bf096da?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/af3a5bf096da</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[dora]]></category>
            <category><![CDATA[apache-devlake]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 10:18:37 GMT</pubDate>
            <atom:updated>2025-10-22T10:18:37.321Z</atom:updated>
            <content:encoded><![CDATA[<p>(A DevOps tale of encryption chaos, pod drama, and eventual enlightenment)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0PMaP1tItt1egorGKhncw.png" /></figure><h3>Introduction</h3><p>When my manager said, “We need DORA,” my brain immediately pictured the cartoon explorer marching into prod with a backpack and a talking map. For a glorious second, I thought she’d sing us to 99.99% uptime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*5A-Gpm_zP4WrhfDVfe5O2A.gif" /></figure><p>Then Google ruined the joke: this DORA is DevOps, not daycare — and she measures whether our deploys light small candles or full-on bonfires.</p><p>I’ve been chasing one ancient DevOps mystery:<br> <strong>“How fast can we deploy without setting production on fire?”</strong> 🔥</p><p>That’s where <strong>DORA metrics</strong> show up — the four chaotic forces of nature:</p><ul><li><strong>Deployment Frequency</strong> — how many times you press “deploy” before regret kicks in</li><li><strong>Lead Time for Changes</strong> — how long it takes your PR to move from “WIP” to “Why is this still not merged?”</li><li><strong>Change Failure Rate</strong> — percentage of times your deployment screams for rollback</li><li><strong>Time to Restore Service</strong> — how long it takes before you can say “all systems operational” with a straight face</li></ul><p>So my manager goes, <em>“Let’s implement DORA metrics!”</em><br> And my dumb self goes, <em>“Sure, how hard can it be?”</em><br> Spoiler: very. extremely. scientifically painful. 🧠💥</p><p>Enter <strong>Apache DevLake</strong> — an open-source data cauldron that promises DORA dashboards in Grafana.<br> Sounds magical, right? Yeah, until it starts behaving like that one intern who “accidentally” deletes the staging namespace.</p><p>My DevLake journey had everything:<br> 💣 <strong>EBS encryption apocalypse</strong> — where AWS said “nope” and I said “why?”<br> 🌀 <strong>Ingress gymnastics</strong> — because one ingress rule apparently controls your destiny<br> 🐍 <strong>Kubernetes black magic</strong> — logs so cryptic even Promtail looked confused</p><p>But hey — after all the chaos, I did it.<br> DORA metrics are live, Grafana looks happy, and I only cried twice.</p><p>Would I do it again?<br> Probably.<br> But next time, I’m bringing holy water for the cluster. 😇</p><h3>🧩 What is Apache DevLake?</h3><p>Think of DevLake as that friend who listens to everyone’s gossip (Jenkins, GitHub, GitLab, Jira, etc.) and then summarizes it all neatly in Grafana dashboards.</p><p><strong>In short:</strong></p><ul><li>Connects all your DevOps tools into one data lake</li><li>Ships with ready-made DORA dashboards</li><li>Let&#39;s you customize transformations (for when Jenkins behaves weirdly)</li><li>Supports 15+ data sources</li></ul><p>Basically, if your CI/CD and issue-tracking tools were chaotic teenagers, DevLake is the calm parent bringing order to their mess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POyHHz6A87CB2_E1ovnsIA.png" /></figure><h3>My Architecture Setup on AWS EKS</h3><p>I deployed the following components:</p><ul><li><strong>DevLake Lake</strong>: Core service for data collection and processing</li><li><strong>DevLake UI</strong>: Web-based configuration interface (subdomain-based routing)</li><li><strong>MySQL</strong>: Data storage backend (50GB encrypted EBS volume)</li><li><strong>Grafana</strong>: Visualization and pre-built DORA dashboards (4GB encrypted EBS volume)</li><li><strong>AWS EBS CSI Driver</strong>: For dynamic persistent volume provisioning</li><li><strong>NGINX Ingress Controller</strong>: For external access with path-based and subdomain routing</li><li><strong>AWS Application Load Balancer</strong>: Frontend load balancer with SSL termination</li></ul><p>All components run on our EKS cluster with proper encryption, persistence, and timezone configuration for IST (Asia/Kolkata).</p><h3>Prerequisites</h3><p>Before starting, you’ll need:</p><ul><li>AWS EKS cluster (Kubernetes v1.19+)</li><li>EBS CSI Driver installed</li><li>NGINX Ingress Controller installed</li><li>Helm (v3.6+) and kubectl configured</li><li>Jenkins server with API access</li><li>GitHub account with repository access</li><li>Domain name with DNS access</li><li>AWS KMS key for EBS encryption (if nodes are encrypted)</li></ul><h3>The EBS Encryption Challenge I Faced</h3><h3>Context: What Was Working Initially</h3><p>When I first started this project, I had a basic StorageClass configuration without encryption. This worked perfectly because our EKS nodes weren’t encrypted at that time.</p><h3>The Day Everything Broke</h3><p>A few days later, when I tried to redeploy or create new pods, they got stuck in ContainerCreating state:</p><pre>kubectl get pods<br># NAME                    READY   STATUS              RESTARTS   AGE<br># devlake-mysql-0         0/1     ContainerCreating   0          15m</pre><pre>kubectl describe pod devlake-mysql-0<br># Warning  FailedMount  Volume attach failed: could not attach volume</pre><p><strong>What changed?</strong> Our infrastructure team had enabled encryption on all EKS worker nodes as part of our security compliance initiative. I didn’t know this would affect my PVCs!</p><h3>The 4–5 Hour Troubleshooting Marathon</h3><p>As the sole DevOps engineer, I spent hours debugging:</p><p><strong>What I tried:</strong></p><ul><li>✅ Checked EBS CSI Driver logs — nothing useful</li><li>✅ Recreated PVCs multiple times — same issue</li><li>✅ Verified IAM permissions — all looked good</li><li>✅ Searched Kubernetes documentation — no clear answers</li><li>✅ Asked ChatGPT and other AI tools — generic responses, not helpful</li><li>✅ Checked AWS forums — some hints but no clear solution</li></ul><p><strong>What finally worked:</strong> After extensive Googling with specific search terms like “EKS encrypted nodes PVC not attaching” and “AWS EBS CSI driver encrypted volumes”, I found the answer in AWS community blogs and GitHub issues.</p><h3>The Simple Solution with Encryption</h3><p>The solution was adding <strong>encryption parameters</strong> to my StorageClass. Here’s the actual StorageClass I used:</p><pre>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: ebs-sc-devlake-v2<br>provisioner: kubernetes.io/aws-ebs<br>parameters:<br>  type: gp2<br>  encrypted: &quot;true&quot;<br>  kmsKeyId: &quot;arn:aws:kms:ap-south-2:YOUR_ACCOUNT_ID:key/YOUR_KMS_KEY_ID&quot;<br>allowVolumeExpansion: true<br>reclaimPolicy: Delete<br>volumeBindingMode: Immediate</pre><p><strong>Key Parameters Explained:</strong></p><p>Parameter Value Why provisioner kubernetes.io/aws-ebs In-tree AWS EBS provisioner (works with older EKS) type gp2 General Purpose SSD encrypted &quot;true&quot; <strong>REQUIRED</strong> for encrypted nodes kmsKeyId Your organization&#39;s KMS key ARN Use your KMS key for encryption allowVolumeExpansion true Can expand volume size without recreation reclaimPolicy Delete Auto-delete volume when PVC deleted volumeBindingMode Immediate Create volume immediately</p><p><strong>Important Notes:</strong></p><ol><li><strong>Custom KMS Key</strong>: Replace YOUR_ACCOUNT_ID and YOUR_KMS_KEY_ID with your organization&#39;s KMS key ARN. This gives you:</li></ol><ul><li>Full control over key rotation</li><li>Better audit trail via CloudTrail</li><li>Compliance with your security policies</li></ul><p><strong>2 . Alternatively</strong>, you can use AWS&#39;s default managed key:</p><ul><li>kmsKeyId: &quot;alias/aws/ebs&quot; # AWS-managed default key</li></ul><p><strong>3. Reclaim Policy</strong>: I used Delete instead of Retain because:</p><ul><li>We have automated backups via Velero</li><li>Prevents orphaned EBS volumes (cost savings)</li><li>Fresh start approach for non-production</li></ul><h3>Why This Happens</h3><p><strong>The rule I learned:</strong></p><blockquote><em>When EKS worker nodes are encrypted, any EBS volumes attached to them </em><strong><em>must also be encrypted</em></strong><em> with a compatible KMS key. The provisioner won’t attach unencrypted volumes to encrypted nodes.</em></blockquote><p>This isn’t clearly documented in error messages, and I wasted hours because the FailedMount error didn&#39;t mention anything about encryption!</p><h3>Resources That Saved Me</h3><p>After ChatGPT couldn’t help, I found these resources through Google:</p><ol><li><strong>AWS EBS CSI Driver GitHub — Parameters Documentation</strong></li></ol><ul><li><a href="https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/parameters.md">https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/parameters.md</a></li><li>This had the exact parameter names I needed</li></ul><p><strong>2. EKS Best Practices Guide — Data Encryption</strong></p><ul><li><a href="https://aws.github.io/aws-eks-best-practices/security/docs/data/">https://aws.github.io/aws-eks-best-practices/security/docs/data/</a></li><li>Explained why encryption is required</li></ul><p><strong>3. AWS Community Blog Posts</strong> (found via Google)</p><ul><li>Search terms: “EKS encrypted nodes PVC”, “EBS CSI encrypted volumes”</li><li>Real-world examples from other engineers who faced the same issue</li></ul><p><strong>Lesson learned:</strong> For infrastructure-specific issues, Google searches with exact error terms and community blogs are more helpful than AI tools!</p><h3>Step-by-Step Implementation</h3><h3>Step 1: Create the Encrypted StorageClass</h3><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: ebs-sc-devlake-v2<br>provisioner: kubernetes.io/aws-ebs<br>parameters:<br>  type: gp2<br>  encrypted: &quot;true&quot;<br>  kmsKeyId: &quot;arn:aws:kms:ap-south-2:YOUR_ACCOUNT_ID:key/YOUR_KMS_KEY_ID&quot;<br>allowVolumeExpansion: true<br>reclaimPolicy: Delete<br>volumeBindingMode: Immediate<br>EOF</pre><pre># Verify<br>kubectl get storageclass ebs-sc-devlake-v2</pre><p><strong>Note:</strong> Replace the kmsKeyId with your organization&#39;s KMS key ARN, or use alias/aws/ebs for AWS default managed key.</p><h3>Step 2: Generate DevLake Encryption Secret</h3><pre># Generate a strong encryption secret<br>ENCRYPTION_SECRET=$(openssl rand -base64 2000 | tr -dc &#39;A-Z&#39; | fold -w 128 | head -n 1)</pre><pre># Save it securely<br>echo $ENCRYPTION_SECRET &gt; devlake-encryption-secret.txt<br>chmod 600 devlake-encryption-secret.txt</pre><pre># Or store in AWS Secrets Manager (recommended)<br>aws secretsmanager create-secret \<br>  --name devlake-encryption-secret \<br>  --description &quot;DevLake encryption secret for production&quot; \<br>  --secret-string &quot;$ENCRYPTION_SECRET&quot;</pre><h3>Step 3: Configure values.yaml</h3><p>I created a comprehensive values.yaml for our setup:</p><pre># values.yaml<br>replicaCount: 1<br>imageTag: v1.0.2</pre><pre># IST Timezone<br>commonEnvs:<br>  TZ: &quot;Asia/Kolkata&quot;</pre><pre># MySQL with Encrypted Storage<br>mysql:<br>  useExternal: false<br>  username: merico<br>  password: merico<br>  database: lake<br>  rootPassword: admin<br>  <br>  storage:<br>    type: pvc<br>    class: &quot;ebs-sc-devlake-v2&quot;  # Our encrypted StorageClass<br>    size: 50Gi<br>  <br>  resources:<br>    requests:<br>      memory: &quot;2Gi&quot;<br>      cpu: &quot;1000m&quot;<br>    limits:<br>      memory: &quot;4Gi&quot;<br>      cpu: &quot;2000m&quot;</pre><pre># Grafana Configuration<br>grafana:<br>  enabled: true<br>  adminPassword: &quot;YourSecurePassword123&quot;<br>  <br>  grafana.ini:<br>    server:<br>      serve_from_subpath: &quot;true&quot;<br>      domain: &quot;subdomain.domain&quot;<br>      root_url: &quot;%(protocol)s://%(domain)s/grafana/dora&quot;<br>  <br>  # CRITICAL: Datasource with full FQDN<br>  datasources:<br>    datasources.yaml:<br>      apiVersion: 1<br>      datasources:<br>        - name: mysql<br>          type: mysql<br>          url: devlake-mysql.default.svc.cluster.local:3306<br>          database: lake<br>          user: merico<br>          secureJsonData:<br>            password: merico<br>          jsonData:<br>            maxOpenConns: 100<br>            maxIdleConns: 100<br>            connMaxLifetime: 14400<br>          isDefault: true<br>  <br>  envFromSecrets:<br>    - name: &quot;devlake-mysql-auth&quot;<br>  <br>  env:<br>    TZ: &quot;Asia/Kolkata&quot;<br>  <br>  persistence:<br>    enabled: true<br>    storageClassName: &quot;ebs-sc-devlake-v2&quot;<br>    size: 4Gi</pre><pre># Lake Service<br>lake:<br>  encryptionSecret:<br>    secret: &quot;YOUR_ENCRYPTION_SECRET_HERE&quot;<br>    autoCreateSecret: true<br>  <br>  resources:<br>    requests:<br>      memory: &quot;1Gi&quot;<br>      cpu: &quot;500m&quot;<br>    limits:<br>      memory: &quot;2Gi&quot;<br>      cpu: &quot;1000m&quot;</pre><pre># UI Service<br>ui:<br>  basicAuth:<br>    enabled: true<br>    user: admin<br>    password: &quot;YourUIPassword123&quot;<br>    autoCreateSecret: true<br>  <br>  resources:<br>    requests:<br>      memory: &quot;256Mi&quot;<br>      cpu: &quot;250m&quot;<br>    limits:<br>      memory: &quot;512Mi&quot;<br>      cpu: &quot;500m&quot;</pre><pre>service:<br>  type: ClusterIP</pre><pre>ingress:<br>  enabled: false  # We&#39;ll create custom ingress resources</pre><h3>Step 4: Deploy with Helm</h3><pre># Add repo<br>helm repo add devlake https://apache.github.io/incubator-devlake-helm-chart<br>helm repo update</pre><pre># Install<br>helm install devlake devlake/devlake \<br>  -f values.yaml \<br>  --namespace default</pre><pre># Monitor deployment<br>kubectl get pods -w</pre><p>Expected output (all Running):</p><pre>devlake-grafana-xxx      1/1     Running   0          2m<br>devlake-lake-xxx         1/1     Running   0          2m<br>devlake-mysql-0          1/1     Running   0          2m<br>devlake-ui-xxx           1/1     Running   0          2m</pre><h3>Step 5: Verify Encrypted Volumes</h3><pre># Check PVCs<br>kubectl get pvc</pre><pre># Get volume ID<br>VOLUME_ID=$(kubectl get pv -o jsonpath=&#39;{.items[0].spec.csi.volumeHandle}&#39;)</pre><pre># Verify encryption in AWS<br>aws ec2 describe-volumes --volume-ids $VOLUME_ID \<br>  --query &#39;Volumes[0].[VolumeId,Encrypted,VolumeType,Size]&#39; \<br>  --output table</pre><pre># Should show: Encrypted = True ✅</pre><h3>Securing Access with Ingress Configuration</h3><p>One of the challenges I faced was setting up secure external access. Here’s how I configured it.</p><h3>The DevLake UI Routing Challenge</h3><p><strong>Important Discovery:</strong> DevLake UI does <strong>NOT support subpath routing</strong>.</p><p>I spent hours trying to make it work with paths like /devlake/ui or /dora/ui, checking:</p><ul><li>✅ DevLake documentation</li><li>✅ GitHub issues</li><li>✅ Community forums</li><li>✅ Source code</li></ul><p><strong>Conclusion:</strong> DevLake UI always looks for the root path, / and there&#39;s currently <strong>no way to configure subpath routing</strong>. The application is hardcoded to expect root-level routing.</p><h3>Ingress Architecture</h3><p>I implemented a two-ingress setup:</p><ol><li><strong>Grafana Ingress</strong> — Path-based routing (Grafana supports subpaths)</li><li><strong>DevLake UI Ingress</strong> — (UI requires root path)</li></ol><p><strong>Note:</strong> SSL/TLS termination is handled at the AWS Application Load Balancer level, so we don’t need to configure certificates in the ingress resources.</p><h3>Ingress Configuration for Grafana</h3><p>Grafana natively supports subpath routing with the serve_from_subpath configuration:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: dora-grafana-ingress<br>  namespace: default<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - host: subdomain.domain<br>    http:<br>      paths:<br>      - path: /grafana/dora*<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: devlake-grafana<br>            port:<br>              number: 80</pre><p><strong>Why this configuration:</strong></p><ul><li>path: /grafana/dora* - Matches /grafana/dora and everything under it</li><li>Works with Grafana’s root_url configuration in values.yaml</li><li>No TLS configuration needed (handled by ALB)</li></ul><p><strong>Access URL:</strong> <a href="https://ai-staging.ihx.in/grafana/dora">https://sub-domain.domain/grafana/dora</a></p><h3>Ingress Configuration for DevLake UI</h3><p>Since DevLake UI doesn’t support subpaths, I used subdomain routing:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: dora-ui-ingress<br>  namespace: default<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - host: subdomain.domain  # Subdomain for UI<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: devlake-ui<br>            port:<br>              number: 4000</pre><p><strong>Why this configuration:</strong></p><ul><li><strong>Subdomain routing:</strong> subdmain.domain instead of path-based</li><li><strong>Root path:</strong> UI gets / as it expects</li><li><strong>Timeout settings:</strong> Long timeout for data collection operations (can take several minutes)</li><li><strong>Port 4000:</strong> DevLake UI default port</li><li><strong>No TLS config:</strong> SSL termination handled by AWS ALB</li></ul><p><strong>Access URL:</strong> https://subdomain.domain</p><p><strong>Critical Note:</strong> This is the only way to expose DevLake UI externally. Path-based routing like /dora/ui will <strong>NOT work</strong> - the UI will show a blank page or errors because it&#39;s hardcoded to expect requests at the root path.</p><h3>Apply Ingress Resources</h3><pre># Apply Grafana ingress<br>kubectl apply -f dora-grafana-ingress.yaml</pre><pre># Apply UI ingress<br>kubectl apply -f dora-ui-ingress.yaml</pre><pre># Verify ingresses<br>kubectl get ingress</pre><pre># Check NGINX controller logs if issues<br>kubectl logs -n ingress-nginx deploy/ingress-nginx-controller</pre><h3>DNS Configuration</h3><h3>Add DNS Records</h3><p>Add these DNS records in your DNS provider, pointing to the LoadBalancer address:</p><p><strong>For Grafana (path-based):</strong></p><pre>Type: CNAME<br>Name: subdomain.domain<br>Path: /grafana/dora*<br>Value: &lt;LOAD_BALANCER_DNS&gt;<br>TTL: 300</pre><p><strong>For DevLake UI (subdomain):</strong></p><pre>Type: CNAME<br>Name: subdomain.domain<br>Value: &lt;LOAD_BALANCER_DNS&gt;<br>TTL: 300</pre><p><strong>Note:</strong> Since SSL termination is handled at the AWS Application Load Balancer level, ensure your ALB is configured with the appropriate SSL certificate for both domains (subdomain.domain)</p><h3>Verify DNS and Access</h3><pre># Test DNS resolution<br>nslookup subdomain.domain</pre><pre># Both should resolve to the LoadBalancer address</pre><pre># Test access (use https since ALB handles SSL)<br>curl -I https://subdomain.domain <br># Should return: HTTP 200 OK or redirect to login</pre><h3>The Grafana Connection Issue I Solved</h3><h3>Problem</h3><p>After deployment, Grafana dashboards showed “No data”:</p><pre>db query error: dial tcp 127.0.0.1:3306: connect: connection refused</pre><h3>Root Cause</h3><p>The default Grafana datasource configuration was trying to connect to localhost:3306, but MySQL runs in a separate pod!</p><h3>Solution</h3><p>I had to explicitly configure the datasource with the <strong>full Kubernetes service FQDN</strong>:</p><pre>grafana:<br>  datasources:<br>    datasources.yaml:<br>      apiVersion: 1<br>      datasources:<br>        - name: mysql<br>          type: mysql<br>          url: devlake-mysql.default.svc.cluster.local:3306  # Not 127.0.0.1!<br>          database: lake<br>          user: merico<br>          secureJsonData:<br>            password: merico</pre><p>Then upgrade:</p><pre>helm upgrade devlake devlake/devlake -f values.yaml</pre><p><strong>Pro tip:</strong> Always use &lt;service&gt;.&lt;namespace&gt;.svc.cluster.local for inter-pod communication in Kubernetes.</p><h3>The Password Management Headache</h3><h3>What Happened</h3><p>I initially tried changing the MySQL password after installation. Big mistake! It broke everything:</p><pre>Error 1045: Access denied for user &#39;merico&#39;</pre><h3>Why It’s Complicated</h3><p>The password exists in multiple places:</p><ol><li>MySQL user database</li><li>Kubernetes secret (devlake-mysql-auth)</li><li>Grafana datasource configuration</li><li>Lake service connection string</li></ol><p>Changing one without updating all causes authentication failures.</p><h3>My Solution</h3><p>Since we had no production data yet, I did a <strong>clean reinstall</strong>:</p><pre># 1. Uninstall completely<br>helm uninstall devlake</pre><pre># 2. Delete PVC (THIS DELETES ALL DATA!)<br>kubectl delete pvc devlake-mysql-data-devlake-mysql-0 devlake-grafana</pre><pre># 3. Delete secrets<br>kubectl delete secret devlake-mysql-auth</pre><pre># 4. Update values.yaml with consistent password everywhere</pre><pre># 5. Fresh install<br>helm install devlake devlake/devlake -f values.yaml</pre><p><strong>Lesson learned:</strong> Keep the default password (merico) during initial setup. Change it only if necessary, and plan for downtime.</p><h3>Integrating with Jenkins</h3><p>As the DevOps engineer managing our Jenkins infrastructure, this integration was straightforward:</p><h3>Steps I Followed:</h3><ol><li><strong>Access DevLake UI via subdomain:</strong></li></ol><ul><li>https://subdomain.domain</li></ul><p><strong>2. Add Jenkins Connection:</strong></p><ul><li>Connections → Add Connection → Jenkins</li><li>Connection Name: jenkins-stage</li><li>Endpoint: https://jenkins-url/</li><li>Username: my Jenkins admin user</li><li>Token: Generated from Jenkins → User → Configure → API Token</li></ul><p><strong>3. Add Data Scopes:</strong> I selected 20+ Jenkins jobs, including:</p><ul><li>job-1</li><li>job-2</li><li>job-3</li><li>And many more…</li></ul><p><strong>4. Create Scope Config:</strong></p><ul><li>Name: jenkins-jobs</li><li>Data Entities: <strong>CI/CD</strong></li><li>This enables DORA metrics calculation</li></ul><p><strong>5. Create Project:</strong></p><ul><li>Projects → New Project → project-1</li><li>Click “+ Add a Connection”</li><li>Select jenkins-stage</li><li>Select data scopes</li><li>Click “Collect Data”</li></ul><p><strong>Important:</strong> Just creating a connection doesn’t collect data! You must:</p><ol><li>Create project</li><li>Add connection to project</li><li>Trigger “Collect Data”</li></ol><h3>Integrating with GitHub</h3><h3>Security First</h3><p>I created a dedicated GitHub bot account with read-only access:</p><ol><li>Created service account: devlake-metrics-bot</li><li>Generated Personal Access Token with scopes:</li></ol><ul><li>repo (for private repos)</li><li>read:org</li></ul><ol><li>Set 90-day expiration</li></ol><p><strong>Why a bot account?</strong></p><ul><li>Easy to revoke if compromised</li><li>Doesn’t depend on individual users</li><li>Clear audit trail</li><li>Follows the principle of least privilege</li></ul><h3>Configuration:</h3><ol><li><strong>Add GitHub Connection:</strong></li></ol><ul><li>Connection Name: github-prod</li><li>Endpoint: <a href="https://api.github.com/">https://api.github.com</a></li><li>Token: Service account PAT</li></ul><p><strong>2. Add Repositories:</strong> Selected all our active repos</p><p><strong>3. Create Scope Config:</strong></p><ul><li>Name: github</li><li>Data Entities (selected all):</li><li>Source Code Management</li><li>Issue Tracking</li><li>Code Review</li><li>Cross Domain</li><li>CI/CD</li></ul><p><strong>4. Transformation Settings:</strong></p><ul><li><strong>CI/CD Deployment:</strong> Unchecked (we use Jenkins)</li><li><strong>Code Review:</strong> Default regex patterns</li><li><strong>Cross-domain:</strong> Default (links PRs to Issues via “fixes #123”)</li></ul><p><strong>5. Add to Project:</strong></p><ul><li>Added to the same gcp project with Jenkins</li><li>Triggered collection</li><li>Waited ~10 minutes</li></ul><h3>Verifying Everything Works</h3><h3>Check Data in MySQL:</h3><pre>kubectl exec -it devlake-mysql-0 -- mysql -u merico -pmerico lake</pre><pre># In MySQL:<br>SELECT COUNT(*) as jenkins_builds FROM cicd_pipelines;<br>SELECT COUNT(*) as git_commits FROM commits;<br>SELECT COUNT(*) as pull_requests FROM pull_requests;</pre><pre># Expected:<br># jenkins_builds: 100+<br># git_commits: 1000+<br># pull_requests: 50+</pre><h3>Check Grafana Dashboards:</h3><ol><li>Access: <a href="https://ai-staging.ihx.in/grafana/dora">https://subdomain.domain/grafana/dora</a></li><li>Login with admin credentials</li><li>Browse → Dashboards</li><li>Open “DORA Dashboard”</li></ol><p>You should see:</p><ul><li>Deployment Frequency chart</li><li>Lead Time for Changes</li><li>Change Failure Rate</li><li>Time to Restore Service</li></ul><h3>My Troubleshooting Playbook</h3><h3>Issue 1: Pods Stuck in ContainerCreating</h3><p><strong>Cause:</strong> EBS volume encryption mismatch</p><p><strong>Fix:</strong></p><pre># Check if nodes are encrypted<br>kubectl describe node &lt;node-name&gt; | grep -i encrypt</pre><pre># Use encrypted StorageClass with proper KMS key<br># See Step 1 above</pre><h3>Issue 2: Grafana Shows “No Data”</h3><p><strong>Cause:</strong> Wrong datasource URL or time range</p><p><strong>Fix:</strong></p><pre># 1. Verify datasource uses FQDN<br># 2. Check data exists<br>kubectl exec -it devlake-mysql-0 -- mysql -u merico -pmerico lake -e &quot;SELECT COUNT(*) FROM cicd_pipelines;&quot;</pre><pre># 3. In Grafana, change time range from &quot;Last 30 min&quot; to &quot;Last 30 days&quot;</pre><h3>Issue 3: Data Not Collecting</h3><p><strong>Cause:</strong> Connection not added to the project</p><p><strong>Fix:</strong></p><ol><li>DevLake UI → Projects → Your Project</li><li>Configuration tab</li><li>Check the “Data Connections” section</li><li>If empty, click “+ Add a Connection”</li><li>Select your connections</li><li>Click “Collect Data”</li></ol><h3>Additional Security Hardening</h3><h3>1. Enable Basic Auth on Ingress (Optional Extra Layer)</h3><pre># Create basic auth secret<br>htpasswd -c auth devops<br># Enter password when prompted</pre><pre>kubectl create secret generic basic-auth \<br>  --from-file=auth \<br>  --namespace default</pre><pre># Add annotation to ingress<br># nginx.ingress.kubernetes.io/auth-type: basic<br># nginx.ingress.kubernetes.io/auth-secret: basic-auth<br># nginx.ingress.kubernetes.io/auth-realm: &#39;Authentication Required&#39;</pre><h3>Key Takeaways from This Project</h3><h3>1. The Encryption Discovery</h3><p><strong>Problem:</strong> Spent 4–5 hours debugging why PVCs wouldn’t attach <br><strong>Solution:</strong> Added encrypted: &quot;true&quot; and the KMS key to the StorageClass <br><strong>Lesson:</strong> EKS node encryption requires PVC encryption with a compatible KMS key</p><h3>2. Documentation Gaps</h3><p><strong>Where AI failed:</strong> ChatGPT gave generic answers <br><strong>Where Google helped:</strong> Specific AWS blogs and GitHub issues <br><strong>Lesson:</strong> For platform-specific issues, community resources &gt; AI tools</p><h3>3. Kubernetes Networking</h3><p><strong>Problem:</strong> Grafana couldn’t connect to MySQL <br><strong>Solution:</strong> Use full FQDN, not localhost <br><strong>Lesson:</strong> Never use 127.0.0.1 for cross-pod communication</p><h3>4. The DevLake UI Routing Limitation</h3><p><strong>Problem:</strong> Spent hours trying to configure subpath routing <br><strong>Discovery:</strong> DevLake UI does NOT support subpath routing (e.g., /dora/ui) <strong>Solution:</strong> Use subdomain-based routing (e.g., subdomain.domain) <br><strong>Lesson:</strong> Check application capabilities before designing ingress architecture</p><h3>5. SSL Termination at ALB</h3><p><strong>Approach:</strong> Instead of managing certificates in Kubernetes, we handle SSL at the AWS ALB level. <br><strong>Benefits:</strong></p><ul><li>Centralized certificate management</li><li>Better performance (TLS offloading)</li><li>Easier certificate renewal<br>Lesson<strong>:</strong> Use cloud-native features when available</li></ul><h3>6. The “Add Connection” Trap</h3><p><strong>Problem:</strong> Created connections, but no data<br><strong>Solution:</strong> Must add connections to the project AND trigger collection.<br><strong>Lesson:</strong> Creating ≠ Collecting</p><h3>7. Password Changes Are Hard</h3><p><strong>Problem:</strong> Changing the password broke the authentication <br><strong>Solution:</strong> Fresh reinstall (data loss acceptable in our case) <br><strong>Lesson:</strong> Plan passwords before deployment</p><h3>My DevOps Checklist for DevLake</h3><p><strong>Pre-deployment:</strong></p><ul><li>[ ] Check if EKS nodes are encrypted</li><li>[ ] Get KMS key ARN from the security team</li><li>[ ] Create StorageClass with encryption</li><li>[ ] Verify EBS CSI Driver is running</li><li>[ ] Plan MySQL password (don’t change later!)</li><li>[ ] Decide storage sizes (50GB MySQL, 4GB Grafana)</li><li>[ ] Generate and store encryption secret</li><li>[ ] Plan DNS strategy (subdomain for UI, path for Grafana)</li><li>[ ] Verify ALB has SSL certificates configured</li></ul><p><strong>Post-deployment:</strong></p><ul><li>[ ] All pods running</li><li>[ ] PVCs Bound to encrypted volumes</li><li>[ ] Verify volumes encrypted with the correct KMS key</li><li>[ ] Grafana connects to MySQL</li><li>[ ] Configure ingress resources</li><li>[ ] Add DNS records pointing to LoadBalancer</li><li>[ ] Verify SSL works (handled by ALB)</li><li>[ ] Test HTTPS access to both URLs</li><li>[ ] Test data collection from Jenkins</li><li>[ ] Test data collection from GitHub</li><li>[ ] Verify DORA dashboards showing data</li><li>[ ] Set up monitoring alerts</li><li>[ ] Document access URLs for the team</li><li>[ ] Create runbook for common issues</li></ul><h3>Complete Access Summary</h3><p>After completing the setup, here’s how to access everything:</p><p>Service URL Authentication Notes <br><strong>DevLake UI</strong> https://subdomain.domain Basic Auth (admin/password) Must use subdomain, no subpath support <br><strong>Grafana</strong> https://subdomain.domain/grafana/dora Grafana Auth (admin/password) Supports subpath routing <br> <strong>Jenkins</strong> https://jenkins-url Jenkins Auth Data source for CI/CD metrics <strong>GitHub</strong> https://github.com OAuth Token Data source for code metrics</p><p><strong>Security layers:</strong></p><ol><li>✅ HTTPS/TLS encryption (handled by AWS ALB)</li><li>✅ Application-level authentication</li><li>✅ (Optional) NGINX basic auth</li><li>✅ (Optional) IP whitelisting</li><li>✅ KMS-encrypted persistent volumes</li></ol><p>Jenkins:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvStHwuW16wqp5oHYmPdYA.png" /></figure><p>Github:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ON10plGKq5u-Lr4LpxJovQ.png" /></figure><h3>Resources That Actually Helped Me</h3><p>When I was stuck, these were invaluable:</p><p><strong>Official Docs:</strong></p><ul><li>AWS EBS CSI Driver Parameters: <a href="https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/parameters.md">https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/parameters.md</a></li><li>Kubernetes Ingress NGINX: <a href="https://kubernetes.github.io/ingress-nginx/">https://kubernetes.github.io/ingress-nginx/</a></li><li>EKS Best Practices: <a href="https://aws.github.io/aws-eks-best-practices/security/docs/data/">https://aws.github.io/aws-eks-best-practices/security/docs/data/</a></li><li>Apache DevLake: <a href="https://devlake.apache.org/">https://devlake.apache.org</a></li></ul><p><strong>Google Search Terms That Worked:</strong></p><ul><li>“EKS encrypted nodes PVC not attaching”</li><li>“AWS EBS CSI driver encrypted volumes StorageClass”</li><li>“Kubernetes FailedMount encrypted node”</li><li>“DevLake Grafana no data MySQL connection”</li><li>“NGINX ingress subdomain routing”</li><li>“DevLake UI subpath configuration” (learned it’s not supported!)</li></ul><h3>Conclusion</h3><p>As the sole DevOps engineer implementing DORA metrics, this project taught me valuable lessons about AWS EKS, Kubernetes storage, ingress routing, and the importance of community resources over AI tools when debugging infrastructure issues.</p><p>The journey from stuck pods to fully functional DORA dashboards with secure external access took patience and systematic troubleshooting. Key challenges included:</p><ol><li><strong>Encryption issue</strong> — 4–5 hours debugging, fixed with proper KMS configuration in StorageClass</li><li><strong>Grafana connectivity</strong> — Solved with proper FQDN configuration</li><li><strong>Ingress routing</strong> — Discovered DevLake UI’s limitation with subpaths, used subdomain routing</li><li><strong>DNS and SSL</strong> — Configured DNS records, SSL handled by AWS ALB</li></ol><p>Today, we’re successfully tracking DORA metrics for 20+ Jenkins jobs and multiple GitHub repositories, accessible securely via:</p><ul><li>https://subdomain.domain (DevLake UI)</li><li>https://subdomain.domain/grafana/dora (Grafana Dashboards)</li></ul><p>The insights have already helped our team identify bottlenecks in our deployment pipeline and improve our deployment frequency.</p><p><strong>My advice to fellow DevOps engineers:</strong></p><ul><li>When you hit infrastructure issues, Google will provide specific error terms.</li><li>Read community blogs and GitHub issues — they’re more helpful than AI for platform-specific problems</li><li>Understand application routing capabilities before designing ingress (DevLake UI doesn’t support subpaths!)</li><li>Always verify encryption requirements in your infrastructure</li><li>Leverage cloud-native features like ALB SSL termination</li><li>Test DNS and SSL thoroughly before announcing to the team</li><li>Document everything — your future self will thank you</li></ul><h3>Tags</h3><p>#DevOps #DORA #Metrics #Kubernetes #AWS #EKS #ApacheDevLake #SeniorEngineer #Infrastructure #Jenkins #GitHub #Ingress #NGINX #RealWorldExperience #Encryption</p><p><em>If this helped you solve a similar issue, please don&#39;t hesitate to connect! Questions about the implementation? </em><a href="http://linkedin.com/in/sidhu-sangani-34a8511a9"><em>sidhu.sangani</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af3a5bf096da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Observability with Prometheus, Exporters, Stackdriver, and Grafana-v1]]></title>
            <link>https://medium.com/@sidhusangani/end-to-end-observability-with-prometheus-exporters-stackdriver-and-grafana-v1-d54402118d0e?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54402118d0e</guid>
            <category><![CDATA[gcp-logging]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[gcp-monitoring]]></category>
            <category><![CDATA[black-box]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 05:12:15 GMT</pubDate>
            <atom:updated>2025-10-13T05:13:04.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Observability with Prometheus, Exporters, Stackdriver, and Grafana📊</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXNyfqi85TRCrEm5RVn_yg.png" /></figure><p>It was a calm Tuesday morning — coffee in hand, brain in airplane mode, pretending I had my life together. And then team dropped the nuclear line: “We need one dashboard to monitor <em>everything</em> — APIs, Kubernetes, databases, Pub/Sub, uptime, load balancers… everything.” My first reaction?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*fpUV67LpFmVQnBcSDKavrw.gif" /></figure><p>The reason is that it requires more manual effort and fine-tuning initially.</p><p>Back then, our setup was pure chaos. Kubernetes metrics lived in one tab, Pub/Sub in another, load balancer data was buried somewhere inside GCP’s Bermuda Triangle, and databases? Probably chilling in an Excel sheet from 2019. Every incident turned me into a professional tab switcher — like an Olympic athlete doing a 100m dash between Chrome windows. Client calls were a nightmare. “API down?” they’d ask. And there I was, scrolling through logs, Stackdriver, Grafana (vaguely open in another tab), and maybe crying a little inside. By the time I figured out the root cause, my coffee was cold and my patience had rage quit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_63K-t_dRf-4HXbkHT2Vnw.png" /></figure><p>After surviving countless YouTube tutorials, a few Stack Overflow pilgrimages, and at least two “why isn’t this port scraping?” meltdowns, enlightenment struck. I needed a dream team — my very own <em>Monitoring Avengers.</em> Grafana became the Tony Stark of the group — stylish, powerful, and slightly dramatic. Prometheus was the quiet genius, collecting metrics in the background like an underappreciated intern. Blackbox Exporter joined as the overprotective parent, constantly checking if APIs were still breathing. Windows Exporter showed up because, of course, that one legacy server still hadn’t retired. GCP Logging and Stackdriver arrived late to the party but brought the cloud magic — Pub/Sub metrics, load balancer data, database insights — everything the others couldn’t touch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1QmFEK4LvIenkyMn0uLjA.png" /></figure><p>And just like that, the chaos had structure. One dashboard to rule them all. No more tab-switching cardio, no more guessing which service ghosted us this time. Every problem, every spike, every outage — visible in seconds. My coffee stayed hot, my confidence level went from mild panic to “mass,” and peace was restored.</p><p><strong>Setting Up Grafana: The Canvas for Our Monitoring Masterpiece🎨</strong></p><h3>Setting Up Grafana: The Canvas for Our Monitoring Masterpiece</h3><h3>Why Grafana?</h3><p>Let’s be honest — data without visualization is like biryani without raita. You can consume it, but it’s not a pleasant experience. Grafana is our visualization powerhouse, the place where raw metrics transform into beautiful, understandable dashboards that even non-technical stakeholders can appreciate. Think of it as the frontend of our monitoring stack — while Prometheus and other tools do the heavy lifting in the background, Grafana makes everything look good and accessible.</p><p>The beauty of Grafana lies in its flexibility. Whether you’re pulling data from Prometheus, GCP Stackdriver, or directly from databases, Grafana doesn’t discriminate. It plays well with everyone. Plus, it’s open-source, widely supported, and has a massive community. <em>Translation: when you’re stuck at 2 AM, there’s probably a Stack Overflow answer or GitHub issue waiting to save you.</em></p><h3>Deploying Grafana on Kubernetes</h3><p>Since we’re running everything on Kubernetes (because who doesn’t love container orchestration?), I deployed Grafana as a pod. This gives us the flexibility to scale, manage, and integrate it seamlessly with our existing infrastructure.</p><p><strong>Here’s the complete setup:</strong></p><h4>1. StorageClass for Persistent Storage</h4><p>First, we need a StorageClass to provision persistent volumes. I’m using GCP’s SSD persistent disks for better performance.</p><pre>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: grafana-sc<br>provisioner: pd.csi.storage.gke.io<br>parameters:<br>  type: pd-ssd<br>  replication-type: none<br>volumeBindingMode: WaitForFirstConsumer<br>reclaimPolicy: Delete<br>allowVolumeExpansion: true</pre><h4>2. PersistentVolumeClaim</h4><p>This ensures Grafana’s data (dashboards, configurations, etc.) survives pod restarts.</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: grafana-pvc<br>  namespace: default<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  storageClassName: grafana-sc<br>  resources:<br>    requests:<br>      storage: 1Gi</pre><h4>3. Grafana Deployment</h4><p>The main deployment configuration. Notice the security context settings and resource requests — these are important for production stability.</p><p><strong>IMPORTANT:</strong> The serviceAccountName is critical here. This service account needs proper IAM permissions to access Google Cloud Monitoring and Google Cloud Logging. Without these permissions, Grafana won&#39;t be able to fetch metrics from GCP Stackdriver. Make sure your service account has the following roles:</p><ul><li>roles/monitoring.viewer (to read Cloud Monitoring metrics)</li><li>roles/logging.viewer (to read Cloud Logging data)</li></ul><p>You can use the default service account or create a dedicated one with these permissions.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    app: grafana<br>  name: grafana<br>  namespace: default<br>spec:<br>  selector:<br>    matchLabels:<br>      app: grafana<br>  template:<br>    metadata:<br>      labels:<br>        app: grafana<br>    spec:<br>      serviceAccountName: default  # Replace with your service account that has GCP permissions<br>      securityContext:<br>        fsGroup: 472<br>        supplementalGroups:<br>          - 0<br>      containers:<br>        - name: grafana<br>          image: grafana/grafana:latest<br>          imagePullPolicy: IfNotPresent<br>          ports:<br>            - containerPort: 3000<br>              name: http-grafana<br>              protocol: TCP<br>          readinessProbe:<br>            failureThreshold: 3<br>            httpGet:<br>              path: /robots.txt<br>              port: 3000<br>              scheme: HTTP<br>            initialDelaySeconds: 10<br>            periodSeconds: 30<br>            successThreshold: 1<br>            timeoutSeconds: 2<br>          livenessProbe:<br>            failureThreshold: 3<br>            initialDelaySeconds: 30<br>            periodSeconds: 10<br>            successThreshold: 1<br>            tcpSocket:<br>              port: 3000<br>            timeoutSeconds: 1<br>          resources:<br>            requests:<br>              cpu: 250m<br>              memory: 750Mi<br>          volumeMounts:<br>            - mountPath: /var/lib/grafana<br>              name: grafana-pv<br>      volumes:<br>        - name: grafana-pv<br>          persistentVolumeClaim:<br>            claimName: grafana-pvc</pre><h4>4. Service Configuration</h4><p>Exposing Grafana internally within the cluster using ClusterIP. You can expose it via Ingress or LoadBalancer based on your requirements.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: grafana<br>  namespace: default<br>spec:<br>  ports:<br>    - port: 3000<br>      protocol: TCP<br>      targetPort: http-grafana<br>  selector:<br>    app: grafana<br>  sessionAffinity: None<br>  type: ClusterIP</pre><h3>Deploying Everything</h3><p>Apply all these configurations in order:</p><pre>kubectl apply -f grafana-storageclass.yaml<br>kubectl apply -f grafana-pvc.yaml<br>kubectl apply -f grafana-deployment.yaml<br>kubectl apply -f grafana-service.yaml</pre><p>Check if Grafana is running:</p><pre>kubectl get pods -l app=grafana<br>kubectl get svc grafana</pre><h3>Accessing Grafana</h3><p>Once the pod is running on GKE, I made it accessible using an Ingress via the GKE Ingress Controller.</p><p><strong>Default credentials:</strong></p><ul><li>Username: admin</li><li>Password: admin</li></ul><p><em>Change this password immediately. Seriously. Right now. I’ll wait.</em></p><p><strong>Optional: Keycloak Integration for SSO</strong></p><p>For enterprise-grade authentication with Single Sign-On (SSO), I integrated Grafana with Keycloak. This allows team members to use their existing organizational credentials instead of managing separate Grafana passwords.</p><p>If you want to set up Keycloak integration (highly recommended for production), check out this detailed guide: <a href="https://medium.com/@sidhusangani/keycloak-integration-with-grafana-eded24f73c2f">Keycloak Integration with Grafana</a></p><p><strong>What’s Next?</strong></p><p>At this point, Grafana is deployed and ready, but it’s just an empty canvas waiting for data. <em>Like a brand new whiteboard in a conference room — full of potential but currently useless.</em></p><p><strong>Next up:</strong> Setting up Prometheus to collect all those juicy metrics that Grafana will transform into beautiful visualizations. Because dashboards without data are just… well, sad empty screens.</p><h3>Setting Up Prometheus: The Metric Collection Engine ⚙️</h3><h3>Why Prometheus?</h3><p>If Grafana is the pretty face of our monitoring stack, Prometheus is the hardworking brain behind it. Prometheus is a time-series database and monitoring system that excels at collecting, storing, and querying metrics. It scrapes metrics from configured targets at regular intervals, stores them efficiently, and makes them available for visualization tools like Grafana.</p><p>The beauty of Prometheus lies in its pull-based model — instead of applications pushing metrics, Prometheus actively scrapes them from exporters. This makes the architecture cleaner and more reliable. Plus, it has excellent support for Kubernetes service discovery, making it perfect for our dynamic containerized environment.</p><h3>Setting Up Prometheus: The Metric Collection Engine ⚙️</h3><p>If Grafana is the pretty face of our monitoring stack, Prometheus is the hardworking brain behind it. Prometheus is a time-series database and monitoring system that excels at collecting, storing, and querying metrics. It scrapes metrics from configured targets at regular intervals, stores them efficiently, and makes them available for visualization tools like Grafana.</p><p>The beauty of Prometheus lies in its pull-based model — instead of applications pushing metrics, Prometheus actively scrapes them from exporters. This makes the architecture cleaner and more reliable. Plus, it has excellent support for Kubernetes service discovery, making it perfect for our dynamic containerized environment.</p><h3>Step-by-Step Prometheus Installation</h3><h4>Step 1: Add Prometheus Helm Repository</h4><p>First, let’s search for available Prometheus charts:</p><pre>helm search hub prometheus</pre><p>Add the Prometheus Community Helm repository:</p><pre>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts</pre><p>Verify the repository was added:</p><pre>helm repo list</pre><p>Update your Helm repositories to get the latest charts:</p><pre>helm repo update</pre><h4>Step 2: Create Monitoring Namespace</h4><pre>kubectl create namespace monitoring</pre><h4>Step 3: Download Prometheus Chart</h4><p>Create a working directory and download the Prometheus chart:</p><pre>mkdir grafana-prometheus-monitoring<br>cd grafana-prometheus-monitoring<br>helm pull prometheus-community/prometheus</pre><pre>tar -zxvf prometheus-*.tgz<br>cd prometheus/</pre><h4>Step 4: Create StorageClass for Prometheus</h4><p>Create a file named storage-class-prometheus.yaml:</p><p>yaml</p><pre>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: prometheus-sc<br>provisioner: pd.csi.storage.gke.io<br>parameters:<br>  type: pd-ssd<br>  replication-type: none<br>volumeBindingMode: WaitForFirstConsumer<br>reclaimPolicy: Delete<br>allowVolumeExpansion: true</pre><p>Apply the StorageClass:</p><pre>kubectl apply -f storage-class-prometheus.yaml -n monitoring</pre><h4>Step 5: Create PersistentVolumeClaim</h4><p>Create a file named prometheus-persistent-volume-claim.yaml:</p><p>yaml</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: prometheus-pvc<br>  namespace: monitoring  <br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  storageClassName: prometheus-sc<br>  resources:<br>    requests:<br>      storage: 10Gi</pre><p>Apply the PVC:</p><pre>kubectl apply -f prometheus-persistent-volume-claim.yaml -n monitoring</pre><p>Verify the StorageClass and PVC are created:</p><pre>kubectl get sc<br>kubectl get pvc -n monitoring</pre><p>You should see output like:</p><pre>NAME             STATUS    VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS     AGE<br>prometheus-pvc   Pending                                      prometheus-sc    10s</pre><p><em>Note: PVC will remain in “Pending” state until a pod claims it (WaitForFirstConsumer mode).</em></p><h4>Step 6: Configure Prometheus Values</h4><p>Open the values.yaml file in the prometheus directory:</p><p>bash</p><pre>vi values.yaml</pre><p>Find the server section and modify the persistence settings:</p><pre>server:<br>  persistentVolume:<br>    enabled: true<br>    storageClass: &quot;prometheus-sc&quot;<br>    existingClaim: &quot;prometheus-pvc&quot;<br>    accessModes:<br>      - ReadWriteOnce<br>    size: 10Gi<br>  <br>  retention: &quot;15d&quot;  # Adjust retention period as needed</pre><p>Save and close the file.</p><h4>Step 7: Install Prometheus using Helm</h4><p>Now install Prometheus with your custom values:</p><pre>helm install prometheus prometheus-community/prometheus \<br>  -f values.yaml \<br>  --namespace monitoring</pre><h4>Step 8: Verify Prometheus Installation</h4><p>Check if all Prometheus pods are running:</p><pre>kubectl get pods -n monitoring</pre><p>You should see pods like:</p><pre>NAME                                             READY   STATUS    RESTARTS   AGE<br>prometheus-server-xxxxxxxxxx-xxxxx               2/2     Running   0          2m<br>prometheus-kube-state-metrics-xxxxxxxxxx-xxxxx   1/1     Running   0          2m<br>prometheus-node-exporter-xxxxx                   1/1     Running   0          2m<br>prometheus-alertmanager-xxxxxxxxxx-xxxxx         1/1     Running   0          2m</pre><p>Check the services:</p><pre>kubectl get svc -n monitorin</pre><p>Check PVC status (should now be “Bound”):</p><pre>kubectl get pvc -n monitoring</pre><p><strong>Adding Prometheus as a Data Source in Grafana</strong></p><p>Now that both Grafana and Prometheus are running, let’s connect them:</p><p><strong>Step 1:</strong> Access your Grafana pod</p><p><strong>Step 2:</strong> Login to Grafana and navigate to: Configuration → Data Sources → Add data source</p><p><strong>Step 3:</strong> Select <strong>Prometheus</strong></p><p><strong>Step 4:</strong> Configure the data source:</p><ul><li><strong>Name:</strong> Prometheus</li><li><strong>URL:</strong> http://prometheus-server.monitoring.svc.cluster.local:80 <em>(Internal Kubernetes service URL for cluster communication)</em></li><li><strong>Access:</strong> Server (default)</li></ul><p><strong>Step 5:</strong> Scroll down and click <strong>Save &amp; Test</strong></p><p>You should see: <em>“Data source is working”</em> ✅</p><h3>What’s Next?</h3><p>Prometheus is now collecting basic Kubernetes metrics:</p><ul><li>✅ Node metrics (CPU, memory, disk)</li><li>✅ Kubernetes cluster state</li><li>✅ Grafana connected to Prometheus</li></ul><p><em>But we’re just getting started.</em> Next, we need Blackbox Exporter to monitor API endpoints, because a running pod doesn’t guarantee the API is responding. <em>Trust me, learned this at 3 AM the hard way!</em></p><p><strong>Ready for the Blackbox Exporter setup, bro?</strong> 🚀</p><h3>Why Blackbox Exporter?</h3><p>Remember when I said a running pod doesn’t guarantee your API is actually working? This is where Blackbox Exporter comes to the rescue. While Prometheus with node-exporter and kube-state-metrics tells us about infrastructure health (CPU, memory, pod status), Blackbox Exporter answers the real question: <strong>“Is my endpoint actually responding to requests?”</strong></p><p>Think of it as your 24/7 API stalker — it continuously probes your HTTP/HTTPS endpoints, TCP services, DNS, and ICMP targets to verify they’re alive and responding correctly. This is crucial for:</p><ul><li><strong>Monitoring our own APIs</strong> — Are they returning HTTP 200? What’s the response time?</li><li><strong>Monitoring client APIs</strong> — When clients ask “Is your integration down?”, we have receipts</li><li><strong>Uptime tracking</strong> — Calculate actual uptime percentages with real data</li><li><strong>SSL certificate monitoring</strong> — Get alerts before certificates expire</li></ul><p>The beauty of Blackbox Exporter is that it monitors from the outside-in. It doesn’t care what’s happening inside your application — it just checks if the endpoint responds like a real user would expect. <em>Perfect for catching those “pod is running but service is broken” scenarios that haunt DevOps engineers at 3 AM.</em></p><h3>Deploying Blackbox Exporter on Kubernetes</h3><p>We’ll deploy Blackbox Exporter with a custom configuration to probe HTTP endpoints.</p><h4>Understanding the Configuration</h4><p>The ConfigMap defines how Blackbox Exporter should probe endpoints. Our http_2xx module:</p><ul><li><strong>Prober type:</strong> HTTP/HTTPS</li><li><strong>Timeout:</strong> 10 seconds (adjust based on your API response times)</li><li><strong>Valid status codes:</strong> 200 (customize if you need to check for 201, 204, etc.)</li><li><strong>Method:</strong> GET (can be changed to POST, PUT, etc.)</li><li><strong>SSL handling:</strong> Accepts both HTTP and HTTPS</li></ul><p>You can add more modules for different probe types (TCP, ICMP, DNS) as needed.</p><h4>Complete Blackbox Exporter Deployment</h4><p>Create a file named blackbox-exporter.yaml:</p><pre>---<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: blackbox-exporter-config<br>  namespace: monitoring<br>  labels:<br>    app: blackbox-exporter<br>data:<br>  blackbox.yml: |<br>    modules:<br>      http_2xx:<br>        prober: http<br>        timeout: 10s<br>        http:<br>          valid_http_versions: [&quot;HTTP/1.1&quot;, &quot;HTTP/2.0&quot;]<br>          valid_status_codes: [200]<br>          method: GET<br>          no_follow_redirects: false<br>          preferred_ip_protocol: &quot;ip4&quot;<br>          fail_if_ssl: false<br>          fail_if_not_ssl: false<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: blackbox-exporter<br>  namespace: monitoring<br>  labels:<br>    app: blackbox-exporter<br>spec:<br>  type: ClusterIP<br>  ports:<br>    - name: http<br>      port: 9115<br>      protocol: TCP<br>      targetPort: 9115<br>  selector:<br>    app: blackbox-exporter<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: blackbox-exporter<br>  namespace: monitoring<br>  labels:<br>    app: blackbox-exporter<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: blackbox-exporter<br>  template:<br>    metadata:<br>      labels:<br>        app: blackbox-exporter<br>    spec:<br>      containers:<br>      - name: blackbox-exporter<br>        image: prom/blackbox-exporter:v0.24.0<br>        ports:<br>        - containerPort: 9115<br>          name: http<br>        args:<br>          - --config.file=/config/blackbox.yml<br>        volumeMounts:<br>        - name: config<br>          mountPath: /config<br>        resources:<br>          limits:<br>            memory: 256Mi<br>            cpu: 200m<br>          requests:<br>            memory: 128Mi<br>            cpu: 100m<br>        livenessProbe:<br>          httpGet:<br>            path: /health<br>            port: http<br>          initialDelaySeconds: 10<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /health<br>            port: http<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>      volumes:<br>      - name: config<br>        configMap:<br>          name: blackbox-exporter-config</pre><h4>Deploy Blackbox Exporter</h4><pre>kubectl apply -f blackbox-exporter.yaml -n monitoring</pre><p>Verify the deployment:</p><pre>kubectl get pods -n monitoring | grep blackbox<br>kubectl get svc -n monitoring | grep blackbox</pre><p>You should see the blackbox-exporter pod running:</p><pre>NAME                                 READY   STATUS    RESTARTS   AGE<br>blackbox-exporter-xxxxxxxxxx-xxxxx   1/1     Running   0          30s</pre><p>You should see metrics like:</p><pre>probe_success 1<br>probe_http_status_code 200<br>probe_duration_seconds 0.234</pre><p><em>If </em><em>probe_success is 1, congratulations! Your API stalker is working.</em> 🎉</p><h3>What’s Next?</h3><p>Blackbox Exporter is deployed, but it’s not monitoring anything yet. We need to:</p><ol><li>Configure Prometheus to scrape Blackbox Exporter</li><li>Tell Prometheus which endpoints to monitor (our APIs, client APIs, load balancers)</li><li>Create Grafana dashboards to visualize uptime and response times</li></ol><p><em>Think of it this way: we just hired a security guard (Blackbox Exporter), but we haven’t told him which doors to watch yet. That’s coming next!</em></p><p><strong>Next:</strong> Configuring Prometheus to use Blackbox Exporter for monitoring our API endpoints! 🚀</p><h3>Configuring Prometheus Scrape Config</h3><p>We need to add an extra scrape configuration to Prometheus. Open your values.yaml file in the prometheus directory:</p><p>bash</p><pre>cd grafana-prometheus-monitoring/prometheus/<br>vi values.yaml</pre><p>Find the extraScrapeConfigs section (or add it if it doesn&#39;t exist) and add the following:</p><pre>extraScrapeConfigs: |<br>  - job_name: &#39;api-health-checks&#39;<br>    metrics_path: /probe<br>    params:<br>      module: [http_2xx]<br>    static_configs:<br>      - targets:<br>        - https://api.example.com/health<br>        - https://payment-service.production.svc.cluster.local/healthcheck<br>        - https://auth-service.production.svc.cluster.local/status<br>        - https://client-api.external.com/ping<br>    relabel_configs:<br>      - source_labels: [__address__]<br>        target_label: __param_target<br>      - source_labels: [__param_target]<br>        target_label: instance<br>      - target_label: __address__<br>        replacement: blackbox-exporter.monitoring.svc.cluster.local:9115<br>    scrape_interval: 30s<br>    scrape_timeout: 10s</pre><h3>Understanding the Configuration</h3><p>Let me break down what each part does:</p><ul><li><strong>job_name:</strong> &#39;api-health-checks&#39; - A descriptive name for this monitoring job</li><li><strong>metrics_path:</strong> /probe - Blackbox Exporter&#39;s probe endpoint</li><li><strong>params.module:</strong> [http_2xx] - Uses the http_2xx module we defined in the ConfigMap</li><li><strong>targets:</strong> List of URLs to monitor (can be internal Kubernetes services or external APIs)</li><li><strong>relabel_configs:</strong> The magic that redirects Prometheus to use Blackbox Exporter as a proxy</li><li><strong>scrape_interval:</strong> 30s - Check endpoints every 30 seconds (adjust based on your needs)</li><li><strong>scrape_timeout:</strong> 10s - Wait up to 10 seconds for a response</li></ul><h3>Adding Your Endpoints</h3><p>Replace the example targets with your actual endpoints:</p><pre>static_configs:<br>      - targets:<br>        # Internal Kubernetes services<br>        - http://your-service.your-namespace.svc.cluster.local/health<br>        <br>        # External APIs (yours)<br>        - https://your-api.yourdomain.com/health<br>        <br>        # Client APIs you need to monitor<br>        - https://client-api.example.com/status<br>        <br>        # Load balancer health checks<br>        - https://your-loadbalancer-ip/health</pre><p><em>Pro tip: Start with a few critical endpoints, verify they’re being monitored correctly, then add more. Don’t go crazy and add 100 endpoints on day one — your Prometheus will thank you.</em></p><p><strong>Upgrade Prometheus with New Configuration</strong></p><p>After modifying values.yaml, upgrade your Prometheus installation:</p><pre>helm upgrade prometheus prometheus-community/prometheus \<br>  -f values.yaml \<br>  --namespace monitoring</pre><p>Wait for the pods to restart:</p><pre>kubectl get pods -n monitoring -w</pre><h3>Setting Up Windows Exporter: Taming the Legacy Beast 🪟</h3><h3>Why Windows Exporter?</h3><p>Let’s be real — every organization has that one (or many) Windows server that refuses to die. <em>“We’ll migrate it next quarter”</em> has been the promise for the last three years. Meanwhile, these Windows machines are running critical services, and we need to monitor them just like everything else.</p><p>Windows Exporter (formerly known as WMI Exporter) is Prometheus’s answer to monitoring Windows servers. It exposes Windows performance counters, system metrics, and service status as Prometheus-compatible metrics. Think of it as the node-exporter for Windows — it collects CPU, memory, disk, network stats, and Windows-specific metrics like IIS, SQL Server, <strong>service status as Prometheus-compatible metrics</strong> and .NET performance counters.</p><p><em>The good news?</em> It’s surprisingly easy to set up. <em>The bad news?</em> You have to RDP into a Windows machine. <em>Enna koduma!</em> 😅</p><h3>Installing Windows Exporter</h3><h4>Step 1: Download Windows Exporter</h4><p>Go to the Windows server that you want to monitor and download the Windows Exporter MSI installer:</p><p><strong>Download Link:</strong></p><pre>https://github.com/prometheus-community/windows_exporter/releases/download/v0.31.3/windows_exporter-0.31.3-amd64.msi</pre><p>Or visit the GitHub releases page and download the latest version:</p><pre>https://github.com/prometheus-community/windows_exporter/releases</pre><h4>Step 2: Install Windows Exporter</h4><ol><li>Double-click the downloaded .msi file</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*545keU_DwmYIKe4blHLRqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*_Z_i8yl1ASy9fDtaJBAWCQ.png" /></figure><ol><li>Follow the installation wizard (Next → Next → Install — you know the drill)</li><li>The installer will automatically:</li></ol><ul><li>Install Windows Exporter as a Windows Service</li><li>Configure it to start automatically on boot</li><li>Open firewall port 9182 (default port)</li></ul><p><em>That’s it. Seriously. Microsoft made something easy for once.</em> 🎉</p><h4>Step 3: Verify Installation</h4><p>Open a browser on the Windows machine and navigate to:</p><pre>http://localhost:9182/metrics</pre><p>You should see a wall of metrics text like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2AstM8v4-LV7VJQd_4rZQ.png" /></figure><pre># HELP windows_cpu_time_total Time that processor spent in different modes<br># TYPE windows_cpu_time_total counter<br>windows_cpu_time_total{core=&quot;0,0&quot;,mode=&quot;idle&quot;} 12345.67<br>windows_cpu_time_total{core=&quot;0,0&quot;,mode=&quot;user&quot;} 234</pre><p><em>If you see this, congratulations! Your Windows server is now speaking Prometheus.</em> 🗣️</p><h4>Step 4: Test Remote Access</h4><p>From your local machine or any other machine in the network, test if you can access the metrics:</p><pre>curl http://&lt;windows-server-ip&gt;:9182/metrics</pre><p>If this works, you’re golden. If not, check:</p><ul><li>Windows Firewall rules (port 9182 should be open)</li><li>Network security groups (if on cloud)</li><li>The Windows Exporter service is running (check Services.msc)</li></ul><h3>Configuring Prometheus to Scrape Windows Metrics</h3><p>Now let’s tell Prometheus to scrape metrics from our Windows server.</p><p>Open your Prometheus values.yaml:</p><pre>cd grafana-prometheus-monitoring/prometheus/<br>vi values.yaml</pre><p>Add this to your extraScrapeConfigs section:</p><pre>extraScrapeConfigs: |<br>  # ... your existing scrape configs ...<br>  <br>  - job_name: &#39;windows-servers&#39;<br>    scrape_interval: 30s<br>    scrape_timeout: 10s<br>    static_configs:<br>      - targets:<br>        - &#39;192.168.1.100:9182&#39;  # Windows Server 1<br>        - &#39;192.168.1.101:9182&#39;  # Windows Server 2<br>        labels:<br>          instance: &#39;payment-gateway-server&#39;<br>          environment: &#39;production&#39;<br>          os: &#39;windows&#39;<br>          location: &#39;us-central1-a&#39;<br>      <br>      - targets:<br>        - &#39;192.168.1.102:9182&#39;  # Windows Server 3<br>        labels:<br>          instance: &#39;legacy-app-server&#39;<br>          environment: &#39;staging&#39;<br>          os: &#39;windows&#39;<br>          location: &#39;asia-south1-b&#39;</pre><h3>Understanding the Configuration</h3><ul><li><strong>targets:</strong> IP addresses and port (9182) of your Windows servers</li><li><strong>labels:</strong> Custom labels to organize and filter your metrics</li><li><strong>instance:</strong> A friendly name for the server</li><li><strong>environment:</strong> production, staging, dev, etc.</li><li><strong>os:</strong> windows (helps filter in Grafana)</li><li><strong>location:</strong> GCP zone, AWS region, or datacenter location</li></ul><p><em>Pro tip: Use meaningful labels. Future you (at 3 AM debugging) will thank present you.</em></p><h3>Upgrade Prometheus</h3><p>Apply the new configuration:</p><pre>helm upgrade prometheus prometheus-community/prometheus \<br>  -f values.yaml \<br>  --namespace monitoring</pre><p>If you see results, <em>mission accomplished!</em> Your Windows server is now being monitored. 🎯</p><h3>Troubleshooting Tips</h3><p><strong>Windows Exporter service not starting?</strong></p><p>powershell</p><pre># Check service status<br>Get-Service windows_exporter</pre><pre># Start the service<br>Start-Service windows_exporter</pre><pre># Check logs<br>Get-EventLog -LogName Application -Source windows_exporter -Newest 10</pre><p><strong>Can’t access metrics from remote?</strong></p><ul><li>Check Windows Firewall: Allow inbound on port 9182</li><li>Check GCP/AWS security groups: Allow port 9182 from Prometheus server</li><li>Verify the service is listening: netstat -ano | findstr 9182</li></ul><h3>What’s Next?</h3><p>We’ve conquered the Windows beast! Our monitoring stack now covers:</p><ul><li>✅ Kubernetes infrastructure (Prometheus + Node Exporter)</li><li>✅ API endpoints (Blackbox Exporter)</li><li>✅ Windows servers (Windows Exporter)</li></ul><p><em>But wait, there’s more!</em> We still need to monitor:</p><ul><li>⏳ GCP Load Balancer metrics</li><li>⏳ Pub/Sub queues</li><li>⏳ Database performance</li></ul><p><strong>Next up:</strong> Integrating GCP Cloud Monitoring (Stackdriver) into Grafana for complete cloud visibility. <em>Because half the infrastructure is in GCP, and we need to see EVERYTHING in one place!</em> ☁️</p><p><strong>Ready to dive into GCP monitoring integration?</strong> 🚀</p><h3>Integrating GCP Cloud Monitoring, Cloud Logging &amp; MS SQL Server 🔗</h3><p><strong>The Final Integration: Bringing Everything Together</strong></p><p>We’re now at the final stage — integrating GCP services and SQL Server directly into Grafana. This gives us complete visibility across cloud infrastructure, logs, and databases, all in one unified dashboard.</p><p><strong>Prerequisites Checklist</strong></p><p>Before we begin, ensure:</p><p><strong>For GCP Integration:</strong></p><ul><li>✅ Grafana pod has a service account with proper GCP permissions</li><li>✅ GCP IAM roles configured</li><li>✅ Network connectivity to GCP APIs</li></ul><p><strong>For MS SQL Server:</strong></p><ul><li>✅ SQL Server accessible from Grafana pod</li><li>✅ Monitoring user created with read permissions</li><li>✅ Port 1433 accessible</li></ul><h3>Part 1: Adding Google Cloud Monitoring Data Source 📊</h3><p>Google Cloud Monitoring (formerly Stackdriver Monitoring) provides metrics from GCP resources like Load Balancers, Pub/Sub, Cloud SQL, and more.</p><p><strong>Step 1: Navigate to Data Sources</strong></p><ol><li>Click <strong>☰</strong> (hamburger menu) in the left sidebar</li><li>Go to <strong>Connections</strong> → <strong>Data sources</strong></li><li>Click the <strong>Add data source</strong> button (blue button at top right)</li></ol><p><strong>Step 2: Select Google Cloud Monitoring</strong></p><ol><li>In the search box, type: Google Cloud Monitoring</li><li>Click on the <strong>Google Cloud Monitoring</strong> card</li></ol><p><strong>Step 3: Configure the Data Source</strong></p><p><strong>Basic Settings:</strong></p><ul><li><strong>Name:</strong> GCP Cloud Monitoring (or any descriptive name)</li></ul><p><strong>Authentication:</strong></p><ul><li><strong>Authentication Type:</strong> Select GCE Default Service Account</li><li><em>This uses the Workload Identity from your Grafana pod’s service account</em></li><li><em>Ensure your service account has </em><em>roles/monitoring.viewer permission</em></li><li><strong>Default Project:</strong> Enter your GCP Project ID (e.g., my-project-12345)</li></ul><p><strong>Step 4: Save &amp; Test</strong></p><ul><li>Scroll down to the bottom</li><li>Click <strong>Save &amp; Test</strong> button</li><li>You should see: ✅ <em>“Successfully queried the Google Cloud Monitoring API”</em></li></ul><p><strong>What you can monitor:</strong></p><ul><li>Load Balancer request rates, latency, errors</li><li>Pub/Sub queue depth and message age</li><li>Cloud SQL CPU, memory, connections</li><li>GKE cluster metrics</li><li>Compute Engine VM metrics</li></ul><h3>Part 2: Adding Google Cloud Logging Data Source 📝</h3><p>Google Cloud Logging (googlecloud-logging-datasource) provides access to application logs, system logs, and audit logs from GCP.</p><p><strong>Step 1: Navigate to Data Sources</strong></p><ol><li>Click <strong>☰</strong> → <strong>Connections</strong> → <strong>Data sources</strong></li><li>Click <strong>Add data source</strong> button</li></ol><p><strong>Step 2: Select Google Cloud Logging</strong></p><ol><li>In the search box, type: Google Cloud Logging</li><li>Click on the <strong>Google Cloud Logging</strong> card</li></ol><ul><li><em>This is the </em><em>googlecloud-logging-datasource plugin</em></li></ul><p><strong>Step 3: Configure the Data Source</strong></p><p><strong>Basic Settings:</strong></p><ul><li><strong>Name:</strong> GCP Cloud Logging (or any descriptive name)</li></ul><p><strong>Authentication:</strong></p><ul><li><strong>Authentication Type:</strong> Select GCE Default Service Account</li><li><em>Uses the Workload Identity from your Grafana pod</em></li><li><em>Ensure your service account has </em><em>roles/logging.viewer permission</em></li><li><strong>Default Project:</strong> Enter your GCP Project ID (e.g., my-project-12345)</li></ul><p><strong>Step 4: Save &amp; Test</strong></p><ul><li>Scroll down to the bottom</li><li>Click <strong>Save &amp; Test</strong> button</li><li>You should see: ✅ <em>“Successfully queried the Logging API”</em></li></ul><p><strong>What you can query:</strong></p><ul><li>Load Balancer access logs</li><li>Application logs from GKE/GCE</li><li>System logs</li><li>Audit logs</li><li>Error logs and stack traces</li></ul><h3>Part 3: Adding Microsoft SQL Server Data Source 🗄️</h3><p>MS SQL Server data source allows direct querying of your SQL Server databases for performance metrics and business data.</p><p><strong>Step 1: Navigate to Data Sources</strong></p><ol><li>Click <strong>☰</strong> → <strong>Connections</strong> → <strong>Data sources</strong></li><li>Click <strong>Add data source</strong> button</li></ol><p><strong>Step 2: Select Microsoft SQL Server</strong></p><ol><li>In the search box, type: Microsoft SQL Server or MSSQL</li><li>Click on the <strong>Microsoft SQL Server</strong> card</li></ol><ul><li><em>This is a built-in data source, no plugin needed</em></li></ul><p><strong>Step 3: Configure Connection Settings</strong></p><p><strong>Connection:</strong></p><ul><li><strong>Name:</strong> Production-MSSQL (or your preferred name)</li><li><strong>Host:</strong> 192.168.1.100:1433</li><li>Format: IP_ADDRESS:PORT or hostname:port</li><li>For named instance: 192.168.1.100\INSTANCENAME</li><li>Default port: 1433</li></ul><p><strong>Authentication:</strong></p><ul><li><strong>Authentication:</strong> Select SQL Server Authentication</li><li><strong>User:</strong> grafana_monitor (the read-only user you created)</li><li><strong>Password:</strong> Enter the password for grafana_monitor user</li><li><strong>Encrypt:</strong> Select false (or true if SQL Server uses SSL/TLS)</li></ul><p><strong>Connection Limits:</strong></p><ul><li><strong>Database:</strong> YourDatabaseName (or leave empty to use default database)</li><li><strong>Max open connections:</strong> 5 (adjust based on your load)</li><li><strong>Max idle connections:</strong> 2</li><li><strong>Max connection lifetime:</strong> 14400 (4 hours in seconds)</li></ul><p><strong>Additional Settings:</strong></p><ul><li><strong>TLS/SSL Mode:</strong> disable (unless you have SSL configured)</li></ul><p><strong>Step 4: Save &amp; Test</strong></p><ul><li>Scroll down to the bottom</li><li>Click <strong>Save &amp; Test</strong> button</li><li>You should see: ✅ <em>“Database Connection OK”</em></li></ul><p><strong>What you can query:</strong></p><ul><li>Database performance metrics (CPU, memory, connections)</li><li>Query execution times and slow queries</li><li>Transaction logs and deadlocks</li><li>Custom business metrics from your tables</li><li>Real-time data for dashboards</li></ul><h3>Time to Build Dashboards! 🎨</h3><p>Now comes the fun part — creating dashboards to visualize all this data. You have two options:</p><h3>Option 1: Use Pre-built Dashboards from the Community</h3><p>There are <strong>thousands of ready-made dashboards</strong> available on Grafana’s community dashboard repository. These are great starting points and can save you hours of work.</p><p><strong>How to Import Community Dashboards:</strong></p><ol><li>Visit: <a href="https://grafana.com/grafana/dashboards/">https://grafana.com/grafana/dashboards/</a></li><li>Search for dashboards related to your needs (Kubernetes, Prometheus, GCP, SQL Server)</li><li>Note the <strong>Dashboard ID</strong> (e.g., 3119, 1860, 14694)</li><li>In Grafana:</li></ol><ul><li>Go to <strong>Dashboards → Import</strong></li><li>Enter the Dashboard ID</li><li>Select your data source</li><li>Click <strong>Import</strong></li></ul><h3>Option 2: Build Custom Dashboards for Your Specific Needs</h3><p>While community dashboards are excellent, you might need custom dashboards tailored to your specific requirements. Here are some examples:</p><h3>Custom Dashboard Examples 🎯</h3><h3>a) API Response Time Dashboard</h3><p><strong>Purpose:</strong> Monitor API performance with 4xx/5xx error counts and identify slow endpoints</p><p><strong>Visualization:</strong></p><ul><li>Use <strong>Stat</strong> panels for 4xx/5xx counts</li><li>Use <strong>Time Series</strong> for response time trends</li><li>Use <strong>Table</strong> for slowest APIs list</li><li>Use <strong>Gauge</strong> for endpoints exceeding 5s threshold</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAI_Bj7CgsX2vNzt3JhBjA.png" /></figure><h3>b) Cloud SQL Dashboard</h3><p><strong>Purpose:</strong> Monitor database performance and identify slow queries</p><p><strong>Visualization:</strong></p><ul><li>Use <strong>Gauge</strong> for CPU, Memory, Disk utilization</li><li>Use <strong>Bar Chart</strong> for query latency distribution</li><li>Use <strong>Table</strong> for top 20 slow queries</li><li>Use <strong>Time Series</strong> for connection trends</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v337SwB3vhGl9S2FW4xjog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbVMkN9fjns_jmK1bvYnfQ.png" /></figure><h3>c) Client-Specific Dashboard</h3><p><strong>Purpose:</strong> Dedicated dashboard for each client showing their infrastructure health</p><p><strong>Visualization:</strong></p><ul><li>Use <strong>Stat</strong> panels with color thresholds for health checks (Green = Up, Red = Down)</li><li>Use <strong>Gauge</strong> for CPU/Memory utilization</li><li>Use <strong>Time Series</strong> for trends</li><li>Use <strong>Table</strong> for pod status list</li><li>Use <strong>Single Stat</strong> with sparkline for Pub/Sub counts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPlnjQkTaT0vEbVO7b7LVA.png" /></figure><h3>Need Help Building Custom Dashboards? 📬</h3><p>If you need assistance creating these custom dashboards or have specific requirements for your monitoring setup, feel free to reach out!</p><p><strong>Connect with me on LinkedIn:</strong>🔗 [<a href="http://linkedin.com/in/sidhu-sangani-34a8511a9">sidhu sangani</a>]</p><p>I can help you with:</p><ul><li>Custom dashboard design and implementation</li><li>Complex Prometheus queries and PromQL</li><li>GCP monitoring integration</li><li>SQL Server performance tuning queries</li><li>Alert configuration and best practices</li><li>Monitoring architecture consultation</li></ul><p><em>Let’s build monitoring solutions that actually make your life easier!</em> 🚀</p><h3>Final Thoughts 🎯</h3><p>You’ve built a <strong>world-class monitoring infrastructure</strong> from scratch:</p><p>✅ Complete observability across infrastructure, cloud, and databases<br> ✅ Multiple data sources integrated into one platform<br> ✅ Foundation for unlimited custom dashboards<br> ✅ Scalable architecture for future growth</p><p><strong>From that Tuesday meeting where management said “we need better dashboards” to now having enterprise-grade monitoring — you’ve come a long way!</strong></p><p><em>Ippo ellam complete! From zero to full monitoring empire. Infrastructure metrics, API monitoring, database performance, business KPIs, client dashboards — ellame ready! Management-ku kanakka dashboard kuduthu, clients-ku dedicated monitoring, namakku peace of mind. Perfect-a mudichutom!</em> 🏆✨</p><p>After doing all this, I feel like Inimel inga naan thaan Rangaraya Sakthivel😎🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojXg5wMpyPQiMOHA915nRg.jpeg" /></figure><p><strong>Happy Monitoring! May your dashboards always be green and your alerts always be silent (until they need to be loud)!</strong> 🎉📊🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54402118d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keycloak integration with grafana]]></title>
            <link>https://medium.com/@sidhusangani/keycloak-integration-with-grafana-eded24f73c2f?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eded24f73c2f</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 04:45:54 GMT</pubDate>
            <atom:updated>2025-10-03T04:45:54.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*YDUA2ZL9kmZxZu1L.png" /></figure><p>Managing users in Grafana without Keycloak can feel a bit like running a neighborhood club with a paper guest list — you keep scribbling down names, handing out passes, and hoping nobody sneaks in with their friend’s badge. 😅 Sure, it works, but it’s messy.</p><p>Enter <strong>Keycloak</strong> — your very own professional bouncer <em>and</em> guest manager. Instead of manually juggling users, Keycloak lets you handle authentication and access in one clean place. Need to add someone? Done. Remove someone? Easy. Assign roles? Just a couple of clicks. It’s like upgrading from sticky notes to a proper CRM for your dashboard crowd.</p><p>In this guide, I’ll show you how to integrate Keycloak with Grafana so you can stop playing “user admin” and start enjoying smoother logins, simpler role management, and a much happier ops team. 🚀</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*z0T6-klqPVXk-LaZ.png" /></figure><p>Keycloak integration with grafana</p><ol><li>Pre-Requisites:-</li></ol><p>→ Keycloak set-up is done<br>→ K8s cluster set-up is done</p><p>2. Initial Keycloak setup:-</p><p>→Open keycloak click on clients and create a new client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*byYBgl5XGXDEc2l7.png" /></figure><p>→ In the General setting Provide the Client ID, Name, and description</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*CmRk99t-psFW8_jk.png" /></figure><p>→ capability config we can use the default configuration<br>→ Login settings<br>root URL, Home URL, and Admin URL can be the same as the Jenkins URL used.</p><p>valid redirect URL’s update as <a href="https://monitoring-dev-01.ihx.in/login/generic_oauth">https://sub-domain.domain/login/generic_oauth</a></p><pre>Client ID: grafana-oauth<br>Enabled: ON<br>Client Protocol: openid-connect<br>Access Type: confidential<br>Standard Flow Enabled: ON<br>Implicit Flow Enabled: OFF<br>Direct Access Grants Enabled: ON<br>Root URL: &lt;grafana_root_url&gt;<br>Valid Redirect URIs: &lt;grafana_root_url&gt;/login/generic_oauth<br>Web Origins: &lt;grafana_root_url&gt;<br>Admin URL: &lt;grafana_root_url&gt;<br>Base URL: &lt;grafana_root_url&gt;</pre><p>below is an example:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*pRURAbw8V3VUquJ_.png" /></figure><p>3. Initial grafana setup:-</p><p>add the below configurations in values.yaml if you have installed grafana using helm</p><pre>[auth.generic_oauth]<br>enabled = true<br>name = Keycloak-OAuth<br>allow_sign_up = true<br>client_id = YOUR_APP_CLIENT_ID<br>client_secret = YOUR_APP_CLIENT_SECRET<br>scopes = openid email profile offline_access roles<br>email_attribute_path = email<br>login_attribute_path = username<br>name_attribute_path = full_name<br>auth_url = https://&lt;PROVIDER_DOMAIN&gt;/realms/&lt;REALM_NAME&gt;/protocol/openid-connect/auth<br>token_url = https://&lt;PROVIDER_DOMAIN&gt;/realms/&lt;REALM_NAME&gt;/protocol/openid-connect/token<br>api_url = https://&lt;PROVIDER_DOMAIN&gt;/realms/&lt;REALM_NAME&gt;/protocol/openid-connect/userinfo<br>role_attribute_path = contains(roles[*], &#39;admin&#39;) &amp;&amp; &#39;Admin&#39; || contains(roles[*], &#39;editor&#39;) &amp;&amp; &#39;Editor&#39; || &#39;Viewer&#39;</pre><p>if you have grafana running via the deployment file add the below env variables:-</p><pre>env:<br>            - name: GF_AUTH_GENERIC_OAUTH_ENABLED<br>              value: &quot;true&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_NAME<br>              value: &quot;Keycloak&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_ALLOW_SIGN_UP<br>              value: &quot;true&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_CLIENT_ID<br>              value: &quot;grafana-oauth&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET<br>              value: &quot;&quot; # replace with actual client secret<br>            - name: GF_AUTH_GENERIC_OAUTH_SCOPES<br>              value: &quot;openid profile email offline_access roles&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_USE_REFRESH_TOKEN<br>              value: &quot;true&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_EMAIL_ATTRIBUTE_PATH<br>              value: &quot;email&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_GROUPS_ATTRIBUTE_PATH<br>              value: &quot;groups&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_LOGIN_ATTRIBUTE_PATH<br>              value: &quot;username&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_NAME_ATTRIBUTE_PATH<br>              value: &quot;full_name&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_AUTH_URL<br>              value: &quot;https://sub-domain.domain/realms/IHX-AI/protocol/openid-connect/auth&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_TOKEN_URL<br>              value: &quot;https://sub-domain.domain/realms/IHX-AI/protocol/openid-connect/token&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_API_URL<br>              value: &quot;https://sub-domain.domain/realms/IHX-AI/protocol/openid-connect/userinfo&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_SIGNOUT_REDIRECT_URL<br>              value: &quot;https://sub-domain.domain/realms/IHX-AI/protocol/openid-connect/logout?post_logout_redirect_uri=https%3A%2F%2Fsub-domain.domain%2F&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_ROLE_ATTRIBUTE_PATH<br>              value: &quot;contains(groups[*], &#39;grafanaadmin&#39;) &amp;&amp; &#39;GrafanaAdmin&#39; || contains(groups[*], &#39;admin&#39;) &amp;&amp; &#39;Admin&#39; || contains(groups[*], &#39;editor&#39;) &amp;&amp; &#39;Editor&#39; || &#39;Viewer&#39;&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_ALLOW_ASSIGN_GRAFANA_ADMIN<br>              value: &quot;true&quot;<br>            - name: GF_SERVER_ROOT_URL<br>              value: &quot;https://sub-domain.domain/&quot;<br>            - name: GF_SIGNOUT_REDIRECT_URL<br>              value: &quot;https://sub-domain.domain/&quot;<br>            - name: GF_AUTH_GENERIC_OAUTH_REDIRECT_URI<br>              value: &quot;https://sub-domain.domain/login/generic_oauth&quot;</pre><blockquote><em>then apply the deployment file, kubectl apply -f deployment-file.yaml</em></blockquote><p>4. Configuring Google sign-on:</p><ul><li>Login to GCP → APIs → Credentials → Oauth 2.0 Client IDs (If you don’t have one create)</li><li>Authorized JavaScript origins → <a href="https://domainname/">https://domainname</a></li><li>Authorized redirect URIs → <a href="https://subdomain.domain%20name/realms/realm%20name/broker/google/endpoint">https://subdomain.domain name/realms/realm name/broker/google/endpoint</a></li></ul><p>update subdomain, domain name, and realm name in above URL.</p><ul><li>Copy the Client ID and Secret from the GCP Console</li></ul><p>5. Configuring Identity providers in Keyloak</p><ul><li>On keycloak → Identity Providers → Add Google provider</li><li>Enter the client ID and secret for Identity Provider (Google) and configure it in keycloak.</li><li>Turn on the Request refresh token</li></ul><p>6. log in to grafana UI, you should be able to log in via Google.</p><p>Note:if the user is of your organization he/she by default will get view access.</p><p>In the end, integrating Keycloak with Grafana transforms your data fortress from a chaotic maze of access keys into a streamlined bastion of security and efficiency. With Keycloak’s Single Sign-On and centralized control, your warriors navigate the citadel effortlessly, while robust defenses and detailed logs keep your realm secure. As your kingdom expands, Keycloak adapts, seamlessly integrating with every domain. This partnership ensures that your Grafana fortress remains an impenetrable stronghold, where access is smooth, security is tight, and your data is always protected.</p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><h3>References</h3><ol><li><a href="https://medium.com/@shreyasmk.mathur/mastering-multi-factor-authentication-in-keycloak-sms-email-and-totp-setup-guide-957305b92be1">Mastering the MFA Authentication</a> → by Shreyas (One of the best blogs for references and implementation of MFA (Gmail, authenticator, and SMS)</li><li><a href="https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/keycloak/">https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/keycloak/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eded24f73c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time AWS DMS Task Monitoring with Slack Integration]]></title>
            <link>https://medium.com/@sidhusangani/real-time-aws-dms-task-monitoring-with-slack-integration-f99c99713325?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99c99713325</guid>
            <category><![CDATA[lamda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[dms]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 07:25:45 GMT</pubDate>
            <atom:updated>2025-02-24T07:25:45.314Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with AWS Database Migration Service (DMS), monitoring task status is crucial. In this guide, we’ll create a serverless solution that sends DMS task status notifications directly to Slack, helping teams stay informed about their database migrations in real-time.</p><p><strong>Architecture Overview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5Ok4LextDN_SASrxYPAdw.png" /></figure><p>The solution uses these AWS services:<br>- AWS DMS Event Subscriptions<br>- Amazon SNS (Simple Notification Service)<br>- AWS Lambda<br>- Slack Incoming Webhooks</p><p>Flow:<br>1. DMS task status changes<br>2. DMS Event subscription captures the change<br>3. SNS receives the notification<br>4. Lambda processes and formats the message<br>5. Slack displays the formatted notification</p><p><strong>Prerequisites</strong><br>- AWS Account with appropriate permissions<br>- Slack workspace where you can create apps<br>- Existing DMS replication tasks</p><h3>Step-by-Step Implementation</h3><p><strong>1. Create Slack App and Get Webhook URL</strong></p><p>1. Go to api.slack.com/apps<br>2. Click “Create New App”<br>3. Choose “From scratch”<br>4. Enter app name and select workspace<br>5. Click “Incoming Webhooks”<br>6. Toggle “Activate Incoming Webhooks” to On<br>7. Click “Add New Webhook to Workspace”<br>8. Select the channel for notifications<br>9. Copy the webhook URL for later use</p><p><strong>2. Set Up SNS Topic</strong></p><p>1. Go to SNS in AWS Console<br>2. Create Topic:<br> — Click “Create topic”<br> — Type: Standard<br> — Name: dms-slack-notifier<br> — Create topic</p><p>3. Configure topic policy (this is automatically created, just add DMS permissions):</p><pre>{<br>  &quot;Version&quot;: &quot;2008-10-17&quot;,<br>  &quot;Id&quot;: &quot;__default_policy_ID&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;__default_statement_ID&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;*&quot;<br>      },<br>      &quot;Action&quot;: [<br>        &quot;SNS:Publish&quot;,<br>        &quot;SNS:RemovePermission&quot;,<br>        &quot;SNS:SetTopicAttributes&quot;,<br>        &quot;SNS:DeleteTopic&quot;,<br>        &quot;SNS:ListSubscriptionsByTopic&quot;,<br>        &quot;SNS:GetTopicAttributes&quot;,<br>        &quot;SNS:AddPermission&quot;,<br>        &quot;SNS:Subscribe&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:sns:REGION:ACCOUNT_ID:dms-slack-notifier&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;AWS:SourceOwner&quot;: &quot;ACCOUNT_ID&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Sid&quot;: &quot;AllowDMSPublish&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;dms.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;SNS:Publish&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:sns:REGION:ACCOUNT_ID:dms-slack-notifier&quot;<br>    }<br>  ]<br>}</pre><p>3. Create Lambda Function</p><p>1. Go to Lambda console<br>2. Create function:<br> — Click “Create function”<br> — Author from scratch<br> — Name: dms-slack-notifier<br> — Runtime: Python 3.9<br> — Architecture: x86_64</p><p>3. Add environment variable:<br> — Key: webhook_url<br> — Value: Your-Slack-Webhook-URL (from Step 1)</p><p>4. Add this code:</p><pre>import json<br>import urllib3<br>import os<br><br>def get_status_emoji(message):<br>    &quot;&quot;&quot;Return appropriate emoji based on message content&quot;&quot;&quot;<br>    message_lower = message.lower() if message else &#39;&#39;<br>    if &#39;error&#39; in message_lower or &#39;failed&#39; in message_lower:<br>        return &quot;🔴&quot;, &quot;ERROR&quot;<br>    elif &#39;stopped&#39; in message_lower:<br>        return &quot;⏹️&quot;, &quot;STOPPED&quot;<br>    elif &#39;starting&#39; in message_lower:<br>        return &quot;▶️&quot;, &quot;STARTING&quot;<br>    elif &#39;resumed&#39; in message_lower or &#39;running&#39; in message_lower:<br>        return &quot;✅&quot;, &quot;RUNNING&quot;<br>    else:<br>        return &quot;ℹ️&quot;, &quot;INFO&quot;<br><br>def lambda_handler(event, context):<br>    webhook_url = os.environ[&#39;webhook_url&#39;]<br>    http = urllib3.PoolManager()<br>    <br>    try:<br>        # Parse SNS message<br>        sns_message_raw = event[&#39;Records&#39;][0][&#39;Sns&#39;][&#39;Message&#39;]<br>        <br>        try:<br>            sns_message = json.loads(sns_message_raw)<br>        except json.JSONDecodeError:<br>            sns_message = {&quot;Message&quot;: sns_message_raw}<br><br>        # Extract message details<br>        event_source = sns_message.get(&#39;Event Source&#39;, &#39;&#39;)<br>        source_id = sns_message.get(&#39;SourceId&#39;, &#39;Unknown&#39;)<br>        event_time = sns_message.get(&#39;Event Time&#39;, &#39;&#39;)<br>        event_message = sns_message.get(&#39;Event Message&#39;, &#39;&#39;)<br>        event_id = sns_message.get(&#39;Event ID&#39;, &#39;&#39;)<br><br>        # Get status emoji and status text<br>        status_emoji, status_text = get_status_emoji(event_message)<br>        <br>        # Create formatted Slack message<br>        slack_message = {<br>            &quot;blocks&quot;: [<br>                {<br>                    &quot;type&quot;: &quot;header&quot;,<br>                    &quot;text&quot;: {<br>                        &quot;type&quot;: &quot;plain_text&quot;,<br>                        &quot;text&quot;: f&quot;{status_emoji} DMS Task: {source_id} | Status: {status_text}&quot;<br>                    }<br>                },<br>                {<br>                    &quot;type&quot;: &quot;divider&quot;<br>                },<br>                {<br>                    &quot;type&quot;: &quot;section&quot;,<br>                    &quot;fields&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;mrkdwn&quot;,<br>                            &quot;text&quot;: f&quot;*Source ID:*\n`{source_id}`&quot;<br>                        },<br>                        {<br>                            &quot;type&quot;: &quot;mrkdwn&quot;,<br>                            &quot;text&quot;: f&quot;*Status:*\n`{status_text}`&quot;<br>                        }<br>                    ]<br>                },<br>                {<br>                    &quot;type&quot;: &quot;section&quot;,<br>                    &quot;fields&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;mrkdwn&quot;,<br>                            &quot;text&quot;: f&quot;*Time:*\n{event_time}&quot;<br>                        },<br>                        {<br>                            &quot;type&quot;: &quot;mrkdwn&quot;,<br>                            &quot;text&quot;: f&quot;*Event Source:*\n{event_source}&quot;<br>                        }<br>                    ]<br>                },<br>                {<br>                    &quot;type&quot;: &quot;section&quot;,<br>                    &quot;text&quot;: {<br>                        &quot;type&quot;: &quot;mrkdwn&quot;,<br>                        &quot;text&quot;: f&quot;*Message:*\n{event_message}&quot;<br>                    }<br>                },<br>                {<br>                    &quot;type&quot;: &quot;context&quot;,<br>                    &quot;elements&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;mrkdwn&quot;,<br>                            &quot;text&quot;: f&quot;*Event ID:* {event_id}&quot;<br>                        }<br>                    ]<br>                }<br>            ]<br>        }<br>        <br>        # Send to Slack<br>        encoded_msg = json.dumps(slack_message).encode(&#39;utf-8&#39;)<br>        response = http.request(&#39;POST&#39;,<br>                              webhook_url,<br>                              body=encoded_msg,<br>                              headers={&#39;Content-Type&#39;: &#39;application/json&#39;})<br>        <br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps(&#39;Message sent to Slack!&#39;)<br>        }<br>        <br>    except Exception as e:<br>        print(f&quot;Error: {str(e)}&quot;)<br>        print(f&quot;Raw event: {json.dumps(event, indent=2)}&quot;)<br>        raise</pre><p>4. Test Lambda Function</p><p>Create a test event with this JSON:</p><pre>{<br>  &quot;Records&quot;: [<br>    {<br>      &quot;Sns&quot;: {<br>        &quot;Message&quot;: &quot;{\&quot;Event Source\&quot;:\&quot;replication-task\&quot;,\&quot;SourceId\&quot;:\&quot;mt-stage-dw-pc\&quot;,\&quot;Event Time\&quot;:\&quot;2025-02-24 07:05:50.522\&quot;,\&quot;Event Message\&quot;:\&quot;Replication task has failed. Reason: Last Error The task stopped abnormally Stop Reason FATAL_ERROR Error Level FATAL.\&quot;,\&quot;Event ID\&quot;:\&quot;http://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html#DMS-EVENT-0078\&quot;}&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>5. Create DMS Event Subscription</p><p>1. Go to DMS console<br>2. Click “Event subscriptions”<br>3. Create event subscription:<br> — Name: dms-task-alerts<br> — Send notifications to: SNS topic<br> — Select your topic (dms-slack-notifier)<br> — Event source: Replication task<br> — Event categories: Select events you want to monitor<br> — Source: Choose specific tasks or all tasks</p><p><strong>Features</strong></p><p>1. Status Indicators:<br> — 🔴 ERROR — For failures and errors<br> — ✅ RUNNING — For running tasks<br> — ▶️ STARTING — For tasks starting up<br> — ⏹️ STOPPED — For stopped tasks<br> — ℹ️ INFO — For other states</p><p>2. Message Format:<br> — Task ID and Status in header<br> — Source ID and current status<br> — Timestamp and event source<br> — Detailed message<br> — Event ID reference</p><p><strong>Best Practices</strong></p><p>1. Security:<br> — Store webhook URL in environment variables<br> — Use minimum required permissions<br> — Regularly rotate credentials</p><p>2. Monitoring:<br> — Set up CloudWatch alarms for Lambda errors<br> — Monitor SNS delivery status<br> — Check DMS event subscription status</p><p>3. Maintenance:<br> — Regularly test the notification flow<br> — Update Lambda runtime when needed<br> — Monitor Lambda costs</p><p><strong>Troubleshooting</strong></p><p>Common issues and solutions:</p><p>1. Messages not appearing in Slack:<br> — Verify webhook URL is correct<br> — Check Lambda execution role permissions<br> — Review CloudWatch logs</p><p>2. Missing notifications:<br> — Verify DMS event subscription is active<br> — Check SNS topic permissions<br> — Review DMS task status</p><p><strong>Conclusion</strong></p><p>This setup provides real-time visibility into your DMS tasks with formatted Slack notifications. It helps teams:<br>- Monitor database migrations actively<br>- Respond quickly to issues<br>- Track task status changes<br>- Maintain migration history</p><p>Consider extending the solution with:<br>- Additional notification channels<br>- Custom message formatting<br>- Automated response actions<br>- Historical status tracking</p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99c99713325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Great Log Heist: When Promtail Met Loki]]></title>
            <link>https://medium.com/@sidhusangani/the-great-log-heist-when-promtail-met-loki-cf0b67f16371?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf0b67f16371</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[loki]]></category>
            <category><![CDATA[promtail]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 12:08:54 GMT</pubDate>
            <atom:updated>2025-01-06T12:08:54.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBJqY6al0u3kdXJs-9aZ_A.gif" /></figure><p>There I was, sipping my third coffee of the day, when a developer materialized at my desk with the kind of panicked expression usually reserved for production outages. ‘The logs… they’re gone!’ they declared, as if our logs had decided to take an unscheduled vacation to the Bahamas.</p><p>Being the sophisticated DevOps engineer I am, I reached for the most elegant solution in our playbook — turning it off and on again. Well, technically, restarting the pod. Lo and behold, logs started flowing like a broken fire hydrant. Problem solved! <strong>pats self on back</strong></p><p>Or so I thought.</p><p>A few days later, the same developer returned, probably wondering if our logs had joined a witness protection program. This time, I decided to play detective and peek under the hood. Our Kubernetes pod was running two containers — our application and something called Promtail. At this point, my knowledge of Promtail was about as deep as a puddle: ‘It ships logs… somewhere?’ (<strong>Don’t judge me, we’ve all been there</strong>.)</p><p>Turns out our pod was having the equivalent of a CPU heart attack — throttled to within an inch of its digital life. No wonder the logs were playing hide and seek! A quick CPU boost brought everything back online, but it felt like putting premium gas in a car that needed an engine overhaul.</p><p>But wait, there’s more! The plot thickened faster than instant ramen. Our pod was now doing its best impression of a hyperactive jumping bean — restarting continuously like it had one too many espressos. During these caffeinated restarts, our application was faithfully writing logs to a .log file like a dear diary, but they never made it to Grafana Loki. Yet mysteriously, when we ran `kubectl logs` (on the rare moments we could catch the pod before another restart), the logs were right there, clear as day. It was like our logs were posting on Instagram but ghosting Facebook — they were definitely being written somewhere, but Loki was being left on read.</p><p>This whole comedy of errors left me wondering:<br>- Why was Promtail tagging along in our pods like an overprotective parent?<br>- What exactly was this Loki system? (Definitely not Thor’s prankster sibling, though the chaos levels seemed similar)<br>- How did we end up with a logging system that had more mood swings than a teenager?</p><p>Join me on this wild ride through the world of logging infrastructure, where we’ll uncover why Promtail isn’t just some random container crashing on your pod’s couch, and how Loki became the superhero of logging (no Marvel lawsuit pending).</p><p>Because let’s face it — in the world of Kubernetes, losing your logs is like trying to find your keys in a dark room while wearing a blindfold. Sure, they’re probably somewhere, but good luck figuring out where without bumping into everything first.</p><p>Spoiler alert: This story has a happy ending, but first, let’s talk about how we turned our logging system from ‘Ghost in the Shell’ to ‘Mission Possible.’”</p><p>In this blog series, we’re starting from ground zero. I’ll take you through my journey from “What even is Loki?” to deploying a fully-functional logging system in Kubernetes</p><ul><li>Loki is a log aggregation (the formation of a number of things into a cluster) system designed to store and query the logs.</li><li>Designed to be cost-effective and easy to operate.</li><li>Loki only indexes labels (metadata) from logs unlike Elasticsearch which does index full text from logs</li></ul><p>For example:-</p><p>A log entry from an application could look like this:</p><pre>{<br>&quot;timestamp&quot;: &quot;2024–12–26T10:30:00Z&quot;,<br>&quot;level&quot;: &quot;ERROR&quot;,<br>&quot;message&quot;: &quot;Failed to connect to database&quot;,<br>&quot;app&quot;: &quot;billing-service&quot;,<br>&quot;env&quot;: &quot;production&quot;,<br>&quot;pod&quot;: &quot;billing-service-xyz123&quot;,<br>&quot;error_code&quot;: &quot;DB_CONN_TIMEOUT&quot;<br>}</pre><h3>Elasticsearch: Full-Text Indexing</h3><p>Elasticsearch indexes <strong>all fields</strong> (structured and unstructured) by default, including the message field.</p><h4>What Happens in Elasticsearch:</h4><ol><li><strong>Full-text Indexing</strong>:</li></ol><ul><li>Every word in the message field (“Failed”, “to”, “connect”, “database”, etc.) is indexed.</li><li>Fields like app, env, pod, and error_code are also indexed as structured data.</li></ul><ol><li><strong>Query Examples</strong>:</li></ol><ul><li><strong>Search by Labels</strong>: app=”billing-service” AND env=”production”</li><li><strong>Full-text Search</strong>: Find logs containing “database” or “Failed to connect”.</li><li><strong>Advanced Search</strong>: Search for message=”Failed AND database” using Elasticsearch’s full-text search capabilities.</li></ul><ol><li><strong>Storage</strong>:</li></ol><ul><li>Full-text indexing requires more storage because every word and field is indexed for fast searching.</li><li>Loki indexes only <strong>labels</strong> (metadata), not the full log content.</li></ul><h4>What Happens in Loki:</h4><ol><li><strong>Labels</strong>:</li></ol><ul><li>Labels are key-value pairs, such as app=”billing-service”, env=”production”, and pod=”billing-service-xyz123&quot;.</li><li>These labels are the only indexed data.</li></ul><p><strong>2. Log Content</strong>:</p><ul><li>The actual log content (message: “Failed to connect to database”) is stored in compressed form without being indexed.</li></ul><p><strong>3. Query Examples</strong>:</p><ul><li><strong>Search by Labels</strong>: app=”billing-service” AND env=”production”</li><li><strong>Search Log Content</strong>: To find “database” in the message, Loki retrieves raw logs that match the label filter and scans for the text.</li></ul><p><strong>4. Storage</strong>:</p><ul><li>Only the labels are indexed, drastically reducing storage and indexing overhead.</li></ul><h3><strong>Simple Overview of Loki</strong>:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*C4QOjizgNAMKYutO" /></figure><p>→ As Loki is a log aggregator there are several agent which help in shipping the logs to it called log shippers like promtail ,fluentd and Logstash</p><p>→ Promatil scaps the logs sends to loki , then loki indexes the label and then store the log message in object storage like s3</p><p>→LogQL query language is used by the user to interact with loki to filter out logs</p><h3><strong>Architecutre of Loki:-</strong></h3><p>a)<strong> Distributor</strong>:-</p><p>→It’s the first step in the write path for log data</p><p>→ it is a stateless component that is responsible for handling and validating the logs received from log agents like Promtail and distributing the logs to the ingester.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*gNyuE_5UeIPRyRJG" /></figure><p>→ When the distributor receives logs, As part of log processing, Loki first verifies whether the log streams comply with the agreed specification(like, valid labels, isn’t older timestamps and the log is not too long.). It then preprocesses the incoming log data by standardizing the labels, enabling Loki to cache and hash them efficiently. The Distributor can also enforce rate limiting on incoming logs based on the allowed bitrate per tenant.</p><p>→Once the validation is complete the distributor distributes the logs to every ingester based on the consistent hashing scheme to make sure to distribute to every available ingester equally.[basically, Each valid stream is then sent to n <a href="https://grafana.com/docs/loki/latest/get-started/components/#ingester">ingesters</a> in parallel, where n is the <a href="https://grafana.com/docs/loki/latest/get-started/components/#replication-factor">replication factor</a> for data. The distributor determines the ingesters it sends a stream using <a href="https://grafana.com/docs/loki/latest/get-started/components/#hashing">consistent hashing</a>.]</p><p><strong>Hashing</strong> is a technique that distributes the data across multiple ingesters (like how a load balancer distributes traffic)</p><p>→ A hash ring, maintained by peer-to-peer communication using the <a href="https://github.com/hashicorp/memberlist">Memberlist</a> protocol, or stored in a Key-Value store such as <a href="https://www.consul.io/">Consul</a> is used to achieve consistent hashing; all <a href="https://grafana.com/docs/loki/latest/get-started/components/#ingester">ingesters</a> register themselves into the hash ring with a set of tokens they own. Each token is a random unsigned 32-bit number. Along with a set of tokens, ingesters register their state into the hash ring. The state JOINING, and ACTIVE may all receive write requests, while ACTIVE and LEAVING ingesters may receive read requests. When doing a hash lookup, distributors only use tokens for ingesters who are in the appropriate state for the request.</p><p>→ To do the hash lookup, distributors find the smallest appropriate token whose value is larger than the hash of the stream. When the replication factor is larger than 1, the next subsequent tokens (clockwise in the ring) that belong to different ingesters will also be included in the result.</p><p>→ The effect of this hash setup is that each token that an ingester owns is responsible for a range of hashes. If there are three tokens with values 0, 25, and 50, then a hash of 3 would be given to the ingester that owns the token 25; the ingester owning token 25 is responsible for the hash range of 1–25.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iGAVUzT4hd0V-vpU" /></figure><p>b)<strong> Ingester</strong>:-</p><p>→The Ingester is responsible for storing and indexing the logs received from the distributor on its memory and transferring logs to persistent storage (long-term storage) like S3 regularly.</p><p>→Ingester sets a retention policy (automatic log deletion time) according to the configuration.</p><p>→It uses a time-series database to store the log in a certain structural format which eases the process of efficient querying and retiring logs.</p><p>→Additionally, the Ingester service is responsible for providing log data for in-memory queries on the read path.</p><p>→Within the Ingester service, there is a component called the lifecycler, which manages the lifecycle of each Ingester in the hash ring. This lifecycler handles tasks such as starting and stopping Ingesters, as well as managing their placement within the hash ring structure.</p><p>→chunks are compressed and closed when<br> <strong>Size limited reached</strong> (chunk_block_size:26144) [Close chunk when it reaches 256KB size]<br> <strong>Time limit reached</strong> (chunk_idle_period:1h) [Close chunk if no new logs arrive for 1 hour]<br> <strong>Forced flush happens</strong> (chunk_retain_period: 1h) [Keep closed chunks in memory for 1 hour before moving to persistence storage]</p><p>c) <strong>Querier </strong>:The Querier service is responsible for processing queries using the LogQL query language. It retrieves logs from both the Ingesters and long-term storage. When a query is received, the querier first retrieves in-memory data from all Ingesters. If the desired logs are not found in memory, the same query is executed against the backend store.</p><p>→ Due to the replication factor, there is a possibility of receiving duplicate data in the Querier. To handle this, the querier internally removes duplicate entries by comparing the nanosecond timestamp, label set, and log message. This deduplication process ensures that only unique logs are returned in the query results.</p><p>d) <strong>Query Frontend</strong>:The query frontend is an optional service providing the querier’s API endpoints and can be used to accelerate the read path.</p><p>→When the query frontend is in place, incoming query requests should be directed to the query frontend instead of the queriers. The querier service will be still required within the cluster, in order to execute the actual queries.</p><p>→The query frontend internally performs some query adjustments and holds queries in an internal queue. In this setup, queriers act as workers which pull jobs from the queue, execute them, and return them to the query frontend for aggregation. Queriers need to be configured with the query frontend address (via the -querier.frontend-address CLI flag) in order to allow them to connect to the query frontends.</p><p>→Query frontends are stateless. However, due to how the internal queue works, it’s recommended to run a few query frontend replicas to reap the benefit of fair scheduling. Two replicas should suffice in most cases</p><p>e)<strong>Cachin</strong>g: <br>→<strong>Metric Queries</strong>: The query frontend provides support for caching the results of metric queries, allowing them to be reused in subsequent queries. The result cache is compatible with various Loki caching backends, including memcached, Redis, and an in-memory cache. This caching mechanism enhances query performance by retrieving and serving cached results, reducing the need to fetch the same data from the underlying storage repeatedly.</p><p>Example Query: “How many errors per minute?”<br>- Saves result for reuse<br>- Like saving a calculation you do often</p><p>→<strong>Log Queries</strong>: The query frontend also supports caching of <strong>log queries</strong> in the form of a <strong>negative cache</strong>. This means that instead of caching the log results for quantized time ranges, Loki only caches empty results for quantized time ranges. This is more efficient than caching actual results because log queries are limited (usually 1000 results) and if you have a query over a long time range that matches only a few lines, and you only cache actual results, you’d still need to process a lot of data in addition to the data from the results cache in order to verify that nothing else matches.</p><p>Example Query: “Show all error logs”</p><p>- Instead of saving logs, saves “empty spaces”<br>- Example:<br> Time 1–2 PM: No errors (saved)<br> Time 2–3 PM: Has errors (not saved)</p><p>When same query comes:<br>- Skips checking 1–2 PM (known empty)<br>- Only checks 2–3 PM</p><p>→<strong> Index stats queries</strong>: The query frontend caches index stats query results similar to the <a href="https://grafana.com/docs/loki/latest/get-started/components/#metric-queries">metric query</a> results. This cache is only applicable when using single store TSDB.</p><p>→<strong>Log Volume queries</strong>:The query frontend caches log volume query results similar to the <a href="https://grafana.com/docs/loki/latest/get-started/components/#metric-queries">metric query</a> results. This cache is only applicable when using single store TSDB.</p><p>f) <strong>Consul:<br> </strong>A hash ring stored in <a href="https://www.consul.io/">Consul</a> is used to achieve consistent hashing, all <a href="https://grafana.com/docs/loki/latest/fundamentals/architecture/components/#ingester">Ingesters<strong><br></strong></a><strong> </strong>register themselves into the hash ring with a set of tokens they own.</p><p><strong>g) Compactor:<br> → </strong>Index File Consolidation</p><ul><li>When data is initially ingested into Loki, the ingesters create multiple index files and store them in object storage (like S3, GCS, etc.)</li><li>Having many small index files is inefficient for querying, as each lookup needs to check multiple files</li><li>The compactor periodically (at regular intervals) consolidates these index files into a single file per day per tenant</li><li>The process is:</li></ul><p>Download multiple index files from storage<br>Merge them into one consolidated file<br>Upload the new consolidated file<br>Remove the original smaller files</p><p>→ Performance Optimization</p><ul><li>By combining <strong>multiple small index files into a single larger file</strong>, the compactor improves query performance</li><li>When Loki needs to look up logs, it can now check one file instead of many</li><li>This is especially important for larger deployments where you might have many small index files</li></ul><p>→ Log Management</p><ul><li>The compactor handles<strong> log retention</strong> policies (how long to keep logs)</li><li>It manages log deletion when logs exceed their retention period</li><li>This helps manage storage costs and system performance</li></ul><p>h)<strong>Object Storage: </strong>The Object Store serves as the persistent storage backend for log<br> data in Loki. It can be a remote object storage service like Amazon S3 or Google <br> Cloud Storage, or local disk-based storage. The Object Store stores compressed <br> log chunks generated by the Ingester, which can be efficiently queried and retrieved <br> by the Querier.</p><p>i)<strong>Ruler:</strong>The ruler component in Loki is responsible for executing alerting rules <br> and generating alerts based on the log data ingested by Loki. It allows users <br> to define and configure rules that specify conditions or patterns to be <br> matched against the log stream. When a rule is triggered, the ruler component <br> generates alerts, which can be sent to various alerting platforms or <br> notification channels.</p><h3><strong>How are data flows handled in Loki?</strong></h3><p><strong>a) Write Path</strong></p><ul><li>Log Ingestion: Log entries from applications or agents are sent to the Loki Distributor.</li><li>Distributor: The Loki Distributor receives log entries and distributes them among the available Ingester instances using load balancing techniques. It ensures even distribution of log entries across the Ingester instances.</li><li>Ingester: Each Ingester instance receives log entries from the Loki Distributor. It handles the ingestion process by persisting the log entries into the storage layer. The Ingester performs tasks like log stream discovery, label extraction, chunking, and storing the compressed chunks in the configured Object Store.</li><li>Object Store: The Object Store serves as the persistent storage backend for log data in Loki. The Ingester writes the compressed log chunks to the Object Store, which can be a remote object storage service (e.g., Amazon S3, Google Cloud Storage) or a local disk-based storage.</li></ul><p><strong>b) Read Path</strong></p><ul><li>Query Request: A user submits a query request to the Loki Query Frontend.</li><li>Query Frontend: The Query Frontend serves as the entry point for user queries. It receives the query request and handles authentication and authorization. It then forwards the query to the Querier instances for processing.</li><li>Querier: The Querier instances receive queries from the Query Frontend. They interact with the Loki Index, which is a distributed index across multiple Querier instances. The Querier determines the relevant log chunks for the query by examining the index.</li><li>Loki Index: The Loki Index is responsible for locating the log chunks that contain the relevant data for a given query. It helps identify the log chunks based on the labels associated with the log entries. The Loki Index is distributed across the Querier instances and provides efficient querying capabilities.</li><li>Object Store Retrieval: The Querier communicates with the Object Store to fetch the log chunks that match the query. It retrieves the compressed log chunks from the Object Store based on the information obtained from the Loki Index.</li><li>Result Aggregation: The Querier aggregates the results received from the Object Store, combining the log data from different chunks into a coherent response.</li><li>Query Response: The Querier sends the aggregated query results back to the Query Frontend, which formats the results and sends them as a response to the user’s query.</li></ul><h3><strong>What are the clients of Loki?</strong></h3><p>Loki support variety of clients for sending log and they are Promtail, Docker Driver, Fluentd, Fluent Bit, Logstash and Lambda Promtail. Based on the nature of your usecase decide the client.</p><ul><li>Promtail: Promtail is the client of choice when running a Kubernetes, one can configure it to automatically scrape logs from pods running on the same node that Promtail runs on.</li><li>Docker Driver can be used for docker only usecase where Docker is running on a non-Kubernetes based environment.</li><li>Logstash, Fluent Bit and Fluentd can be used when already deployed in the target environment.</li></ul><h3><strong>What are Loki Deployment modes?</strong></h3><ul><li><strong>Monolith Mode<br></strong>In this mode, Loki is deployed as a single binary and runs as a single process. All Loki components, such as the distributor, ingester, querier, and query frontend, are part of the same Loki instance. This mode is suitable for smaller deployments or for testing and development purposes.</li><li><strong>Microservices Mode<br></strong>In the microservices mode, Loki components are deployed as separate services, allowing for scalability and isolation. Each component, such as the distributor, ingester, querier, and query frontend, is deployed as an independent service and can be scaled individually based on the workload. This mode is suitable for larger deployments and provides better resource utilization and flexibility.</li></ul><h3>Deployment of Promtail:</h3><pre>--- # Daemonset.yaml<br>apiVersion: apps/v1<br>kind: DaemonSet<br>metadata:<br>  name: promtail-daemonset<br>spec:<br>  selector:<br>    matchLabels:<br>      name: promtail<br>  template:<br>    metadata:<br>      labels:<br>        name: promtail<br>    spec:<br>      serviceAccount: promtail-serviceaccount<br>      containers:<br>      - name: promtail-container<br>        image: grafana/promtail<br>        args:<br>        - -config.file=/etc/promtail/promtail.yaml<br>        env: <br>        - name: &#39;HOSTNAME&#39; # needed when using kubernetes_sd_configs<br>          valueFrom:<br>            fieldRef:<br>              fieldPath: &#39;spec.nodeName&#39;<br>        volumeMounts:<br>        - name: logs<br>          mountPath: /var/log<br>        - name: promtail-config<br>          mountPath: /etc/promtail<br>        - mountPath: /var/lib/docker/containers<br>          name: varlibdockercontainers<br>          readOnly: true<br>      volumes:<br>      - name: logs<br>        hostPath:<br>          path: /var/log<br>      - name: varlibdockercontainers<br>        hostPath:<br>          path: /var/lib/docker/containers<br>      - name: promtail-config<br>        configMap:<br>          name: promtail-config<br>--- # configmap.yaml<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: promtail-config<br>data:<br>  promtail.yaml: |<br>    server:<br>      http_listen_port: 9080<br>      grpc_listen_port: 0<br><br>    clients:<br>    - url: https://{YOUR_LOKI_ENDPOINT}/loki/api/v1/push<br><br>    positions:<br>      filename: /tmp/positions.yaml<br>    target_config:<br>      sync_period: 10s<br>    scrape_configs:<br>    - job_name: pod-logs<br>      kubernetes_sd_configs:<br>        - role: pod<br>      pipeline_stages:<br>        - docker: {}<br>      relabel_configs:<br>        - source_labels:<br>            - __meta_kubernetes_pod_node_name<br>          target_label: __host__<br>        - action: labelmap<br>          regex: __meta_kubernetes_pod_label_(.+)<br>        - action: replace<br>          replacement: $1<br>          separator: /<br>          source_labels:<br>            - __meta_kubernetes_namespace<br>            - __meta_kubernetes_pod_name<br>          target_label: job<br>        - action: replace<br>          source_labels:<br>            - __meta_kubernetes_namespace<br>          target_label: namespace<br>        - action: replace<br>          source_labels:<br>            - __meta_kubernetes_pod_name<br>          target_label: pod<br>        - action: replace<br>          source_labels:<br>            - __meta_kubernetes_pod_container_name<br>          target_label: container<br>        - replacement: /var/log/pods/*$1/*.log<br>          separator: /<br>          source_labels:<br>            - __meta_kubernetes_pod_uid<br>            - __meta_kubernetes_pod_container_name<br>          target_label: __path__<br><br>--- # Clusterrole.yaml<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: promtail-clusterrole<br>rules:<br>  - apiGroups: [&quot;&quot;]<br>    resources:<br>    - nodes<br>    - services<br>    - pods<br>    verbs:<br>    - get<br>    - watch<br>    - list<br><br>--- # ServiceAccount.yaml<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: promtail-serviceaccount<br><br>--- # Rolebinding.yaml<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: promtail-clusterrolebinding<br>subjects:<br>    - kind: ServiceAccount<br>      name: promtail-serviceaccount<br>      namespace: default<br>roleRef:<br>    kind: ClusterRole<br>    name: promtail-clusterrole<br>    apiGroup: rbac.authorization.k8s.io</pre><p>kubectl apply -f above_file_name.yaml</p><h3>Deployment of Loki:-</h3><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: loki-service  # Name of the Kubernetes service<br>  namespace: default  # The namespace in which the service will be created<br>spec:<br>  type: NodePort  # The service type is NodePort, exposing the service on a port on each node<br>  selector:<br>    app: loki  # The label selector for the pod this service targets<br>  ports:<br>  - name: http  # Name of the port<br>    port: 3100  # Port exposed by the service<br>    targetPort: 3100  # The port on the container to forward traffic to (same as the service port in this case)<br><br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: loki  # Name of the deployment<br>  namespace: default  # The namespace where the deployment will be created<br>spec:<br>  replicas: 1  # The number of pod replicas to create<br>  selector:<br>    matchLabels:<br>      app: loki  # This selector matches pods with the label `app=loki`<br>  template:<br>    metadata:<br>      labels:<br>        app: loki  # Label applied to the pod for identification and service routing<br>    spec:<br>      containers:<br>      - name: loki  # Name of the container in the pod<br>        image: grafana/loki:2.7.3  # The Docker image for Loki<br>        args:<br>        - -config.file=/etc/loki/loki-config.yaml  # Argument to specify the configuration file for Loki<br>        - -target=all  # Run Loki in &#39;all&#39; mode, enabling all components<br>        - -log.level=debug  # Set Loki log level to debug for more detailed logs<br>        ports:<br>        - name: http  # Name of the port exposed by the container<br>          containerPort: 3100  # Port the container listens on<br>        volumeMounts:<br>        - name: loki-config  # Mounting the configMap for Loki&#39;s configuration file<br>          mountPath: /etc/loki/loki-config.yaml  # Path inside the container where the config file will be mounted<br>          subPath: loki-config.yaml  # This mounts the configMap file as a single file with a specific name<br>          readOnly: true  # The config file is read-only<br>        - name: loki-storage  # Mounting an emptyDir volume for temporary storage<br>          mountPath: /data  # Path inside the container where storage is mounted<br>        - name: loki-wal  # Mounting an emptyDir volume for Write-Ahead Logs (WAL)<br>          mountPath: /wal  # Path inside the container where WAL will be mounted<br>        securityContext:  # Security context for running the container<br>          runAsUser: 0  # The container will run as the root user (useful for debugging and testing)<br>      volumes:<br>      - name: loki-config  # ConfigMap volume for Loki&#39;s configuration<br>        configMap:<br>          name: loki-config  # Name of the configMap<br>          items:<br>          - key: loki-config.yaml  # Key within the configMap containing the Loki configuration<br>            path: loki-config.yaml  # Path where it will be available inside the container<br>      - name: loki-storage  # Temporary storage volume for Loki data<br>        emptyDir: {}  # Defines an emptyDir volume, meaning the data is stored temporarily and is lost when the pod is removed<br>      - name: loki-wal  # Write-Ahead Log volume<br>        emptyDir: {}  # Defines another emptyDir volume for WAL logs<br>---<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: loki-config  # The name of the configMap containing the Loki configuration<br>  namespace: default  # Namespace for the configMap<br>data:<br>  loki-config.yaml: |  # Configuration data in YAML format<br>    auth_enabled: false  # Disable authentication for Loki (not recommended for production)<br>    <br>    server:<br>      http_listen_port: 3100  # Loki will listen for HTTP requests on port 3100<br>    <br>    distributor:<br>      ring:<br>        kvstore:<br>          store: memberlist  # Using memberlist for storing the ring data (helps in distributing logs)<br><br>    ingester:<br>      lifecycler:<br>        ring:<br>          kvstore:<br>            store: memberlist  # Using memberlist for storing ingester ring data<br>          replication_factor: 1  # Number of replicas for ingester data<br>        final_sleep: 0s  # Time to wait before the ingester starts after lifecycle changes<br>      chunk_idle_period: 5m  # Time after which chunks are considered idle<br>      chunk_retain_period: 30m  # Time to retain a chunk in memory before eviction<br>        # push_interval: 100m  # This could set the interval at which the ingester pushes data (commented out)<br><br>    memberlist:<br>      abort_if_cluster_join_fails: false  # Don&#39;t abort if Loki fails to join the cluster<br>      bind_port: 7946  # Port for memberlist to bind to<br>      max_join_backoff: 1m  # Maximum backoff time before retrying to join the cluster<br>      max_join_retries: 10  # Maximum retries for joining the cluster<br>      min_join_backoff: 1s  # Minimum backoff time for retries<br><br>    schema_config:<br>      configs:<br>      - from: 2020-05-15  # The start date for this configuration (versioning)<br>        store: boltdb-shipper  # Loki will use the BoltDB shipper for indexing<br>        object_store: s3  # S3 is used for object storage<br>        schema: v11  # Schema version<br>        index:<br>          prefix: index_  # Prefix for index objects<br>          period: 24h  # Index rotation period (one day)<br><br>    storage_config:<br>      boltdb_shipper:<br>        active_index_directory: /loki/index  # Directory for active index files<br>        cache_location: /loki/index_cache  # Cache location for index files<br>        shared_store: s3  # Using S3 as the shared storage backend<br><br>      aws:<br>        s3: s3://awskeys+@awsregion/bucket/loki  # S3 bucket URL for Loki storage<br>        s3forcepathstyle: true  # Enforce path style access to S3 (useful for some S3-compatible services)<br><br>    limits_config:<br>      enforce_metric_name: false  # Allow metric names to be flexible<br>      reject_old_samples: true  # Reject log samples that are older than the max age<br>      reject_old_samples_max_age: 168h  # Max age for logs before rejecting them (7 days)<br><br>    compactor:<br>      working_directory: /data/compactor  # Directory for compactor to store its working files<br>      shared_store: s3  # S3 is used for shared compaction storage<br>      compaction_interval: 5m  # Interval for running log compaction (5 minutes)</pre><p>kubectl apply -f above_file_name.yaml</p><p>Go To Grafana and add Loki as the endpoint:-</p><h3>Step 1: Log in to Grafana</h3><ul><li>Open your Grafana dashboard and log in.</li></ul><h3>Step 2: Go to Data Sources</h3><ul><li>Click the <strong>gear icon</strong> (⚙️) on the left sidebar.</li><li>Select <strong>Data Sources</strong>.</li></ul><h3>Step 3: Add Loki</h3><ul><li>Click <strong>Add data source</strong>.</li><li>Select <strong>Loki</strong> from the list.</li></ul><h3>Step 4: Configure Loki</h3><ul><li>In the <strong>URL</strong> field, enter your Loki server URL (e.g., http://&lt;Loki-URL&gt;:3100).</li><li>Under <strong>Access</strong>, choose <strong>Server</strong> if Grafana connects via backend or <strong>Browser</strong> if it’s via the user’s browser.</li></ul><h3>Step 5: Save and Test</h3><ul><li>Click <strong>Save &amp; Test</strong> to check if the connection is working.</li></ul><h3>Step 6: Use Loki</h3><ul><li>Create a new dashboard, add a panel, and select <strong>Loki</strong> as the data source.</li></ul><p>You’re done! Now you can query and view logs from Loki in Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQafo_Oo9fPBArFYtupMCw.png" /></figure><h3><strong>Conclusion:</strong></h3><p>Loki is an excellent tool for aggregating and querying logs in a Kubernetes environment. By integrating it with Grafana, you can gain valuable insights into your system’s health and performance. With its lightweight architecture, powerful query capabilities, and seamless integration with other tools, Loki simplifies the process of managing logs at scale.</p><p>Whether you’re troubleshooting an issue, monitoring application behavior, or seeking to optimize your infrastructure, Loki provides a streamlined, efficient solution for log aggregation and analysis. By setting up Loki in your Kubernetes cluster, you’re empowering your team to stay on top of logs without the complexity of traditional logging systems, making your workflow faster, smarter, and more reliable.</p><p>As you continue to scale and optimize your monitoring systems, keep in mind that Loki’s flexibility and ease of use make it a valuable tool for any modern DevOps toolkit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*jD3e0GO2m2u7ejQ1DGWPNA.gif" /></figure><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><h3>References</h3><ol><li><a href="https://grafana.com/docs/loki/latest/send-data/promtail/installation/">https://grafana.com/docs/loki/latest/send-data/promtail/installation/</a></li><li><a href="https://grafana.com/docs/loki/latest/get-started/architecture/">https://grafana.com/docs/loki/latest/get-started/architecture/</a></li><li><a href="https://grafana.com/docs/loki/latest/get-started/components/">https://grafana.com/docs/loki/latest/get-started/components/</a></li><li><a href="https://www.youtube.com/watch?v=_hv4i84Z68s">https://www.youtube.com/watch?v=_hv4i84Z68s</a> [must watch to understand better]</li><li><a href="https://devopscube.com/setup-grafana-loki/">https://devopscube.com/setup-grafana-loki/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf0b67f16371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discovering Prometheus: Unpacking the Pods Behind the Power]]></title>
            <link>https://medium.com/@sidhusangani/discovering-prometheus-unpacking-the-pods-behind-the-power-35b11cfa3967?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b11cfa3967</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 06:50:41 GMT</pubDate>
            <atom:updated>2024-11-26T07:48:24.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_Yfc5k5VNY_K3mjNKLeWw.png" /></figure><p>When I first deployed Prometheus with Helm, I thought, “Great! One simple pod, up and running, and I’ll be on my way.” But instead, a whole gang of pods appeared — each with its own name, looking like they’d rolled in for some kind of pod party. I stood there, a little dazed, scanning the lineup: <strong>kube-state-metrics</strong>, <strong>alert-manager</strong>, <strong>push-gateway</strong>, <strong>node-exporter</strong>… wait, what? Only <strong>Prometheus-server</strong> made sense, but the rest? They had me scratching my head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*KKMTPdFNJdng5gAVnguqVw.png" /></figure><p>It felt like I’d walked into a team meeting where I only knew one person — and the rest were staring at me like, “Oh, we’re essential too, you’ll see.” Apparently, Prometheus didn’t just need a pod; it needed an entire entourage, each with its own job, all just to keep tabs on metrics!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*E3_trI4XlMT1e0vOpn3RLg.gif" /><figcaption>my honest reaction</figcaption></figure><p>Why does a metric collector need an alert manager? A push-gateway? And kube-state-metrics? These pods sounded more like job titles at a startup than what I’d imagined Prometheus needed. But as it turns out, there’s a method to this madness.</p><p>To understand this setup better, I decided to take a different approach: using deployment files instead of Helm. This allowed me to see each component up close and learn what each of these pods does, how they interact, and why they’re essential to Prometheus’s design.</p><p>This unexpected setup led me down a path to understand Prometheus in depth — from its architecture to the details of its deployment. In this post, I’ll share that journey with you, and together, we’ll uncover the purpose behind each pod and the structure of Prometheus.</p><h3>Observability and Prometheus</h3><p>Before diving into the details, let’s start with a quick primer on <strong>observability</strong>. Observability is all about understanding and measuring the state of a system through its generated data. This visibility allows us to catch issues early, troubleshoot faster, and monitor performance more accurately. It’s built on three key pillars:</p><ol><li><strong>Logging</strong>: Captures specific events in the system, complete with timestamps and messages for each event.</li><li><strong>Metrics</strong>: Provides quantitative insights into system performance, such as CPU load, error counts, and response times.</li><li><strong>Traces</strong>: Follows individual requests as they travel through different services, showing how processes work together.</li></ol><p>Prometheus is a tool that focuses on metrics, providing us with the numbers and data we need to understand how our systems are performing and evolving.</p><p>Let’s dive in, step-by-step, to explore Prometheus’s architecture, components, and ultimately how to deploy it effectively.</p><h3>Understanding Prometheus Architecture</h3><p>Now, back to those mysterious pods! Prometheus’s architecture is modular, designed to separate different functions for scalability and efficiency. Here’s a breakdown of its core components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*nUK-sHSS-3rj4-Pq" /></figure><ol><li><strong>Retrieval</strong>:<br>The retrieval worker in Prometheus is responsible for collecting metrics from various targets. It sends HTTP requests to the /metrics endpoint of each target, pulling data at regular intervals.<br><em>Example</em>: Suppose we have a web server exposing metrics at http://localhost:8080/metrics. Prometheus will periodically request this endpoint, retrieve data on metrics like CPU usage, memory utilization, and request counts, and store it in its database.</li><li><strong>Time Series Database (TSDB)</strong>:<br>The retrieved metrics are stored in Prometheus’s Time Series Database (TSDB). This database keeps a record of every metric, timestamped, to provide historical data and support trend analysis.<br><em>Example</em>: If Prometheus scrapes the CPU usage metric from a server every 15 seconds, the TSDB will store each value with a timestamp, allowing you to see trends over time, like increased CPU usage during peak hours.</li><li><strong>HTTP Server and PromQL</strong>:<br>The Prometheus HTTP server allows users to query data stored in the TSDB. PromQL, Prometheus’s query language, is used to specify queries to retrieve and analyze metric data.<br><em>Example</em>: To view the average CPU usage of a server over the past hour, you could run a PromQL query like avg(rate(cpu_usage[1h])), which retrieves data from the TSDB and calculates the average.</li><li><strong>Jobs/Exporters</strong>:<br>Exporters are mini-processes running on targets to expose internal metrics in a format Prometheus can understand. For each type of target (e.g., Linux servers, MySQL databases), Prometheus uses a specific exporter to collect relevant metrics.<br><em>Example</em>: A common exporter is the Node Exporter for Linux. When installed on a Linux server, it collects system-level metrics, like CPU load, memory usage, and disk I/O, and makes these metrics available for Prometheus to scrape at the /metrics endpoint.</li><li><strong>Short-lived Jobs and Pushgateway</strong>:<br>Short-lived jobs, like batch processes, may end before Prometheus has a chance to scrape them. Pushgateway is used in such cases to push data to Prometheus directly.<br><em>Example</em>: Imagine a nightly job that processes logs. This job completes quickly and exits before Prometheus can scrape it. Instead, the job can push its metrics to Pushgateway, which Prometheus scrapes, ensuring the metrics are still captured.</li><li><strong>Service Discovery</strong>:<br>In dynamic environments, like Kubernetes or AWS EC2, hardcoding the list of targets isn’t practical. Service discovery automatically updates Prometheus’s list of targets by discovering services in real time.<br><em>Example</em>: In a Kubernetes cluster, service discovery allows Prometheus to automatically detect new pods or services that expose metrics, without needing manual configuration.</li><li><strong>Alertmanager</strong>:<br>While Prometheus can trigger alerts based on metric thresholds, it doesn’t send notifications. Alertmanager handles alert notifications, routing them to platforms like Slack, email, or SMS.<br><em>Example</em>: You set an alert to notify you if CPU usage exceeds 90%. When this happens, Prometheus sends the alert to Alertmanager, which can then notify your team on Slack, email, or other integrated services.</li><li><strong>Prometheus UI / Grafana</strong>:<br>To visualize metrics, Prometheus provides a basic UI for running PromQL queries, while Grafana offers advanced visualization features and dashboards. Grafana queries Prometheus’s HTTP server to present data in real-time charts and graphs.<br><em>Example</em>: In Grafana, you could create a dashboard displaying CPU and memory usage over time, making it easy to monitor application health visually.</li></ol><h3>Pull-Based vs. Push-Based Monitoring: Benefits and Use Cases</h3><p>Prometheus primarily follows a pull-based model, where it scrapes metrics from targets. Here’s why this approach is beneficial, and when a push-based system, like Pushgateway, is more appropriate.</p><p><strong>Pull-Based Benefits</strong>:-</p><ul><li><strong>Easier Target Monitoring</strong>: If a target goes down, Prometheus will detect it automatically by failing to scrape it.</li><li><strong>Controlled Load</strong>: Pulling data avoids the risk of overloading the Prometheus server with too many connections at once, which can occur in push-based systems.</li><li><strong>Centralized Configuration</strong>: Prometheus maintains a definitive list of targets, creating a single source of truth for monitoring.</li></ul><p><strong>Push-Based Use Cases</strong>:-</p><ul><li><strong>Event-Driven Systems</strong>: Some events happen irregularly or too quickly for a pull-based approach.</li><li><strong>Short-Lived Jobs</strong>: Jobs that complete quickly, like nightly data processing, can use Pushgateway to make their metrics accessible to Prometheus.</li></ul><p>Now that we know the architecture let&#39;s set up Prometheus with Deployment files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*oOMcL2_TtELFksoK4PM_Gw.jpeg" /></figure><p>Here’s a simplified guide to installing Prometheus using deployment files:</p><h3>Step 1: Clone the Repository</h3><p>Clone the Kubernetes Prometheus setup from GitHub:</p><pre>git clone https://github.com/techiescamp/kubernetes-prometheus</pre><h3>Step 2: Create a Namespace for Monitoring</h3><pre>kubectl create namespace monitoring</pre><h3>Step 3: Set Up RBAC Permissions</h3><p>Prometheus needs permission to access Kubernetes metrics. We’ll create an RBAC policy to give it read access.</p><ol><li>Create a file named clusterRole.yaml with the following content:</li></ol><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: prometheus<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources:<br>  - nodes<br>  - nodes/proxy<br>  - services<br>  - endpoints<br>  - pods<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;]<br>- apiGroups:<br>  - extensions<br>  resources:<br>  - ingresses<br>  verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;]<br>- nonResourceURLs: [&quot;/metrics&quot;]<br>  verbs: [&quot;get&quot;]<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: prometheus<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: prometheus<br>subjects:<br>- kind: ServiceAccount<br>  name: default<br>  namespace: monitoring</pre><ol><li>Apply the file to create the role and binding:</li></ol><ul><li>kubectl create -f clusterRole.yaml</li></ul><h3>Step 4: Configure Prometheus with a ConfigMap</h3><p>Prometheus configuration is stored in a ConfigMap, which allows updates without rebuilding the image.</p><ol><li>Create a config-map.yaml file. You can find an example config <a href="https://github.com/techiescamp/kubernetes-prometheus">here</a>.</li><li>Apply the ConfigMap:</li></ol><ul><li>kubectl create -f config-map.yaml</li></ul><h3>Step 5: Deploy Prometheus</h3><ol><li>Create a prometheus-deployment.yaml file with the following content:</li></ol><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: prometheus-deployment<br>  namespace: monitoring<br>  labels:<br>    app: prometheus-server<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: prometheus-server<br>  template:<br>    metadata:<br>      labels:<br>        app: prometheus-server<br>    spec:<br>      containers:<br>        - name: prometheus<br>          image: prom/prometheus<br>          args:<br>            - &quot;--storage.tsdb.retention.time=12h&quot;<br>            - &quot;--config.file=/etc/prometheus/prometheus.yml&quot;<br>            - &quot;--storage.tsdb.path=/prometheus/&quot;<br>          ports:<br>            - containerPort: 9090<br>          resources:<br>            requests:<br>              cpu: 500m<br>              memory: 500M<br>            limits:<br>              cpu: 1<br>              memory: 1Gi<br>          volumeMounts:<br>            - name: prometheus-config-volume<br>              mountPath: /etc/prometheus/<br>            - name: prometheus-storage-volume<br>              mountPath: /prometheus/<br>      volumes:<br>        - name: prometheus-config-volume<br>          configMap:<br>            defaultMode: 420<br>            name: prometheus-server-conf<br>  <br>        - name: prometheus-storage-volume<br>          emptyDir: {}</pre><p>2. Deploy Prometheus:</p><ul><li>kubectl create -f prometheus-deployment.yaml</li></ul><p>3. Verify the deployments:</p><ul><li>kubectl get deployments --namespace=monitoring</li></ul><p>This setup provides a basic Prometheus installation. For production, consider adding persistent storage.</p><p>4. k8s Service of Prometheus:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: prometheus-service<br>  namespace: monitoring<br>  annotations:<br>      prometheus.io/scrape: &#39;true&#39;<br>      prometheus.io/port: &#39;9090&#39;<br>spec:<br>  selector: <br>    app: prometheus-server<br>  type: ClusterIP  # Changed to ClusterIP<br>  ports:<br>    - port: 9090  # Use port 9090 for Prometheus&#39; web interface<br>      targetPort: 9090  # Target Prometheus container&#39;s port</pre><p>Now that grafana is pre-installed let me add Promtheus as a source in grafana.</p><ul><li><strong>Open Grafana</strong>: Go to your Grafana instance in a web browser and log in.</li><li><strong>Add Data Source</strong>:<br>Click on <strong>Settings</strong> (gear icon) in the left menu, then go to <strong>Data Sources</strong>.<br>Click <strong>Add data source.</strong></li><li><strong>Select Prometheus</strong>: Find and click on <strong>Prometheus</strong> from the list.</li><li><strong>Enter Prometheus URL</strong>:<br>In the <strong>URL</strong> field, enter</li></ul><pre>http://prometheus-service.monitoring.svc.cluster.local:9090</pre><ul><li><strong>Save &amp; Test</strong>: Click <strong>Save &amp; Test</strong> to check the connection. You should see a success message if it’s working.</li></ul><p>but the Sad part is still can’t see any metrics in the grafana dashboard after importing dashboards</p><p>15760 --&gt; Kubernetes / Views / Pods<br>18283 --&gt; Kubernetes Dashboard<br>17375 --&gt; K8s Resource Monitoring<br>15759 --&gt; Kubernetes / Views / Nodes<br>1860 --&gt; Node Exporter Full .</p><p>Now I know the importance of other pods and why it is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*lO6933nI2rANF3Fh8Zbxiw.gif" /></figure><h3><strong>Setting Up kube-state-metrics.</strong></h3><p><strong>What is Kube State Metrics?</strong> Kube State Metrics is a service that collects metrics from Kubernetes API objects like Deployments, Pods, StatefulSets, etc., and formats them for Prometheus. These metrics are exposed at the /metrics endpoint for Prometheus to scrape.</p><p><strong>Important Metrics Collected</strong>:</p><ul><li>Node status and capacity</li><li>ReplicaSet and Pod status</li><li>Ingress, PV, PVC metrics</li><li>DaemonSet, StatefulSet metrics</li><li>Resource requests/limits</li><li>Job and CronJob metrics</li></ul><p><strong>Setup for Kube State Metrics</strong>:</p><ol><li><strong>Clone Repo</strong>:</li></ol><ul><li>git clone <a href="https://github.com/devopscube/kube-state-metrics-configs.git">https://github.com/devopscube/kube-state-metrics-configs.git</a></li></ul><p><strong>2. Deploy Objects</strong>:</p><ul><li>kubectl apply -f kube-state-metrics-configs/</li></ul><p><strong>3. Check Deployment</strong>:</p><ul><li>kubectl get deployments kube-state-metrics -n kube-system</li></ul><p><strong>Prometheus Configuration</strong>: To have Prometheus scrape these metrics, add this job configuration to your Prometheus config (if it’s not already there):</p><pre>- job_name: &#39;kube-state-metrics&#39;<br>  static_configs:<br>    - targets: [&#39;kube-state-metrics.kube-system.svc.cluster.local:8080&#39;]</pre><p>This configuration uses a static target to help Prometheus find the kube-state-metrics service by pointing directly to its stable DNS name: kube-state-metrics.kube-system.svc.cluster.local:8080. While this approach doesn’t involve true Kubernetes service discovery, it still allows Prometheus to scrape metrics reliably, as the DNS name remains consistent even if the underlying pods scale up, down, or change</p><h3>Setting Up alert-manager.</h3><h3>Prerequisites</h3><ul><li>Ensure Prometheus is up and running.</li><li>Prometheus should be configured to send alerts to Alertmanager by adding this to config.yaml.</li></ul><pre>alerting:<br>  alertmanagers:<br>    - scheme: http<br>      static_configs:<br>        - targets:<br>          - &quot;alertmanager.monitoring.svc:9093&quot;</pre><h3>Step 1: Clone the Repository</h3><p>Clone the setup files.</p><pre>git clone https://github.com/bibinwilson/kubernetes-alert-manager.git</pre><h3>Step 2: Configure Alertmanager</h3><p>Alertmanager requires two ConfigMaps:</p><ol><li><strong>Config Map for Alertmanager</strong> (config.yml) — defines alert routes and receivers (like email, Slack):</li></ol><pre>kind: ConfigMap<br>apiVersion: v1<br>metadata:<br>  name: alertmanager-config<br>  namespace: monitoring<br>data:<br>  config.yml: |-<br>    global:<br>    templates:<br>    - &#39;/etc/alertmanager/*.tmpl&#39;<br>    route:<br>      receiver: alert-emailer<br>      group_by: [&#39;alertname&#39;, &#39;priority&#39;]<br>      group_wait: 10s<br>      repeat_interval: 30m<br>      routes:<br>        - receiver: slack_demo<br>        # Send severity=slack alerts to slack.<br>          match:<br>            severity: slack<br>          group_wait: 10s<br>          repeat_interval: 1m<br> <br>    receivers:<br>    - name: alert-emailer<br>      email_configs:<br>      - to: demo@devopscube.com<br>        send_resolved: false<br>        from: from-email@email.com<br>        smarthost: smtp.eample.com:25<br>        require_tls: false<br>    - name: slack_demo<br>      slack_configs:<br>      - api_url: https://hooks.slack.com/services/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sz4Qk<br>        channel: &#39;#devopscube-demo&#39;</pre><ol><li>Apply with:</li></ol><ul><li>kubectl apply -f AlertManagerConfigmap.yaml</li></ul><ol><li><strong>Config Map for Alert Templates</strong> — create templates for email or Slack alerts as needed.</li></ol><ul><li>kubectl apply -f AlertTemplateConfigMap.yaml</li></ul><h3>Step 3: Deploy Alertmanager</h3><p>Create a Deployment for Alertmanager to mount the config files:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: alertmanager<br>  namespace: monitoring<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: alertmanager<br>  template:<br>    metadata:<br>      labels:<br>        app: alertmanager<br>    spec:<br>      containers:<br>      - name: alertmanager<br>        image: prom/alertmanager:latest<br>        args:<br>          - &quot;--config.file=/etc/alertmanager/config.yml&quot;<br>          - &quot;--storage.path=/alertmanager&quot;<br>        ports:<br>          - containerPort: 9093<br>        volumeMounts:<br>          - name: config-volume<br>            mountPath: /etc/alertmanager<br>          - name: templates-volume<br>            mountPath: /etc/alertmanager-templates<br>        volumes:<br>          - name: config-volume<br>            configMap:<br>              name: alertmanager-config<br>          - name: templates-volume<br>            configMap:<br>              name: alertmanager-templates</pre><p>Apply the deployment:</p><pre>kubectl apply -f Deployment.yaml</pre><h3>Step 4: Expose Alertmanager Service</h3><p>Create a NodePort or LoadBalancer Service to access the Alertmanager UI and enable Prometheus scraping:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: alertmanager<br>  namespace: monitoring<br>  annotations:<br>    prometheus.io/scrape: &#39;true&#39;<br>    prometheus.io/port: &#39;9093&#39;<br>spec:<br>  selector:<br>    app: alertmanager<br>  type: NodePort<br>  ports:<br>    - port: 9093<br>      targetPort: 9093<br>      nodePort: 31000</pre><p>Apply the service:</p><pre>kubectl apply -f Service.yaml</pre><p>With these steps, Alertmanager is set up to receive alerts from Prometheus and can send notifications to configured receivers like email and Slack.</p><h3>Setting up Prometheus Node Exporter on Kubernetes</h3><p><strong>Node Exporter Overview</strong><br>Node Exporter collects hardware and OS-level metrics on Linux systems, allowing detailed insights on CPU, memory, disk, and network usage. While Kubernetes provides cluster-level metrics via Metric Server and container-level metrics through cAdvisor, it doesn’t provide node-level metrics, which Node Exporter adds.</p><p><strong>Why Node Exporter on Kubernetes?</strong><br>Node Exporter runs as a DaemonSet on each node in the cluster, ensuring each node’s system metrics are available via /metrics endpoint on port 9100. Prometheus then scrapes these endpoints for node-level insights.</p><h3>Steps for Setup</h3><h3>Clone the Github repo</h3><pre>git clone https://github.com/devopscube/kube-state-metrics-configs.git</pre><ol><li><strong>Create DaemonSet</strong></li></ol><pre>apiVersion: apps/v1<br>kind: DaemonSet<br>metadata:<br>  labels:<br>    app.kubernetes.io/component: exporter<br>    app.kubernetes.io/name: node-exporter<br>  name: node-exporter<br>  namespace: monitoring<br>spec:<br>  selector:<br>    matchLabels:<br>      app.kubernetes.io/component: exporter<br>      app.kubernetes.io/name: node-exporter<br>  template:<br>    metadata:<br>      labels:<br>        app.kubernetes.io/component: exporter<br>        app.kubernetes.io/name: node-exporter<br>    spec:<br>      containers:<br>      - args:<br>        - --path.sysfs=/host/sys<br>        - --path.rootfs=/host/root<br>        - --no-collector.wifi<br>        - --no-collector.hwmon<br>        - --collector.filesystem.ignored-mount-points=^/(dev|proc|sys|var/lib/docker/.+|var/lib/kubelet/pods/.+)($|/)<br>        - --collector.netclass.ignored-devices=^(veth.*)$<br>        name: node-exporter<br>        image: prom/node-exporter<br>        ports:<br>          - containerPort: 9100<br>            protocol: TCP<br>        resources:<br>          limits:<br>            cpu: 250m<br>            memory: 180Mi<br>          requests:<br>            cpu: 102m<br>            memory: 180Mi<br>        volumeMounts:<br>        - mountPath: /host/sys<br>          mountPropagation: HostToContainer<br>          name: sys<br>          readOnly: true<br>        - mountPath: /host/root<br>          mountPropagation: HostToContainer<br>          name: root<br>          readOnly: true<br>      volumes:<br>      - hostPath:<br>          path: /sys<br>        name: sys<br>      - hostPath:<br>          path: /<br>        name: root</pre><ul><li>Deploy Node Exporter as a DaemonSet to ensure one instance runs on each node.</li><li>Exposes metrics on port 9100.</li></ul><pre>kubectl create -f daemonset.yaml</pre><p><strong>2. Verify DaemonSet</strong></p><ul><li>Check if Node Exporter is deployed on all nodes.</li></ul><pre>kubectl get daemonset -n monitoring</pre><p><strong>3. Create Service</strong></p><ul><li>Define a service to expose Node Exporter metrics on port 9100, allowing Prometheus to scrape node metrics.</li></ul><pre>---<br>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: node-exporter<br>  namespace: monitoring<br>  annotations:<br>      prometheus.io/scrape: &#39;true&#39;<br>      prometheus.io/port:   &#39;9100&#39;<br>spec:<br>  selector:<br>      app.kubernetes.io/component: exporter<br>      app.kubernetes.io/name: node-exporter<br>  ports:<br>  - name: node-exporter<br>    protocol: TCP<br>    port: 9100<br>    targetPort: 9100</pre><pre>kubectl create -f service.yaml</pre><p><strong>4. Check Service Endpoints</strong></p><ul><li>Ensure the service routes to all Node Exporter pods.</li></ul><pre>kubectl get endpoints -n monitoring</pre><p>Now Prometheus can scrape metrics from the Node Exporter service to monitor node-level metrics across the Kubernetes cluster.</p><p>Now you should be able to see metrics in grafana.</p><p>And that’s how you tame Prometheus… or at least get it to stop screaming at you. Setting up monitoring is like assembling IKEA furniture — at first, you’re confused, then you find a piece you didn’t know existed, and by the end, you’re just hoping it doesn’t collapse on you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*NCWjlRxzZqGaMST70QH_pw.gif" /></figure><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><h3>References</h3><ol><li><a href="https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/">https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/</a></li><li><a href="https://prometheus.io/docs/introduction/overview/">https://prometheus.io/docs/introduction/overview/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b11cfa3967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Beat the GKE Ingress Controller Limitation: A Journey to NGINX Ingress]]></title>
            <link>https://medium.com/@sidhusangani/how-we-beat-the-gke-ingress-controller-limitation-a-journey-to-nginx-ingress-e85bcc68b4c8?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85bcc68b4c8</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[gke-ingress]]></category>
            <category><![CDATA[nginx-ingress-controller]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 06:15:15 GMT</pubDate>
            <atom:updated>2024-11-12T06:15:15.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZppAbBHX43-cQlwGtyZUA.png" /></figure><p>In the world of Kubernetes, setting up an Ingress controller seems simple at first glance. However, as we discovered, sometimes even the most well-prepared plans can go awry, and troubleshooting becomes an adventure in itself. In this story, we’ll walk through our journey from attempting to create a regional external load balancer on Google Kubernetes Engine (GKE) to finally implementing the NGINX Ingress Controller to overcome limitations. Along the way, we’ll dive into technical hurdles and our methods for handling them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVdFSjdNziCzO-VfdLYvyw.png" /><figcaption>Ingress-Managed Global Load Balancer (GKE)</figcaption></figure><h3>The Challenge: Regional Routing Limitations in GKE Ingress Controller</h3><p>Our story begins with a desire for a simple yet essential feature: a regional external load balancer with HTTPS routing. As we configured the GKE Ingress controller, we discovered an unexpected limitation — it only allowed us to create global load balancers with external IP addresses that routed requests through specific regions, often resulting in traffic originating from the United States. For our application, regional traffic distribution was crucial to maintain performance and localization for users.</p><h4>Attempts to Work Around the Limitation</h4><p>We tried three different approaches to solve this:</p><ol><li><strong>Regional External Ingress</strong>: We configured a regional external ingress, hoping to restrict traffic routing to our chosen region. But alas, requests were still being routed through U.S.-based servers.</li><li><strong>Regional Load Balancer Linked to Global Ingress</strong>: Next, we tried creating a regional load balancer to point to our existing global external ingress. However, this approach didn’t change the routing behavior.</li><li><strong>Kubernetes Service as a Load Balancer</strong>: We finally created a Kubernetes Service of type LoadBalancer, which successfully generated a regional external load balancer pointing to our application. However, the routing worked only over HTTP, not HTTPS.</li></ol><p>Despite our efforts, none of these solutions met our requirements. Frustrated but undeterred, we decided to pivot to a new approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l92cMYpUi4VVD21rgL3ccg.jpeg" /></figure><h3>The Solution: Implementing NGINX Ingress Controller</h3><p>Enter the NGINX Ingress Controller — a robust, highly customizable alternative to the default GKE Ingress Controller. With NGINX, we knew we could create a regional load balancer, manage HTTPS routing, and gain more control over the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COvtDQaRuhnoCKelkPJcJg.png" /><figcaption>Ingress-Managed Regional Load Balancer (GKE)</figcaption></figure><h3>Step-by-Step Guide to Setting Up NGINX Ingress on GKE</h3><p>If you’re ready to embark on a similar journey, here’s how you can set up NGINX Ingress to achieve regional routing and HTTPS support.</p><h4>Step 1: Add the NGINX Helm Repository</h4><p>Open Cloud Shell in GCP, and add the NGINX stable Helm chart repository:</p><pre>helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx<br>helm repo update</pre><h4>Step 2: Reserve a Static IP for the Load Balancer</h4><p>Before deploying, we need a static IP to ensure our service has a consistent endpoint. Here’s how to do it from the GCP Console:</p><ol><li>Go to <strong>VPC network</strong> &gt; <strong>External IP addresses</strong>.</li><li>Select <strong>Reserve static address</strong>.</li><li>Set the network tier to <strong>Premium</strong> and ensure the IP type is <strong>Regional</strong>.</li><li>Name your IP address and reserve it. Copy the reserved IP to use in your configuration.</li></ol><h4>Step 3: Download and Configure the NGINX Helm Chart</h4><p>Download the NGINX chart locally to customize it:</p><pre>helm pull ingress-nginx/ingress-nginx<br>tar -xzvf ingress-nginx-*.tgz</pre><p>Now, open the values.yaml file in the extracted directory and configure it to use your static IP:</p><pre>controller:<br>  service:<br>    enabled: true<br>    type: LoadBalancer<br>    loadBalancerIP: &quot;YOUR_STATIC_IP&quot;<br>    annotations:<br>      service.beta.kubernetes.io/google-load-balancer-ip: &quot;YOUR_STATIC_IP&quot;</pre><p>Replace &quot;YOUR_STATIC_IP&quot; with the IP address you reserved.</p><h4>Step 4: Deploy the NGINX Ingress Controller</h4><p>With your configuration ready, install NGINX Ingress using Helm:</p><pre>helm install nginx-ingress ingress-nginx/ingress-nginx -f values.yaml</pre><p>⚠️ <strong>Note:</strong> Don’t run the default install command without specifying values.yaml to ensure your static IP and configuration are correctly applied.</p><h4>Step 5: Verify the Deployment</h4><p>Once deployed, check that the NGINX controller is up and running:</p><pre>kubectl get deployment nginx-ingress-ingress-nginx-controller<br>kubectl get service nginx-ingress-ingress-nginx-controller</pre><p>You should see your service with the static external IP assigned to it. Confirm the IP is active by running:</p><pre>kubectl get service nginx-ingress-ingress-nginx-controller</pre><h3>Setting Up SSL for Secure Connections</h3><p>To complete the setup, let’s add SSL for secure HTTPS routing.</p><h4>Step 6: Import and Create SSL Certificates</h4><p>In Cloud Shell, generate or import your SSL certificates. Use this command to get the certificate:</p><pre>gcloud compute ssl-certificates describe YOUR_CERTIFICATE_NAME \<br>  --project=project_name \<br>  --format=&quot;get(certificate)&quot; &gt; certificate.crt</pre><p>Create a Kubernetes secret to store the certificate:</p><pre>kubectl create secret tls secret_name --cert=certificate.crt --key=private.key</pre><h4>Step 7: Define the Ingress Resource</h4><p>Finally, create an Ingress resource to define your routing rules. Here’s an example:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: nginx-ingress-example<br>  annotations:<br>    kubernetes.io/ingress.class: &quot;nginx&quot;<br>    nginx.ingress.kubernetes.io/ssl-redirect: &quot;true&quot;<br>    nginx.ingress.kubernetes.io/force-ssl-redirect: &quot;true&quot;<br>spec:<br>  tls:<br>  - hosts:<br>    - example-service.yourdomain.com<br>    secretName: secret_name<br>  rules:<br>  - host: example-service.yourdomain.com<br>    http:<br>      paths:<br>      - backend:<br>          service:<br>            name: example-service<br>            port:<br>              number: 80<br>        pathType: ImplementationSpecific</pre><p>This configuration directs requests for example-service.yourdomain.com to our service over HTTPS.</p><h3>Troubleshooting: Overcoming Webhook Timeout Errors</h3><p>Of course, no deployment journey is complete without its share of bumps in the road. We encountered an error with the validating webhook:</p><pre>error when patching &quot;nginx-ingress.yaml&quot;: Internal error occurred: failed calling webhook &quot;validate.nginx.ingress.kubernetes.io&quot;: timeout error</pre><p>This error happened because the webhook’s admission service was timing out. To resolve it, we deleted the webhook configuration temporarily:</p><pre>kubectl delete validatingwebhookconfigurations nginx-ingress-ingress-nginx-admission</pre><p>This allowed us to complete the deployment, though in a production environment, a more thorough resolution might involve network policies or reviewing admission controller settings.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*6EVY5lPRoX9sG17ZJqVv4A.png" /></figure><p>Our journey to set up a regional HTTPS load balancer on GKE took a few twists and turns. From experimenting with GKE’s native Ingress controller to ultimately adopting NGINX Ingress for its flexibility and regional control, we faced challenges, learned valuable lessons, and emerged victorious.</p><p>With the NGINX Ingress Controller in place, we finally have a setup that’s performant, regionally optimized, and secure with HTTPS. For those tackling similar issues, don’t be afraid to dig into alternative solutions like NGINX — sometimes, the key to overcoming challenges is just a bit of persistence and the right tool for the job!</p><p>That’s it! I hope this setup guide (and our story) help others in their quest to conquer the GKE Ingress Controller’s limitations.</p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><h3>References</h3><ol><li><a href="https://github.com/kubernetes/ingress-nginx">https://github.com/kubernetes/ingress-nginx</a></li><li><a href="https://stackoverflow.com/questions/61616203/nginx-ingress-controller-failed-calling-webhook">https://stackoverflow.com/questions/61616203/nginx-ingress-controller-failed-calling-webhook</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85bcc68b4c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Kubernetes Storage: Persistent Volumes, Claims, and Storage Classes]]></title>
            <link>https://medium.com/@sidhusangani/demystifying-kubernetes-storage-persistent-volumes-claims-and-storage-classes-31ad825ed464?source=rss-fc0d411a7f1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31ad825ed464</guid>
            <category><![CDATA[pv]]></category>
            <category><![CDATA[storageclass]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[pvc]]></category>
            <dc:creator><![CDATA[Sidhu Sangani]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 12:04:42 GMT</pubDate>
            <atom:updated>2024-09-03T12:23:00.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCV5xOkL5nhiOXs9MrnKRA.png" /></figure><h3>Introduction</h3><p>Kubernetes has become the de facto standard for container orchestration, offering powerful tools to manage applications at scale. However, as applications become more complex, ensuring data persistence across containers and clusters becomes critical. This is where Kubernetes storage solutions, such as Persistent Volumes (PVs), Persistent Volume Claims (PVCs), and Storage Classes, come into play. In this blog, we’ll explore these storage concepts in depth and how they integrate with Kubernetes to provide flexible and scalable storage options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*0VI81u5QKe0rAanD5rOnJg.png" /></figure><h3>1. Container Runtimes and Interfaces</h3><h3>The Evolution of Container Runtimes</h3><p>In the early days of Kubernetes, Docker was the primary container runtime. All the necessary code was embedded directly within Kubernetes, creating a tight coupling. However, as the container ecosystem grew, so did the need for Kubernetes to support multiple container runtimes, such as rkt and CRI-O.</p><h3>Introduction of the Container Runtime Interface (CRI)</h3><p>To decouple Kubernetes from a single container runtime, the Container Runtime Interface (CRI) was introduced. CRI defines a standardized way for Kubernetes to communicate with different container runtimes. This means that any new container runtime developed in the future can work seamlessly with Kubernetes by adhering to the CRI standard, without needing changes in the Kubernetes source code.</p><h3>2. Extending Kubernetes Networking and Storage</h3><h3>Container Networking Interface (CNI)</h3><p>Just as Kubernetes extended support for different container runtimes with CRI, the Container Networking Interface (CNI) was introduced to allow different networking solutions to integrate with Kubernetes. Networking vendors can develop plugins based on CNI standards, enabling their solutions to work seamlessly with Kubernetes.</p><h3>Container Storage Interface (CSI)</h3><p>To support various storage solutions, Kubernetes introduced the Container Storage Interface (CSI). CSI allows storage vendors to develop their drivers, enabling their storage solutions to integrate with Kubernetes without needing direct support from the Kubernetes development team.</p><h3>3. Understanding Kubernetes Volumes</h3><h3>Basic Volume Concepts</h3><p>In Kubernetes, a volume is defined within a pod’s configuration file. For instance, you can specify a volume named data-volume that uses hostPath, which stores data in the /data directory on the same node.</p><pre>volumes:<br>  - name: data-volume<br>    hostPath:<br>      path: /data</pre><p>The container within the pod can mount this volume to a specific path, such as /opt:</p><pre>volumeMounts:<br>  - mountPath: &quot;/opt&quot;<br>    name: data-volume</pre><h3>Challenges in Multi-Node Clusters</h3><p>Using hostPath is not recommended in multi-node clusters because it stores data on individual nodes, leading to inconsistency across nodes. To address this, Kubernetes supports various storage solutions like NFS, Ceph, AWS Elastic Block Store (EBS), and Google Cloud Storage.</p><h3>Using Elastic Block Storage</h3><p>To use AWS EBS, replace hostPath with awsElasticBlockStore in the volume definition, specifying the volumeID and fsType:</p><pre>volumes:<br>  - name: data-volume<br>    awsElasticBlockStore:<br>      volumeID: &lt;volume-id&gt;<br>      fsType: ext4</pre><h3>4. Persistent Volumes (PV) and Persistent Volume Claims (PVC)</h3><h3>The Need for Persistent Volumes</h3><p>Managing storage across multiple pods can become cumbersome, especially when changes are needed. Instead of defining storage in each pod’s configuration file, Kubernetes introduces Persistent Volumes (PVs), which are a cluster-wide pool of storage resources configured by an administrator.</p><h3>Using Persistent Volume Claims</h3><p>Users can request storage from this pool by creating Persistent Volume Claims (PVCs). Kubernetes then binds the PVC to a suitable PV based on the requested capacity, access modes, and other properties.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: mypod<br>spec:<br>  containers:<br>    - name: myfrontend<br>      image: nginx<br>      volumeMounts:<br>        - mountPath: &quot;/var/www/html&quot;<br>          name: mypd<br>  volumes:<br>    - name: mypd<br>      persistentVolumeClaim:<br>        claimName: myclaim</pre><h3>5. Access Modes in Persistent Volumes</h3><h3>ReadWriteOnce (RWO)</h3><ul><li><strong>Definition:</strong> A volume can be mounted as read-write by only one node at a time.</li><li><strong>Use Case:</strong> Ideal for applications like databases where a single instance needs read-write access. For example, an AWS EBS volume attached to one EC2 instance.</li></ul><h3>ReadOnlyMany (ROX)</h3><ul><li><strong>Definition:</strong> A volume can be mounted as read-only by multiple nodes simultaneously.</li><li><strong>Use Case:</strong> Suitable for scenarios where multiple instances need to read the same data, like shared log files on Amazon S3.</li></ul><h3>ReadWriteMany (RWX)</h3><ul><li><strong>Definition:</strong> A volume can be mounted as read-write by multiple nodes simultaneously.</li><li><strong>Use Case:</strong> Perfect for web applications where multiple instances need to read and write shared data, using solutions like Amazon EFS.</li></ul><h3>6. Persistent Volume Reclaim Policy</h3><h3>Handling PVC Deletions</h3><p>When a PVC is deleted, the associated PV’s fate depends on the persistentVolumeReclaimPolicy:</p><ul><li><strong>Retain:</strong> The PV remains after PVC deletion.</li><li><strong>Delete:</strong> The PV is deleted along with the PVC.</li><li><strong>Recycle:</strong> The PV is scrubbed and made available for reuse.</li></ul><h3>7. Storage Classes in Kubernetes</h3><h3>Static vs. Dynamic Provisioning</h3><p>Manually creating disks and PVs is known as static provisioning. However, Kubernetes allows dynamic provisioning through Storage Classes, which automatically provision storage resources when a PVC is created.</p><h3>Creating a Storage Class</h3><p>You can define a Storage Class that specifies a provisioner, such as GCP, to dynamically create and attach storage as needed:</p><pre>kind: StorageClass<br>apiVersion: storage.k8s.io/v1<br>metadata:<br>  name: silver-storage-class<br>provisioner: kubernetes.io/gce-pd<br>parameters:<br>  type: pd-standard<br>  replication-type: none</pre><h3>Naming Conventions and Examples</h3><p>You can create different Storage Classes like silver-storage-class, gold-storage-class, and platinum-storage-class based on your storage requirements, such as standard or SSD types and replication settings.</p><h3>Conclusion</h3><p>Kubernetes provides a robust and flexible storage system that scales with your applications. By understanding and leveraging Persistent Volumes, Persistent Volume Claims, and Storage Classes, you can manage storage efficiently across your Kubernetes clusters. Whether you’re dealing with simple or complex storage needs, Kubernetes offers the tools to ensure your data is persistent, consistent, and readily available.</p><p><strong>Final Thoughts:</strong> Mastering Kubernetes storage concepts is essential for administrators and developers alike. As the Kubernetes ecosystem continues to evolve, staying up-to-date with these concepts will ensure your applications run smoothly and efficiently.</p><p>Please reach out to me on LinkedIn for any questions or any help needed: <a href="https://www.linkedin.com/in/sidhu-sangani-34a8511a9">linkedin.com/in/sidhu-sangani-34a8511a9</a></p><h3>References</h3><ol><li><a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">https://kubernetes.io/docs/concepts/storage/persistent-volumes/</a></li><li><a href="https://kubernetes.io/docs/concepts/storage/storage-classes/">https://kubernetes.io/docs/concepts/storage/storage-classes/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ad825ed464" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>