<?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 Abdelrahman ElShahat on Medium]]></title>
        <description><![CDATA[Stories by Abdelrahman ElShahat on Medium]]></description>
        <link>https://medium.com/@abdelrahmanelshahat00?source=rss-c1e997473fea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tBX08_ZcnX5OtUSBX-DPpg.jpeg</url>
            <title>Stories by Abdelrahman ElShahat on Medium</title>
            <link>https://medium.com/@abdelrahmanelshahat00?source=rss-c1e997473fea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:59:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdelrahmanelshahat00/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[Cutting Down Node Provisioning and Pod Scheduling Time with Karpenter and a Pre-Cached Golden AMI]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/cutting-down-node-provisioning-and-pod-scheduling-time-with-karpenter-and-a-pre-cached-golden-image-4b57d5fc5757?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b57d5fc5757</guid>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 21:59:38 GMT</pubDate>
            <atom:updated>2026-11-10T20:31:43.127Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Benchmarking how Karpenter, an AL2023 Golden AMI, and pre-bootstrap tuning cut EKS node readiness from 44s to 37s on right-sized instances.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6ZByYEXH7LPtD6v45kxew.png" /></figure><h3>Introduction</h3><p>Scaling a standard Amazon EKS node takes too long when pods are stuck pending. With an EC2 Auto Scaling group (ASG) and the Kubernetes Cluster Autoscaler, bringing a new node to Ready means waiting through the autoscaler scan loop, ASG reconciliation, OS boot, and cold image pulls across the network.</p><p>On Amazon EKS 1.37, you can cut this startup window down by combining Karpenter, a Cilium VXLAN overlay, an AL2023 golden AMI with pre-cached images, and a short pre-bootstrap script.</p><p>This benchmark compares two setups running the same nginx workload:</p><ul><li><strong>Baseline:</strong> An EKS managed node group backed by an EC2 Auto Scaling group and Cluster Autoscaler.</li><li><strong>Optimized:</strong> Karpenter (NodePool and EC2NodeClass) running a golden AMI with pre-cached images and a pre-bootstrap.sh script.</li></ul><p>The walkthrough covers:</p><ul><li>Running Cilium in VXLAN overlay mode (10.244.0.0/16) instead of the default AWS VPC CNI (aws-node).</li><li>Pre-caching pause, cilium, coredns, and aws-ebs-csi-driver images directly in containerd.</li><li>Using a pre-bootstrap.sh script to set up early API server routing and prevent CNI race conditions at boot.</li><li>A stage-by-stage latency benchmark from pod pending to node ready.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUU-Krx3iJ3bKcOB6j9_xQ.png" /><figcaption>Architecture Overview</figcaption></figure><blockquote><strong><em>Key Architectural Differences:</em></strong></blockquote><ul><li><strong>Multi-Hop vs. Direct API:</strong> The baseline relies on Cluster Autoscaler polling the API every 4s, waiting for Auto Scaling Group reconciliation, and launching fixed instances. Karpenter watches pod events in sub-second time and calls ec2:CreateFleet directly (~2s).</li><li><strong>Cold Pulls vs. Pre-Baked Layers:</strong> The baseline downloads Cilium and system DaemonSets over the network on every boot. The optimized path boots from an AL2023 Golden AMI where critical images already reside in the containerd storage cache.</li></ul><h3>Prerequisites</h3><p>Before we begin, ensure you have:</p><ul><li>A running <strong>Amazon EKS cluster (</strong><strong>v1.37+)</strong> with the default vpc-cni disabled and <strong>Cilium installed in VXLAN Overlay mode (</strong><strong>10.244.0.0/16)</strong></li><li>Private worker subnets and node security groups tagged with karpenter.sh/discovery: &lt;cluster-name&gt;</li><li><strong>IAM Permissions</strong> configured for Karpenter (KarpenterNodeRole-&lt;cluster-name&gt; registered in EKS Access Entries and the Karpenter Controller IAM Role linked via <strong>EKS Pod Identity</strong>)</li><li>kubectl configured to access your cluster</li><li><strong>Helm 3.x</strong> and <strong>AWS CLI v2</strong> installed</li></ul><p>Verify your Cilium overlay and initial system node are running:</p><pre>kubectl get nodes -L node_pool,node.kubernetes.io/instance-type<br>NAME                                         STATUS   ROLES    AGE   VERSION               NODE_POOL   INSTANCE-TYPE<br>ip-10-2-10-216.eu-north-1.compute.internal   Ready    &lt;none&gt;   44m   v1.37.1-eks-6e7947a   system      c7i-flex.large</pre><h3>Scenario 1: Normal Node Pool with ASG and Cluster Autoscaler</h3><p>In our first scenario, we use a standard EKS Managed Node Group backed by an EC2 Auto Scaling Group starting at 0 nodes (minSize=0, desiredCapacity=0) and managed by the <strong>Kubernetes Cluster Autoscaler</strong>.</p><h4>Provision the nginx Pods and Measure Node Readiness</h4><p>We print the current timestamp, create an nginx deployment with 5 replicas directly from the terminal, and watch the nodes:</p><pre>date &#39;+%H:%M:%S&#39; &amp;&amp; kubectl create deployment nginx --image=nginx --replicas=5 &amp;&amp; kubectl get nodes -w</pre><p>Because the system node is tainted with CriticalAddonsOnly=true:NoSchedule and the ASG node group has 0 running nodes, all 5 nginx pods enter Pending state and trigger the Cluster Autoscaler.</p><h4>Scenario 1 Measured Results</h4><p>Inspecting the Kubernetes events (kubectl get events --sort-by=.lastTimestamp) shows the exact timeline for the ASG node (ip-10-2-12-104.eu-north-1.compute.internal):</p><pre>20:43:04Z   ScalingReplicaSet   nginx                    Scaled up replica set nginx-69b9cdbbdd from 0 to 5<br>20:43:08Z   TriggeredScaleUp    nginx-69b9cdbbdd-grmkb   pod triggered scale-up: [{eks-normal-asg-pool-v2 0-&gt;1 (max: 10)}]   (+4s)<br>20:43:23Z   Starting            ip-10-2-12-104           Starting kubelet.                                                   (+19s)<br>20:43:29Z   RegisteredNode      ip-10-2-12-104           Registered Node ip-10-2-12-104 in Controller                        (+25s)<br>20:43:48Z   NodeReady           ip-10-2-12-104           Node ip-10-2-12-104 status is now: NodeReady                        (+44s)<br>20:43:52Z   Scheduled           nginx-69b9cdbbdd-27pcl   Successfully assigned default/nginx-69b9cdbbdd-27pcl to ip-10-2-12-104 (+48s)<br>20:43:57Z   Started             nginx-69b9cdbbdd-27pcl   Container started                                                   (+53s)</pre><p><strong>Scenario 1 Breakdown:</strong></p><ul><li><strong>Scale Decision Time:</strong> 4 seconds (20:43:04Z → 20:43:08Z) for Cluster Autoscaler to detect nginx-69b9cdbbdd-grmkb and increment the ASG.</li><li><strong>Node Registration (</strong><strong>NotReady):</strong> 25 seconds (20:43:04Z → 20:43:29Z).</li><li><strong>CNI Initialization (</strong><strong>RegisteredNode → </strong><strong>NodeReady):</strong> 19 seconds (20:43:29Z → 20:43:48Z) spent cold-pulling pause and cilium images on the stock EKS AMI.</li><li><strong>Total Time to </strong><strong>NodeReady:</strong> 44 seconds (and 53 seconds until nginx-69b9cdbbdd-27pcl, nginx-69b9cdbbdd-dj8gh, nginx-69b9cdbbdd-rth6v, nginx-69b9cdbbdd-8wm6f, and nginx-69b9cdbbdd-grmkb were Started).</li></ul><p>Before moving to Scenario 2, clean up the nginx deployment and scale down the Cluster Autoscaler so it does not compete with Karpenter:</p><pre>kubectl delete deployment nginx<br>kubectl scale deployment cluster-autoscaler-aws-cluster-autoscaler -n kube-system --replicas=0</pre><h3>Understanding the Golden Image and Karpenter Helm Configuration</h3><p>To eliminate the cold image pull penalty and speed up CNI initialization, we combine two techniques:</p><ol><li><strong>A Pre-Cached Golden AMI (</strong><strong>build-precached-eks-ami.sh)</strong></li><li><strong>A Custom Pre-Bootstrap Script (</strong><strong>pre-bootstrap.sh) injected via a local Helm chart</strong></li></ol><h4>1. Building the Pre-Cached Golden AMI (build-precached-eks-ami.sh)</h4><p>Stock EKS Amazon Linux 2023 AMIs ship with an empty /var/lib/containerd cache. Every time a new node boots, Kubelet must pull pause, cilium, and aws-ebs-csi-driver over the network before the CNI plugin can initialize and mark the node Ready.</p><p>Our builder script launches a temporary builder EC2 instance from the latest official EKS AL2023 AMI, pre-pulls the cluster’s system images into containerd&#39;s k8s.io namespace, cleans cloud-init state so future Karpenter nodes run cloud-init and nodeadm fresh, and snapshots a custom AMI tagged with k8s_version=v&lt;k8s-version&gt;:</p><pre>#!/usr/bin/env bash<br>set -euo pipefail<br><br>REGION=&quot;${AWS_REGION:-&lt;aws-region&gt;}&quot;<br>K8S_VERSION=&quot;${1:-1.37}&quot;<br>SUBNET_ID=&quot;${2:-&lt;worker-subnet-id&gt;}&quot;<br>SECURITY_GROUP_ID=&quot;${3:-&lt;node-security-group-id&gt;}&quot;<br>INSTANCE_PROFILE_ROLE=&quot;${4:-KarpenterNodeRole-&lt;cluster-name&gt;}&quot;<br>CUSTOM_AMI_NAME=&quot;AL2023-EKS-${K8S_VERSION}-Precached-$(date +%Y%m%d-%H%M)&quot;<br><br>echo &quot;[0/4] Resolving latest official Amazon Linux 2023 EKS ${K8S_VERSION} AMI in ${REGION}...&quot;<br>BASE_AMI_ID=$(aws ssm get-parameter \<br>  --region &quot;$REGION&quot; \<br>  --name &quot;/aws/service/eks/optimized-ami/${K8S_VERSION}/amazon-linux-2023/x86_64/standard/recommended/image_id&quot; \<br>  --query &quot;Parameter.Value&quot; --output text)<br><br>cat &lt;&lt; &#39;EOF&#39; &gt; /tmp/eks-builder-cloud-init.sh<br>#!/bin/bash<br>set -euxo pipefail<br>exec &gt;/var/log/precacher.log 2&gt;&amp;1<br><br>systemctl start containerd<br><br>IMAGES=(<br>  &quot;public.ecr.aws/eks-distro/kubernetes/pause:3.10&quot;<br>  &quot;quay.io/cilium/cilium:v1.16.5&quot;<br>  &quot;quay.io/cilium/operator-generic:v1.16.5&quot;<br>  &quot;public.ecr.aws/eks-distro/kubernetes/coredns:v1.11.3-eks-1-31-9&quot;<br>  &quot;public.ecr.aws/ebs-csi-driver/aws-ebs-csi-driver:v1.37.0&quot;<br>)<br><br>for img in &quot;${IMAGES[@]}&quot;; do<br>  for attempt in 1 2 3; do<br>    if ctr -n k8s.io images pull &quot;$img&quot;; then<br>      break<br>    fi<br>    sleep 3<br>  done<br>done<br><br>ctr -n k8s.io images ls<br>systemctl stop containerd<br><br># Clean cloud-init state so Karpenter nodes launched from this AMI run cloud-init &amp; nodeadm fresh<br>rm -rf /var/lib/cloud/instance /var/lib/cloud/instances/* /var/lib/cloud/data/* /var/lib/cloud/sem/*<br>sync<br>poweroff<br>EOF<br><br>echo &quot;[1/4] Ensuring IAM Instance Profile exists for temporary builder...&quot;<br>PROFILE_NAME=&quot;${INSTANCE_PROFILE_ROLE}-builder-profile&quot;<br>if ! aws iam get-instance-profile --instance-profile-name &quot;$PROFILE_NAME&quot; &gt;/dev/null 2&gt;&amp;1; then<br>  aws iam create-instance-profile --instance-profile-name &quot;$PROFILE_NAME&quot; &gt;/dev/null<br>  aws iam add-role-to-instance-profile --instance-profile-name &quot;$PROFILE_NAME&quot; --role-name &quot;$INSTANCE_PROFILE_ROLE&quot; &gt;/dev/null<br>  sleep 10<br>fi<br><br>echo &quot;[2/4] Launching temporary builder instance in $REGION...&quot;<br>INSTANCE_ID=$(aws ec2 run-instances \<br>  --region &quot;$REGION&quot; \<br>  --image-id &quot;$BASE_AMI_ID&quot; \<br>  --instance-type &quot;c7i-flex.large&quot; \<br>  --subnet-id &quot;$SUBNET_ID&quot; \<br>  --security-group-ids &quot;$SECURITY_GROUP_ID&quot; \<br>  --iam-instance-profile &quot;Name=$PROFILE_NAME&quot; \<br>  --block-device-mappings &#39;[{&quot;DeviceName&quot;:&quot;/dev/xvda&quot;,&quot;Ebs&quot;:{&quot;VolumeSize&quot;:30,&quot;VolumeType&quot;:&quot;gp3&quot;,&quot;Throughput&quot;:300,&quot;Iops&quot;:3000}}]&#39; \<br>  --user-data file:///tmp/eks-builder-cloud-init.sh \<br>  --tag-specifications &quot;ResourceType=instance,Tags=[{Key=Name,Value=eks-ami-precacher-tmp}]&quot; \<br>  --query &#39;Instances[0].InstanceId&#39; --output text)<br><br>for i in $(seq 1 60); do<br>  STATE=$(aws ec2 describe-instances --region &quot;$REGION&quot; --instance-ids &quot;$INSTANCE_ID&quot; --query &#39;Reservations[0].Instances[0].State.Name&#39; --output text)<br>  echo &quot;  [$i/60] Builder instance state: $STATE&quot;<br>  if [ &quot;$STATE&quot; = &quot;stopped&quot; ]; then<br>    break<br>  fi<br>  sleep 10<br>done<br><br>echo &quot;[3/4] Creating custom Golden AMI &#39;$CUSTOM_AMI_NAME&#39; tagged with k8s_version=v${K8S_VERSION}...&quot;<br>CUSTOM_AMI_ID=$(aws ec2 create-image \<br>  --region &quot;$REGION&quot; \<br>  --instance-id &quot;$INSTANCE_ID&quot; \<br>  --name &quot;$CUSTOM_AMI_NAME&quot; \<br>  --tag-specifications &quot;ResourceType=image,Tags=[{Key=Name,Value=${CUSTOM_AMI_NAME}},{Key=k8s_version,Value=v${K8S_VERSION}}]&quot; \<br>  --query &#39;ImageId&#39; --output text)<br><br>aws ec2 wait image-available --region &quot;$REGION&quot; --image-ids &quot;$CUSTOM_AMI_ID&quot;<br><br>echo &quot;[4/4] Terminating temporary builder instance $INSTANCE_ID...&quot;<br>aws ec2 terminate-instances --region &quot;$REGION&quot; --instance-ids &quot;$INSTANCE_ID&quot; &gt;/dev/null</pre><p>Run the builder script to create your Golden AMI:</p><pre>./build-precached-eks-ami.sh</pre><h4>2. Structuring the Karpenter Configuration as a Helm Chart</h4><p>Instead of hardcoding base64 or multiline scripts directly inside static YAML manifests, we structure our Karpenter EC2NodeClass and NodePool as a lightweight Helm chart:</p><pre>karpenter/<br>├── Chart.yaml<br>├── values.yaml<br>├── scripts/<br>│   └── pre-bootstrap.sh      # Plain-text bash script injected via .Files.Get<br>└── templates/<br>    ├── nodeclass.yaml        # EC2NodeClass resource<br>    └── nodepool.yaml         # NodePool resource</pre><p><strong>karpenter/values.yaml:</strong></p><pre>clusterName: &quot;&lt;cluster-name&gt;&quot;<br>clusterEndpoint: &quot;&lt;cluster-endpoint&gt;&quot;<br>apiServiceIP: &quot;10.98.0.1&quot;<br>nodeRoleName: &quot;KarpenterNodeRole-&lt;cluster-name&gt;&quot;<br>k8sVersionTag: &quot;v1.37&quot;</pre><h4>3. Custom Pre-Bootstrap Script (karpenter/scripts/pre-bootstrap.sh)</h4><p>This script runs via cloud-init before nodeadm starts Kubelet:</p><pre>#!/bin/bash<br># 1. Expand NVMe root filesystem asynchronously in the background (non-blocking)<br>(<br>  growpart /dev/nvme0n1 1 || true<br>  xfs_growfs -d / || true<br>) &gt;/var/log/eks-growfs.log 2&gt;&amp;1 &amp;<br><br># 2. Ensure Kubernetes API ClusterIP (10.98.0.1:443) routes directly to the EKS<br>#    control plane IP immediately at boot before kube-proxy programs iptables,<br>#    so cilium-agent can fetch the node PodCIDR (10.244.x.0/24) in &lt;10ms.<br>API_HOST=$(echo &quot;${EKS_CLUSTER_ENDPOINT:-}&quot; | sed -e &#39;s|^https://||&#39; -e &#39;s|/.*$||&#39;)<br>if [ -n &quot;$API_HOST&quot; ]; then<br>  API_IP=$(getent ahostsv4 &quot;$API_HOST&quot; | awk &#39;{print $1; exit}&#39;)<br>  if [ -n &quot;$API_IP&quot; ]; then<br>    iptables -t nat -C OUTPUT -p tcp -d 10.98.0.1 --dport 443 -j DNAT --to-destination &quot;${API_IP}:443&quot; 2&gt;/dev/null || \<br>      iptables -t nat -A OUTPUT -p tcp -d 10.98.0.1 --dport 443 -j DNAT --to-destination &quot;${API_IP}:443&quot; || true<br>  fi<br>fi<br><br># 2b. Prevent the 1-2s race condition between Cilium&#39;s install-cni-binaries<br>#     initContainer (which writes /etc/cni/net.d/05-cilium.conflist and marks<br>#     the node Ready) and cilium-agent opening /var/run/cilium/cilium.sock.<br>mkdir -p /usr/local/cni/bin<br>cat &lt;&lt; &#39;EOF&#39; &gt; /usr/local/cni/bin/cilium-cni<br>#!/bin/sh<br>if [ &quot;${CNI_COMMAND:-}&quot; = &quot;ADD&quot; ]; then<br>  for _ in $(seq 1 150); do<br>    [ -S /var/run/cilium/cilium.sock ] &amp;&amp; [ -s /opt/cni/bin/cilium-cni ] &amp;&amp; break<br>    sleep 0.1<br>  done<br>fi<br>exec /opt/cni/bin/cilium-cni &quot;$@&quot;<br>EOF<br>chmod 755 /usr/local/cni/bin/cilium-cni<br><br># 3. Configure Kubelet parallel image pulls (maxParallelImagePulls=5) and Image GC thresholds<br>mkdir -p /etc/kubernetes/kubelet/config.json.d<br>cat &lt;&lt; &#39;EOF&#39; &gt; /etc/kubernetes/kubelet/config.json.d/99-karpenter-tuning.conf<br>{<br>  &quot;apiVersion&quot;: &quot;kubelet.config.k8s.io/v1beta1&quot;,<br>  &quot;kind&quot;: &quot;KubeletConfiguration&quot;,<br>  &quot;serializeImagePulls&quot;: false,<br>  &quot;maxParallelImagePulls&quot;: 5,<br>  &quot;imageGCHighThresholdPercent&quot;: 85,<br>  &quot;imageGCLowThresholdPercent&quot;: 70<br>}<br>EOF<br><br># 4. Start containerd early and verify/pre-pull critical CNI &amp; system images in parallel.<br>#    When booting from our Pre-Cached Golden AMI, `ctr -n k8s.io images ls` finds the cached image in &lt;10ms.<br>systemctl start containerd || true<br><br>PAUSE_IMG=&quot;public.ecr.aws/eks-distro/kubernetes/pause:3.10&quot;<br>CILIUM_IMG=&quot;quay.io/cilium/cilium:v1.16.5&quot;<br>CSI_IMG=&quot;public.ecr.aws/ebs-csi-driver/aws-ebs-csi-driver:v1.37.0&quot;<br><br>(<br>  ctr -n k8s.io images ls -q | grep -qF &quot;$PAUSE_IMG&quot; || ctr -n k8s.io images pull &quot;$PAUSE_IMG&quot; || true<br>  ctr -n k8s.io images ls -q | grep -qF &quot;$CILIUM_IMG&quot; || ctr -n k8s.io images pull &quot;$CILIUM_IMG&quot; || true<br>) &gt;/var/log/eks-prepull-cni.log 2&gt;&amp;1 &amp;<br><br>(<br>  ctr -n k8s.io images ls -q | grep -qF &quot;$CSI_IMG&quot; || ctr -n k8s.io images pull &quot;$CSI_IMG&quot; || true<br>) &gt;/var/log/eks-prepull-ds.log 2&gt;&amp;1 &amp;</pre><h4><strong>Key Optimizations Explained:</strong></h4><ul><li><strong>Asynchronous Root Volume Expansion:</strong> Runs growpart and xfs_growfs in a background subshell so disk expansion never blocks the boot critical path.</li><li><strong>Immediate API ClusterIP DNAT (</strong><strong>10.98.0.1:443):</strong> Allows cilium-agent to reach the Kubernetes API via 10.98.0.1:443 immediately at boot before kube-proxy finishes programming iptables.</li><li><strong>CNI Race-Condition Wrapper (</strong><strong>/usr/local/cni/bin/cilium-cni):</strong> Waits in 100ms increments if a pod sandbox creation (CNI_COMMAND=ADD) is triggered during the 1–2s window after /etc/cni/net.d/05-cilium.conflist is written (marking the node Ready) but before /var/run/cilium/cilium.sock is listening.</li><li><strong>Parallel Image Pulls (</strong><strong>maxParallelImagePulls: 5):</strong> Disables serial image pulls in Kubelet (serializeImagePulls: false) so multiple pod images extract concurrently.</li></ul><h4>4. EC2NodeClass and NodePool Templates (karpenter/templates/)</h4><p><strong>karpenter/templates/nodeclass.yaml:</strong></p><pre>apiVersion: karpenter.k8s.aws/v1<br>kind: EC2NodeClass<br>metadata:<br>  name: default<br>spec:<br>  amiFamily: AL2023<br>  role: {{ .Values.nodeRoleName | quote }}<br>  amiSelectorTerms:<br>    - tags:<br>        k8s_version: {{ .Values.k8sVersionTag | quote }}<br>  subnetSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: {{ .Values.clusterName | quote }}<br>  securityGroupSelectorTerms:<br>    - tags:<br>        karpenter.sh/discovery: {{ .Values.clusterName | quote }}<br>  blockDeviceMappings:<br>    - deviceName: /dev/xvda<br>      ebs:<br>        volumeSize: 50Gi<br>        volumeType: gp3<br>        iops: 3000<br>        throughput: 300<br>        encrypted: true<br>        deleteOnTermination: true<br>  kubelet:<br>    imageGCHighThresholdPercent: 85<br>    imageGCLowThresholdPercent: 70<br>  userData: |<br>    MIME-Version: 1.0<br>    Content-Type: multipart/mixed; boundary=&quot;BOUNDARY&quot;<br><br>    --BOUNDARY<br>    Content-Type: text/x-shellscript; charset=&quot;us-ascii&quot;<br><br>    #!/bin/bash<br>    export EKS_CLUSTER_ENDPOINT={{ .Values.clusterEndpoint | quote }}<br>{{ .Files.Get &quot;scripts/pre-bootstrap.sh&quot; | indent 4 }}<br><br>    --BOUNDARY--</pre><p><strong>karpenter/templates/nodepool.yaml:</strong></p><pre>apiVersion: karpenter.sh/v1<br>kind: NodePool<br>metadata:<br>  name: default<br>spec:<br>  weight: 80<br>  template:<br>    metadata:<br>      labels:<br>        node_pool: karpenter-default<br>    spec:<br>      expireAfter: Never<br>      nodeClassRef:<br>        group: karpenter.k8s.aws<br>        kind: EC2NodeClass<br>        name: default<br>      requirements:<br>        - key: kubernetes.io/arch<br>          operator: In<br>          values: [&quot;amd64&quot;]<br>        - key: karpenter.sh/capacity-type<br>          operator: In<br>          values: [&quot;on-demand&quot;]<br>        - key: karpenter.k8s.aws/instance-category<br>          operator: In<br>          values: [&quot;t&quot;, &quot;c&quot;, &quot;m&quot;]<br>        - key: node.kubernetes.io/instance-type<br>          operator: In<br>          values: [&quot;t3.small&quot;, &quot;c7i-flex.large&quot;, &quot;m7i-flex.large&quot;]<br>  disruption:<br>    consolidationPolicy: WhenEmptyOrUnderutilized<br>    consolidateAfter: 5m<br>  limits:<br>    cpu: &quot;2&quot;<br>    memory: 8Gi</pre><h3>Installing Karpenter with Helm</h3><h4>1. Install the Karpenter Controller</h4><p>Install the Karpenter controller (v1.15.1) from the official AWS public ECR registry onto the system node pool:</p><pre>helm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter \<br>  --version 1.15.1 \<br>  --namespace karpenter \<br>  --create-namespace \<br>  --set settings.clusterName=&quot;&lt;cluster-name&gt;&quot; \<br>  --set settings.clusterEndpoint=&quot;&lt;cluster-endpoint&gt;&quot; \<br>  --set settings.interruptionQueue=&quot;&lt;interruption-queue-name&gt;&quot; \<br>  --set nodeSelector.node_pool=&quot;system&quot; \<br>  --set &quot;tolerations[0].key=CriticalAddonsOnly&quot; \<br>  --set &quot;tolerations[0].operator=Exists&quot;</pre><h4>2. Deploy the EC2NodeClass and NodePool Chart</h4><pre>helm upgrade --install karpenter-config ./karpenter --namespace karpenter</pre><p>Verify that both the EC2NodeClass and NodePool report READY: True:</p><pre>kubectl get ec2nodeclass,nodepool<br>NAME                                     READY   AGE     ROLE<br>ec2nodeclass.karpenter.k8s.aws/default   True    2m32s   KarpenterNodeRole-&lt;cluster-name&gt;<br>NAME                            NODECLASS   NODES   READY   AGE     WEIGHT   CPU   MEMORY<br>nodepool.karpenter.sh/default   default     0       True    2m31s   80       0     0</pre><h3>Scenario 2: Karpenter with Pre-Cached Golden Image and pre-bootstrap.sh</h3><p>Now let’s run the exact same nginx deployment command from 0 worker nodes with Karpenter active:</p><pre>date &#39;+%H:%M:%S&#39; &amp;&amp; kubectl create deployment nginx --image=nginx --replicas=5 &amp;&amp; kubectl get nodes -w</pre><h4>Scenario 2 Measured Results</h4><p>We captured two Karpenter runs in kubectl get events—first using the stock AL2023 AMI (default-7kmh7 / ip-10-2-10-65 where pods nginx-69b9cdbbdd-4ljw4, nginx-69b9cdbbdd-78zfh, nginx-69b9cdbbdd-f57xw, nginx-69b9cdbbdd-bfjqh, and nginx-69b9cdbbdd-sbkkn were nominated in 1s), and then using our <strong>Pre-Cached Golden AMI (</strong><strong>ami-0452ee0dc5c70075c)</strong> (default-kh54r / ip-10-2-13-20):</p><pre>20:58:20Z   ScalingReplicaSet     nginx                    Scaled up replica set nginx-69b9cdbbdd from 0 to 5<br>20:58:21Z   Nominated             nginx-69b9cdbbdd-4ljw4   Pod should schedule on: nodeclaim/default-7kmh7          (+1s)<br>20:58:21Z   Nominated             nginx-69b9cdbbdd-78zfh   Pod should schedule on: nodeclaim/default-7kmh7          (+1s)<br>20:58:21Z   Nominated             nginx-69b9cdbbdd-f57xw   Pod should schedule on: nodeclaim/default-7kmh7          (+1s)<br>20:58:21Z   Nominated             nginx-69b9cdbbdd-bfjqh   Pod should schedule on: nodeclaim/default-7kmh7          (+1s)<br>20:58:21Z   Nominated             nginx-69b9cdbbdd-sbkkn   Pod should schedule on: nodeclaim/default-7kmh7          (+1s)<br>---<br>20:59:19Z   DisruptionLaunching   default-kh54r            Launching NodeClaim (Golden AMI ami-0452ee0dc5c70075c)   (+0s)<br>20:59:21Z   Launched              default-kh54r            Status condition transitioned, Type: Launched -&gt; True    (+2s)<br>20:59:38Z   Starting              ip-10-2-13-20            Starting kubelet.                                        (+19s)<br>20:59:41Z   Registered            default-kh54r            Status condition transitioned, Type: Registered -&gt; True  (+22s)<br>20:59:44Z   RegisteredNode        ip-10-2-13-20            Registered Node ip-10-2-13-20 in Controller              (+25s)<br>20:59:56Z   NodeReady             ip-10-2-13-20            Node ip-10-2-13-20 status is now: NodeReady              (+37s)<br>20:59:59Z   Ready                 default-kh54r            Status condition transitioned, Type: Ready -&gt; True       (+40s)</pre><p>Verify the newly provisioned node and NodeClaim:</p><pre>kubectl get nodes,nodeclaims -o wide<br>NAME                                              STATUS   ROLES    AGE     VERSION               INTERNAL-IP   OS-IMAGE                        CONTAINER-RUNTIME<br>node/ip-10-2-10-216.eu-north-1.compute.internal   Ready    &lt;none&gt;   64m     v1.37.1-eks-6e7947a   10.2.10.216   Amazon Linux 2023.12.20261102   containerd://2.3.7+unknown<br>node/ip-10-2-13-20.eu-north-1.compute.internal    Ready    &lt;none&gt;   2m21s   v1.37.1-eks-6e7947a   10.2.13.20    Amazon Linux 2023.12.20261102   containerd://2.3.7+unknown<br><br>NAME                                   TYPE       CAPACITY    ZONE          NODE                                        READY   AGE     IMAGEID                 ID                                       NODEPOOL   NODECLASS<br>nodeclaim.karpenter.sh/default-kh54r   t3.small   on-demand   eu-north-1b   ip-10-2-13-20.eu-north-1.compute.internal   True    2m43s   ami-0452ee0dc5c70075c   aws:///eu-north-1b/i-04aaee5195b311531   default    default</pre><p><strong>Scenario 2 Breakdown:</strong></p><ul><li><strong>Right-Sized Instance Selection:</strong> Instead of launching a fixed c7i-flex.large (2 vCPU, 4 GiB), Karpenter calculated the exact resource requirements of the 5 nginx pods (nginx-69b9cdbbdd-4ljw4, nginx-69b9cdbbdd-78zfh, nginx-69b9cdbbdd-f57xw, nginx-69b9cdbbdd-bfjqh, and nginx-69b9cdbbdd-sbkkn) and selected a smaller, cheaper t3.small (2 vCPU, 2 GiB).</li><li><strong>Scale Decision &amp; EC2 Launch:</strong> 1s to nominate the NodeClaim and 2 seconds (20:59:19Z → 20:59:21Z) to launch the EC2 instance via ec2:CreateFleet.</li><li><strong>CNI Initialization (</strong><strong>RegisteredNode → </strong><strong>NodeReady):</strong> Reduced from 25 seconds (on t3.small with the stock AMI cold-pulling Cilium) down to 12 seconds (20:59:44Z → 20:59:56Z) with the Pre-Cached Golden AMI and pre-bootstrap.sh—<strong>more than 2x faster CNI readiness</strong>.</li><li><strong>Total Time to </strong><strong>NodeReady:</strong> 37 seconds end-to-end (even on a smaller t3.small instance).</li></ul><h3>Comparison Table: Scenario 1 vs. Scenario 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l14NM-Y-7WXt-IRFLQXArw.png" /><figcaption>Comparison Table</figcaption></figure><h3>Conclusion</h3><p>By replacing static Auto Scaling Groups with <strong>Karpenter</strong>, running <strong>Cilium in VXLAN Overlay mode</strong>, and baking a <strong>Pre-Cached Golden AMI</strong> paired with a <strong>custom </strong><strong>pre-bootstrap.sh script</strong>, we achieved:</p><ul><li><strong>Sub-second scale decisions</strong> and <strong>2-second EC2 fleet launches</strong> via ec2:CreateFleet</li><li><strong>Automatic instance right-sizing</strong> (t3.small instead of fixed c7i-flex.large nodes)</li><li><strong>Over 50% faster CNI initialization (</strong><strong>25s down to </strong><strong>12s)</strong> by eliminating cold CNI/DaemonSet image pulls at boot</li><li><strong>37-second end-to-end node readiness</strong> with zero CNI race conditions</li></ul><h3>References &amp; Additional Resources</h3><ul><li><a href="https://karpenter.sh/docs/">Karpenter AWS Provider Documentation</a></li><li><a href="https://awslabs.github.io/amazon-eks-ami/nodeadm/">Amazon Linux 2023 </a><a href="https://awslabs.github.io/amazon-eks-ami/nodeadm/">nodeadm Configuration Reference</a></li><li><a href="https://docs.cilium.io/en/stable/network/concepts/routing/">Cilium Kubernetes Overlay Routing Documentation</a></li><li><a href="https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html">Amazon EKS Pod Identity Documentation</a></li></ul><p>#Kubernetes #EKS #Karpenter #Cilium #AWS #DevOps #CloudNative</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b57d5fc5757" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArgoCD Image Updater for Regex Tag Strategies and Git Write-Back]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/argocd-image-updater-for-regex-tag-strategies-and-git-write-back-50ec60017d02?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ec60017d02</guid>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 22:22:55 GMT</pubDate>
            <atom:updated>2026-07-26T05:46:11.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxN_-StMev_k3aVIflif4g.png" /><figcaption>Image Updater</figcaption></figure><h3>Introduction</h3><p>In a GitOps workflow, the image tag in your Helm values file is the source of truth for what’s running in each environment. Updating that file manually after every CI build adds friction, especially across dev, stage, and prod environments that each follow different tagging conventions.</p><p>ArgoCD Image Updater solves this by watching a container registry, detecting new tags that match a constraint, and writing the updated tag back to Git automatically. Your ArgoCD Application then syncs from that Git change just like any other commit.</p><p>This configuration uses Image Updater with GCP Artifact Registry authentication, per-environment regex tag constraints on an ApplicationSet, Git write-back over SSH, and a webhook endpoint so updates happen quickly.</p><h3>Prerequisites</h3><ul><li>ArgoCD v2.6+ running on GKE</li><li>ArgoCD Image Updater installed in the argocd namespace</li><li>Container images stored in GCP Artifact Registry</li><li>Git repository with SSH write access (for write-back)</li><li>Familiarity with ArgoCD ApplicationSets (Part 2 of this series)</li></ul><h3>The Tag Convention</h3><p>The approach uses a consistent, environment-aware tagging convention in CI:</p><ul><li><strong>prod:</strong> 1.2.3 (a clean semantic version, no suffix)</li><li><strong>stage:</strong> 1.2.3-stage.4 (semver with a -stage.N pre-release suffix)</li><li><strong>dev:</strong> 1.2.3-dev.7 (semver with a -dev.N pre-release suffix)</li></ul><p>This means the same image name can be published to a shared registry with different tags per environment. Image Updater watches for tags matching the right pattern per environment and only updates the correct Application.</p><h3>Step 1: Install ArgoCD Image Updater</h3><p>Install via Helm in the same namespace as ArgoCD:</p><pre>helm repo add argo https://argoproj.github.io/argo-helm<br>helm repo update</pre><pre>helm install argocd-image-updater argo/argocd-image-updater \<br>  --namespace argocd \<br>  --version 0.14.0</pre><p>If you are running on GKE and using Workload Identity for registry authentication (covered in Step 2), make sure to annotate the Image Updater service account as well, following the same pattern as the ArgoCD service accounts in the previous article.</p><h3>Step 2: Configure GCR / Artifact Registry Authentication</h3><p>Image Updater needs to authenticate to Google Container Registry (GCR) or Artifact Registry to list available tags. The cleanest approach on GKE is a custom auth script that fetches an OAuth2 token from the GKE metadata server via Workload Identity without requiring static service account keys.</p><p>Configure this in the Image Updater Helm values:</p><pre>config:<br>  registries:<br>    - name: platform-registry<br>      api_url: https://us-central1-docker.pkg.dev<br>      prefix: us-central1-docker.pkg.dev<br>      credentials: ext:/scripts/gcr.sh<br>      credsexpire: 15m<br>      default: true<br>authScripts:<br>  enabled: true<br>  scripts:<br>    gcr.sh: |<br>      #!/bin/sh<br>      ACCESS_TOKEN=$(wget -q -O - --header &quot;Metadata-Flavor: Google&quot; \<br>        &quot;http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token&quot; \<br>        | sed -n &#39;s/.*&quot;access_token&quot;:&quot;\([^&quot;]*\)&quot;.*/\1/p&#39;)<br>      echo &quot;oauth2accesstoken:${ACCESS_TOKEN}&quot;<br>serviceAccount:<br>  annotations:<br>    iam.gke.io/gcp-service-account: argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com</pre><p><strong>How the auth script works:</strong></p><ul><li>The script is mounted into the Image Updater pod and called before each registry interaction.</li><li>It hits the GKE metadata server to get a short-lived access token for the annotated GSA. This is the same identity that has roles/artifactregistry.reader on your registry projects.</li><li><strong>The Refresh Pattern:</strong> credsexpire: 15m is critical. Workload Identity (WI) tokens expire automatically. This setting forces Image Updater to re-run the script and refresh the WI token every 15 minutes, well before the token&#39;s TTL expires, ensuring uninterrupted access to GCR / Artifact Registry.</li></ul><p>Grant the GSA read access to GCR or Artifact Registry on each workload project (e.g., roles/artifactregistry.reader or roles/storage.objectViewer for GCR):</p><pre>gcloud projects add-iam-policy-binding my-workload-project \<br>  --role=&quot;roles/artifactregistry.reader&quot; \<br>  --member=&quot;serviceAccount:argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com&quot;</pre><h3>Step 3: Configure Git Write-Back via SSH</h3><p>When Image Updater finds a new matching tag, it needs to write the updated tag back to your Git repository. The git write-back method commits the change to a branch in your Helm values repository. Your CI/CD then picks it up and ArgoCD syncs from the updated file.</p><p>Create a Kubernetes Secret with the SSH private key that has write access to your Git repository:</p><pre>kubectl create secret generic image-updater-git-ssh \<br>  --from-file=id_rsa=/path/to/your/git-deploy-key \<br>  --from-file=known_hosts=/path/to/known_hosts \<br>  -n argocd</pre><p>Mount this secret in the Image Updater Helm values:</p><pre>volumes:<br>  - name: git-ssh-key<br>    secret:<br>      secretName: image-updater-git-ssh<br>      defaultMode: 0600<br>volumeMounts:<br>  - name: git-ssh-key<br>    mountPath: /app/ssh<br>    readOnly: true<br>config:<br>  git:<br>    commit-message-template: &quot;build: update image {{ .ImageName }} to {{ .NewTag }}&quot;</pre><p>The SSH key is mounted at /app/ssh/id_rsa. Image Updater uses this automatically when performing git write-back over SSH. The commit message template is useful for traceability because it shows exactly which image was updated in the Git history.</p><h3>Step 4: The Per-Environment Regex Annotation</h3><p>This is the core of the whole setup. Each ArgoCD Application gets a set of annotations that tell Image Updater:</p><ol><li>Which image to watch and where (the image-list)</li><li>Which tags are allowed (the allow-tags regex)</li><li>How to write the update back to Git (write-back-method)</li><li>Which Helm values keys to update (helm.image-name and helm.image-tag)</li></ol><p>When using an ApplicationSet, these annotations go in the template’s metadata. You can use a <strong>Go template conditional</strong> on the environment value to dynamically set the regex per environment:</p><pre>template:<br>  metadata:<br>    annotations:<br>      # Image list: alias=registry/image-name (image name resolved from chart path)<br>      argocd-image-updater.argoproj.io/image-list: &gt;-<br>        app=us-central1-docker.pkg.dev/demo-project/demo-repo/{{ index .path.segments (sub (len .path.segments) 2) }}# Update strategy: semver<br>      argocd-image-updater.argoproj.io/app.update-strategy: semver<br>      # Per-environment tag regex - production gets clean semver, others get env-suffixed pre-releases<br>      argocd-image-updater.argoproj.io/app.allow-tags: &gt;-<br>        {{ if eq .values.env &quot;prod&quot; }}regexp:^\d+\.\d+\.\d+${{ else }}regexp:^\d+\.\d+\.\d+-{{ .values.env }}\.\d+${{ end }}<br>      # Semver constraint - accept any version<br>      argocd-image-updater.argoproj.io/app.constraint: &quot;&gt;= 0.0.0&quot;<br>      # Write back to Git<br>      argocd-image-updater.argoproj.io/write-back-method: git<br>      # Helm values keys to update<br>      argocd-image-updater.argoproj.io/app.helm.image-name: service.image.repository<br>      argocd-image-updater.argoproj.io/app.helm.image-tag: service.image.tag<br></pre><p><strong>Breaking down the allow-tags annotation:</strong></p><ul><li>For env=prod: regexp:^\d+\.\d+\.\d+$ matches 1.2.3 but NOT 1.2.3-dev.4 or 1.2.3-stage.1. Production only gets clean releases.</li><li>For env=dev: regexp:^\d+\.\d+\.\d+-dev\.\d+$ matches 1.2.3-dev.7 but nothing else. Dev only gets dev pre-releases.</li><li>For env=stage: regexp:^\d+\.\d+\.\d+-stage\.\d+$ matches 1.2.3-stage.2 only.</li></ul><p>This means you can push a new build to dev without any risk of it accidentally appearing in stage or prod. The environments are isolated purely by tag naming convention, with no additional configuration needed per service.</p><h3>Step 5: What Happens When Image Updater Finds a New Tag</h3><p>Here is the full sequence from a CI image push to a running deployment update:</p><ol><li>Your CI pipeline builds an image and pushes it to Artifact Registry with a tag like 1.4.2-dev.11.</li><li>Image Updater polls (or receives a webhook — covered in Step 6) and detects the new tag.</li><li>Image Updater checks the allow-tags regex against the new tag. For a dev Application, ^\d+\.\d+\.\d+-dev\.\d+$ matches, and the update proceeds.</li><li>Image Updater clones your Helm values repository over SSH, finds the values.yaml file for that Application, and updates the service.image.tag key.</li><li>Image Updater commits the change with the configured commit message template and pushes to the target branch.</li><li>ArgoCD detects the new commit (via webhook or polling) and syncs the Application — pulling the updated values and upgrading the Helm release.</li></ol><p>The full cycle from image push to running deployment typically completes in under two minutes with webhooks enabled on both sides.</p><h3>Step 6: Exposing the Webhook Endpoint</h3><p>By default, Image Updater polls the registry on a configurable interval (e.g., every 2 minutes). This is acceptable but means there’s always a delay between a push and an update. The webhook mode eliminates that delay.</p><p>Image Updater listens for registry push notifications on port 8082. You need to expose this port via an ingress and configure your container registry to send push events to it.</p><p>First, create a Kubernetes Service for the webhook port:</p><pre>ArgoCD ApplicationSets for Environment-Based Helm GitOpsapiVersion: v1<br>kind: Service<br>metadata:<br>  name: argocd-image-updater-webhook<br>  namespace: argocd<br>spec:<br>  selector:<br>    app.kubernetes.io/name: argocd-image-updater<br>  ports:<br>    - name: webhook<br>      port: 8082<br>      targetPort: 8082<br>      protocol: TCP</pre><p>Then expose it via your ingress controller. Using Traefik as an example:</p><pre>apiVersion: traefik.io/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: image-updater-webhook<br>  namespace: argocd<br>spec:<br>  entryPoints:<br>    - websecure<br>  routes:<br>    - kind: Rule<br>      match: &quot;Host(`argo-imageupdater.example.com`)&quot;<br>      services:<br>        - name: argocd-image-updater-webhook<br>          port: 8082<br>  tls: {}</pre><p>Secure the webhook with a shared secret. Pass it to Image Updater as an extra argument:</p><pre>extraArgs:<br>  - &quot;--harbor-webhook-secret&quot;<br>  - &quot;my-webhook-secret-value&quot;</pre><p>Now when your registry sends a push event to https://argo-imageupdater.example.com, Image Updater wakes up immediately and processes the new tag without waiting for the next poll cycle.</p><h3>Step 7: The Write-Back in Git — What It Looks Like</h3><p>After Image Updater detects and validates a new tag, it makes exactly one change in your Git repository: it updates the image tag value in the Application’s values file. Nothing else changes.</p><p>The commit appears in your Git history like this:</p><pre>commit a3f8c2d<br>Author: ArgoCD Image Updater &lt;image-updater@argocd&gt;<br>Date:   Thu Jul 24 14:32:01 2026 +0000<br>build: update image demo-service to 1.4.2-dev.11</pre><p>And in the values file:</p><pre># Before<br>service:<br>  image:<br>    repository: us-central1-docker.pkg.dev/demo-project/demo-repo/demo-service<br>    tag: 1.4.2-dev.10</pre><pre># After (committed by Image Updater)<br>service:<br>  image:<br>    repository: us-central1-docker.pkg.dev/demo-project/demo-repo/demo-service<br>    tag: 1.4.2-dev.11</pre><p>This is a real Git commit, so you get a full audit trail of every image update. You can see exactly when each environment got which image version, and rolling back is a plain git revert.</p><h3>Complete Annotation Reference</h3><p>Here is a quick reference for all the annotations used in this setup:</p><pre>annotations:<br>  # The image to watch. Format: alias=registry/image-name<br>  argocd-image-updater.argoproj.io/image-list: &quot;app=us-central1-docker.pkg.dev/project/repo/service-name&quot;<br>  # Update strategy: semver (tracks highest matching semver) or latest (newest by date)<br>  argocd-image-updater.argoproj.io/app.update-strategy: semver<br>  # Tag filter - regex or semver constraint<br>  # regexp: prefix means Image Updater uses Go regex matching<br>  argocd-image-updater.argoproj.io/app.allow-tags: &quot;regexp:^\d+\.\d+\.\d+-dev\.\d+$&quot;<br>  # Semver version constraint (used by semver strategy, independent of allow-tags)<br>  argocd-image-updater.argoproj.io/app.constraint: &quot;&gt;= 0.0.0&quot;<br>  # Where to write updates: git (commit to repo) or argocd (patch Application directly)<br>  argocd-image-updater.argoproj.io/write-back-method: git<br>  # Git branch to write to (optional, defaults to tracked revision)<br>  argocd-image-updater.argoproj.io/git-branch: main<br>  # The Helm values key for the image repository<br>  argocd-image-updater.argoproj.io/app.helm.image-name: service.image.repository<br>  # The Helm values key for the image tag<br>  argocd-image-updater.argoproj.io/app.helm.image-tag: service.image.tag</pre><h3>Troubleshooting</h3><h3>Image Updater not detecting new tags</h3><pre># Check Image Updater logs for registry polling errors<br>kubectl logs -n argocd -l app.kubernetes.io/name=argocd-image-updater --tail=100</pre><pre># Verify the auth script works from within the pod<br>kubectl exec -n argocd deploy/argocd-image-updater -- /scripts/gcr.sh<br># Should print: oauth2accesstoken:ya29.xxx</pre><pre># List available tags manually (replace with your registry path)<br>kubectl exec -n argocd deploy/argocd-image-updater -- \<br>  argocd-image-updater list-images \<br>  --image us-central1-docker.pkg.dev/demo-project/demo-repo/demo-service</pre><h3>Git write-back fails</h3><pre># Check SSH key is mounted and has correct permissions<br>kubectl exec -n argocd deploy/argocd-image-updater -- ls -la /app/ssh/</pre><pre># Verify SSH connectivity to Git host<br>kubectl exec -n argocd deploy/argocd-image-updater -- \<br>  ssh -i /app/ssh/id_rsa -o StrictHostKeyChecking=no git@github.com</pre><h3>Webhook not triggering updates</h3><pre># Verify the webhook port is reachable from outside<br>curl -v https://argo-imageupdater.example.com/api/v1/test</pre><pre># Check Image Updater logs for incoming webhook events<br>kubectl logs -n argocd -l app.kubernetes.io/name=argocd-image-updater --tail=50 | grep -i webhook</pre><pre># Check the Service is correctly targeting the pod<br>kubectl get endpoints argocd-image-updater-webhook -n argocd</pre><h3>Tag regex not matching</h3><pre># Check which annotations are on the Application<br>kubectl get application my-app-dev -n argocd -o jsonpath=&#39;{.metadata.annotations}&#39; | python3 -m json.tool<br># Test your regex against sample tags (Go regex syntax)<br># Note: Image Updater uses Go&#39;s regexp package, not POSIX or Perl<br># \d is supported, but character classes like [:digit:] are not</pre><h3>Conclusion</h3><p>ArgoCD Image Updater with per-environment regex tags and Git write-back gives you a clean automated image delivery pipeline without any custom tooling. The key points:</p><ul><li><strong>Regex tag isolation per environment</strong> means a dev image can never accidentally land in production, as the regex won’t match.</li><li><strong>Git write-back creates a real audit trail.</strong> Every deployment change is a commit. Rollbacks are git reverts.</li><li><strong>The webhook integration</strong> cuts update latency from minutes to seconds without any polling overhead.</li><li><strong>GCP Workload Identity authentication</strong> means no credentials to manage for registry access either.</li></ul><p>Combined with the ApplicationSet pattern from Part 2 and the cluster registration setup from Part 1, you have a complete, credential-free GitOps platform for multi-cluster Kubernetes on GCP.</p><p>Parts in this series:</p><ul><li><strong>Part 1</strong>:<a href="https://medium.com/@abdelrahmanelshahat00/deploying-argocd-on-a-management-cluster-and-registering-gke-clusters-with-gcp-workload-identity-476fda65cf1c?sharedUserId=abdelrahmanelshahat00"> Deploying ArgoCD on a Management Cluster and Registering GKE Clusters with GCP Workload Identity</a></li><li><strong>Part 2</strong>: <a href="https://medium.com/@abdelrahmanelshahat00/argocd-applicationsets-for-environment-based-helm-gitops-f7febea2d312?sharedUserId=abdelrahmanelshahat00">ArgoCD ApplicationSets for Environment-Based Helm GitOps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ec60017d02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArgoCD ApplicationSets for Environment-Based Helm GitOps]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/argocd-applicationsets-for-environment-based-helm-gitops-f7febea2d312?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7febea2d312</guid>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 22:27:53 GMT</pubDate>
            <atom:updated>2026-07-24T22:27:53.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*jqeHnVnKQ4_KQZfM.png" /><figcaption>application set</figcaption></figure><h3>Introduction</h3><p><em>As Kubernetes footprints grow across multiple environments and clusters, managing deployments manually becomes unsustainable. You end up duplicating Helm configurations, maintaining separate manifests for dev, stage, and prod, and struggling with configuration drift.</em></p><p>This ApplicationSet pattern for environment-based deployments requires only Helm and Git. Each environment lives in its own Git folder, and each folder contains a Helm Chart.yaml and values.yaml. ArgoCD renders the chart from that folder, and Helm resolves the dependency declared in Chart.yaml before syncing.</p><p><em>If you haven’t set up your clusters yet, check out </em><a href="https://medium.com/@abdelrahmanelshahat00/deploying-argocd-on-a-management-cluster-and-registering-gke-clusters-with-gcp-workload-identity-476fda65cf1c?sharedUserId=abdelrahmanelshahat00"><strong><em>Deploying ArgoCD on a Management Cluster and Registering GKE Clusters with GCP Workload Identity</em></strong></a><em> before continuing.</em></p><h3>Prerequisites</h3><ul><li>A running ArgoCD installation (v2.6+)</li><li>A Git repository with one folder per environment, and each folder containing Chart.yaml and values.yaml</li><li>Basic familiarity with ArgoCD Applications and Helm</li></ul><h3>Architecture Overview</h3><p>The setup has two pieces:</p><ul><li><strong>An environment chart repository.</strong> Each folder is a Helm chart for one environment and contains both Chart.yaml and values.yaml. The chart file points to the upstream Helm dependency.</li><li><strong>An ApplicationSet.</strong> A single Kubernetes resource generates one ArgoCD Application per environment using a flat list of elements.</li></ul><p>The Git repository structure looks like this:</p><pre>demo-app/<br>├── dev/<br>│   ├── Chart.yaml<br>│   └── values.yaml<br>├── stage/<br>│   ├── Chart.yaml<br>│   └── values.yaml<br>└── prod/<br>    ├── Chart.yaml<br>    └── values.yaml</pre><p>Each environment folder is a small Helm chart wrapper. Chart.yaml declares the dependency on the real application chart, and values.yaml contains the environment-specific overrides.</p><p><em>If you want to deploy another application, you simply create a new top-level folder (e.g., </em><em>another-app/) alongside </em><em>demo-app/ in the same Git repository and follow the exact same environment folder pattern.</em></p><h3>Step 1: Define Your Environment List</h3><p>The List generator flattens a static list of environments into individual Applications. Each element carries everything needed to deploy one environment chart: the environment name, the path to the chart folder, the target namespace, and the destination cluster.</p><p>Here is what the generator section looks like:</p><pre>spec:<br>  generators:<br>    - list:<br>        elements:<br>          - name: dev<br>            chartPath: dev<br>            namespace: demo-dev<br>            destination_server: https://dev-cluster-api-endpoint<br>          - name: stage<br>            chartPath: stage<br>            namespace: demo-stage<br>            destination_server: https://stage-cluster-api-endpoint<br>          - name: prod<br>            chartPath: prod<br>            namespace: demo-prod<br>            destination_server: https://prod-cluster-api-endpoint</pre><p><strong>Key decisions:</strong></p><ul><li>The name field becomes the ArgoCD Application name.</li><li>chartPath points to the folder that contains the environment chart.</li><li>The only thing that changes between environments is the folder name and the values inside that folder.</li></ul><h3>Step 2: How ArgoCD and Helm Resolve the Chart</h3><p>ArgoCD points at the environment folder, and that folder is a Helm chart. When the repo-server renders the Application, Helm reads Chart.yaml, downloads the dependency listed there, and merges the local values.yaml.</p><pre>template:<br>  metadata:<br>    name: &quot;demo-{{ .name }}&quot;<br>    annotations:<br>      argocd.argoproj.io/manifest-generate-paths: &quot;/{{ .chartPath }}&quot;<br>    finalizers:<br>      - resources-finalizer.argocd.argoproj.io<br>spec:<br>    project: demo-app<br>    source:<br>      repoURL: https://github.com/example/demo-app.git<br>      targetRevision: main<br>      path: &quot;{{ .chartPath }}&quot;<br>      helm:<br>        releaseName: demo-app<br>    destination:<br>      server: &quot;{{ .destination_server }}&quot;<br>      namespace: &quot;{{ .namespace }}&quot;<br>    syncPolicy:<br>      syncOptions:<br>        - CreateNamespace=true<br>        - ServerSideApply=true</pre><p><strong>How the chart dependency works:</strong></p><ul><li>The environment folder is the Helm chart source that ArgoCD watches.</li><li>Helm reads Chart.yaml and resolves the dependency before rendering templates.</li><li>The local values.yaml file overrides the chart defaults for that specific environment.</li><li>The manifest-generate-paths annotation keeps refreshes scoped to the matching environment folder.</li></ul><h3>Step 3: The Chart.yaml Dependency Inside Each Environment</h3><p>Each environment folder contains the same Helm chart structure, and the only difference is the overridden values. The dependency declaration in Chart.yaml is what tells Helm where the real application chart lives.</p><pre>apiVersion: v2<br>appVersion: &quot;1.0&quot;<br>name: demo-app<br>description: A Helm chart for Kubernetes deployment<br>type: application<br>version: 1.1.0<br>dependencies:<br>  - name: service<br>    version: 1.1.3<br>    repository: https://charts.example.com/stable</pre><p>When ArgoCD renders the chart, Helm fetches that dependency automatically. You do not need to vendor the upstream chart into the repository. You only keep the environment wrapper, the dependency reference, and the environment-specific overrides.</p><h3>Step 4: Why This Pattern Scales</h3><p>This pattern scales because every environment follows the same shape. The chart structure stays the same, the dependency stays the same, and only the values change. That makes environment promotion a Git diff instead of a rebuild of the deployment model.</p><h3>Step 5: Putting It All Together</h3><p>Here is the minimal shape of the ApplicationSet:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: ApplicationSet<br>metadata:<br>  name: demo-app-envs<br>  namespace: argocd<br>spec:<br>  goTemplate: true<br>  goTemplateOptions: [&quot;missingkey=error&quot;]<br>  generators:<br>    - list:<br>        elements:<br>          - name: dev<br>            chartPath: dev<br>            namespace: demo-dev<br>            destination_server: https://dev-cluster-api-endpoint<br>          - name: stage<br>            chartPath: stage<br>            namespace: demo-stage<br>            destination_server: https://stage-cluster-api-endpoint<br>          - name: prod<br>            chartPath: prod<br>            namespace: demo-prod<br>            destination_server: https://prod-cluster-api-endpoint<br>  template:<br>    metadata:<br>      name: &quot;demo-{{ .name }}&quot;<br>      annotations:<br>        argocd.argoproj.io/manifest-generate-paths: &quot;/{{ .chartPath }}&quot;<br>    spec:<br>      project: demo-app<br>      source:<br>        repoURL: https://github.com/example/demo-app.git<br>        targetRevision: main<br>        path: &quot;{{ .chartPath }}&quot;<br>        helm:<br>          releaseName: demo-app<br>      destination:<br>        server: &quot;{{ .destination_server }}&quot;<br>        namespace: &quot;{{ .namespace }}&quot;<br>      syncPolicy:<br>        syncOptions:<br>          - CreateNamespace=true<br>          - ServerSideApply=true</pre><p>The repo only needs the three environment folders, and each folder carries the chart and values it needs. ArgoCD generates one Application per folder and Helm resolves the dependency declared locally.</p><h3>Step 6: Apply and Verify</h3><p>Apply the ApplicationSet to your management cluster:</p><pre>kubectl apply -f applicationset.yaml</pre><p>Verify that the ApplicationSet controller generated the three Applications based on the list generator:</p><pre>kubectl get applications -n argocd</pre><pre># Example result<br>NAME         SYNC STATUS   HEALTH STATUS<br>demo-dev     Synced        Healthy<br>demo-prod    Synced        Healthy<br>demo-stage   Synced        Healthy</pre><h3>Conclusion</h3><p>The ApplicationSet List generator with Helm manages environment-based deployments. A single ApplicationSet definition covers dev, stage, and prod, and environment differences live entirely in Git.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7febea2d312" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying ArgoCD on a Management Cluster and Registering GKE Clusters with GCP Workload Identity]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/deploying-argocd-on-a-management-cluster-and-registering-gke-clusters-with-gcp-workload-identity-476fda65cf1c?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/476fda65cf1c</guid>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 22:12:00 GMT</pubDate>
            <atom:updated>2026-07-26T06:06:54.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*Tu9_47xNStnvXtjV.jpg" /></figure><h3>Introduction</h3><p>The standard way to add a cluster to ArgoCD is argocd cluster add, which reads your local kubeconfig and creates a Kubernetes Secret with a service account token. That works fine for a single cluster but breaks down at scale: tokens expire, secrets drift, and you end up with a pile of credentials that need rotation.</p><p>On GCP there’s a cleaner path. <strong>GCP Workload Identity</strong> lets Kubernetes Service Accounts assume GCP IAM Service Account identities, which means ArgoCD running on a dedicated management cluster can authenticate to other GKE clusters using short-lived, automatically-rotated GCP tokens. Zero static secrets.</p><p>This article sets up the foundation for the rest of the series. ArgoCD runs in its own management cluster with HA. One workload cluster hosts dev and stage in separate namespaces, and the second workload cluster hosts prod in its own namespace. The next article uses that topology to show the ApplicationSet pattern, and the last one adds Image Updater.</p><p>ArgoCD Multi-Cluster Topology Architecture</p><h3>Step 0: Install ArgoCD on the Management Cluster with Helm HA</h3><p>ArgoCD should run in a separate management cluster, not alongside the workload namespaces. A minimal HA-style Helm install keeps the control plane isolated and ready for production use.</p><pre>helm repo add argo https://argoproj.github.io/argo-helm<br>helm repo update</pre><pre>helm install argocd argo/argo-cd \<br>  --namespace argocd \<br>  --create-namespace \<br>  --values values-ha.yaml</pre><p>A production-oriented values file enables multiple replicas for the server, controller, and repo-server. The exact sizing can vary, but the goal is the same: keep ArgoCD available even if one pod restarts.</p><p>A quick check after install:</p><pre>kubectl get pods -n argocd</pre><pre># Example result<br>NAME                                                READY   STATUS    RESTARTS   AGE<br>argocd-application-controller-0                     1/1     Running   0          2m<br>argocd-application-controller-1                     1/1     Running   0          2m<br>argocd-application-controller-2                     1/1     Running   0          2m<br>argocd-applicationset-controller-58467bc44c-hp2dg   1/1     Running   0          2m<br>argocd-applicationset-controller-58467bc44c-k8bx9   1/1     Running   0          2m<br>argocd-applicationset-controller-58467bc44c-kss8x   1/1     Running   0          2m<br>argocd-notifications-controller-67695f748-9q5sp     1/1     Running   0          2m<br>argocd-redis-57c494579-92fcw                        1/1     Running   0          2m<br>argocd-repo-server-6fd87d5d5f-gs5fq                 1/1     Running   0          2m<br>argocd-repo-server-6fd87d5d5f-pndlm                 1/1     Running   0          2m<br>argocd-repo-server-6fd87d5d5f-v994p                 1/1     Running   0          2m<br>argocd-server-7f5b86f85c-294tn                      1/1     Running   0          2m<br>argocd-server-7f5b86f85c-wbqv6                      1/1     Running   0          2m<br>argocd-server-7f5b86f85c-zjvsx                      1/1     Running   0          2m</pre><p>That gives you the management plane where cluster registration and later ApplicationSet reconciliation will happen.</p><h3>Prerequisites</h3><ul><li>ArgoCD running on a GKE cluster (the management cluster)</li><li>A second GKE cluster for the prod namespace</li><li>Workload Identity enabled on the management cluster’s node pool</li><li>gcloud CLI and kubectl configured</li></ul><h3>How It Works</h3><p>The authentication chain works like this:</p><ol><li>ArgoCD’s Kubernetes Service Account (KSA) is annotated with a GCP Service Account (GSA) email.</li><li>A Workload Identity IAM binding allows that KSA to impersonate the GSA.</li><li>When ArgoCD needs to talk to a workload cluster, it calls argocd-k8s-auth gcp — a binary built into the ArgoCD image that fetches a short-lived GCP access token.</li><li>That token is used as a bearer token to authenticate to the workload cluster’s Kubernetes API.</li><li>The GSA has roles/container.admin on the workload cluster&#39;s project, which grants full cluster access.</li></ol><p>No static tokens. No service account keys. No kubeconfig files stored anywhere.</p><h3>Step 1: Create a Shared GCP Service Account</h3><p>You need one GCP Service Account that ArgoCD will impersonate. Create it in the management cluster’s GCP project:</p><pre>gcloud iam service-accounts create argocd-cluster-manager \<br>  --display-name=&quot;ArgoCD Cluster Manager&quot; \<br>  --project=demo-management-project</pre><p>This single GSA will be shared by all ArgoCD components that need cluster access: argocd-application-controller, argocd-server, and (if you&#39;re running it) argocd-image-updater.</p><h3>Step 2: Create Workload Identity Bindings</h3><p>For each ArgoCD Kubernetes Service Account that needs cluster access, create a Workload Identity IAM binding. The binding grants the KSA the roles/iam.workloadIdentityUser role on the GSA.</p><pre>gcloud iam service-accounts add-iam-policy-binding \<br>  argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com \<br>  --role=&quot;roles/iam.workloadIdentityUser&quot; \<br>  --member=&quot;serviceAccount:demo-management-project.svc.id.goog[argocd/argocd-application-controller]&quot;</pre><p><strong>Member format breakdown:</strong></p><ul><li>demo-management-project.svc.id.goog is the Workload Identity pool identifier for the project.</li><li>[argocd/argocd-application-controller] is the namespace/serviceaccount of the KSA.</li></ul><h3>Step 3: Annotate the ArgoCD Kubernetes Service Accounts</h3><p>The KSA must be annotated with the GSA email. This links the two identities together. Without the annotation, GKE’s metadata server won’t issue tokens for the GSA.</p><pre>kubectl annotate serviceaccount argocd-application-controller \<br>  -n argocd \<br>  iam.gke.io/gcp-service-account=argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com</pre><p>If you are deploying ArgoCD via Helm, add these annotations in your values.yaml so they&#39;re applied on every upgrade:</p><pre>controller:<br>  serviceAccount:<br>    annotations:<br>      iam.gke.io/gcp-service-account: argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com</pre><h3>Step 4: Grant IAM Access on Each Workload Cluster</h3><p>For each GKE cluster you want ArgoCD to manage, grant the GSA roles/container.admin on that cluster&#39;s GCP project. This gives ArgoCD full Kubernetes API access to that cluster.</p><pre># Grant container.admin on the workload cluster&#39;s project<br>gcloud projects add-iam-policy-binding demo-workload-project \<br>  --role=&quot;roles/container.admin&quot; \<br>  --member=&quot;serviceAccount:argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com&quot;</pre><p>Repeat this for every GCP project that hosts a cluster you want to register. You do not need to repeat the Workload Identity binding — that only needs to be set up once on the management project.</p><h3>Step 5: Create the ArgoCD Cluster Secret</h3><p>ArgoCD recognizes clusters by Kubernetes Secrets with the label argocd.argoproj.io/secret-type=cluster. The Secret holds the cluster name, API server URL, CA certificate, and auth configuration.</p><p>Instead of a static token, we configure an <strong>exec provider</strong> — ArgoCD calls argocd-k8s-auth gcp to get a fresh token on every API call:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: cluster-my-workload-cluster<br>  namespace: argocd<br>  labels:<br>    argocd.argoproj.io/secret-type: cluster<br>type: Opaque<br>stringData:<br>  name: my-workload-cluster<br>  server: &quot;https://&lt;cluster-api-endpoint&gt;&quot;<br>  config: |<br>    {<br>      &quot;execProviderConfig&quot;: {<br>        &quot;command&quot;: &quot;argocd-k8s-auth&quot;,<br>        &quot;args&quot;: [&quot;gcp&quot;],<br>        &quot;apiVersion&quot;: &quot;client.authentication.k8s.io/v1beta1&quot;<br>      },<br>      &quot;tlsClientConfig&quot;: {<br>        &quot;insecure&quot;: false,<br>        &quot;caData&quot;: &quot;&lt;base64-encoded-cluster-ca-certificate&gt;&quot;<br>      }<br>    }</pre><p><strong>Key configuration choices:</strong></p><ul><li>command: argocd-k8s-auth specifies the binary built into the ArgoCD image. It calls the GKE metadata server to get a short-lived OAuth2 access token for the annotated GSA.</li><li>args: [&quot;gcp&quot;] selects the GCP token provider inside argocd-k8s-auth.</li><li>caData is the base64-encoded CA certificate of the target cluster. Get this from the cluster&#39;s master_auth.cluster_ca_certificate field or from gcloud container clusters describe.</li><li>insecure: false ensures the client always validates the server certificate using the CA data.</li></ul><h3>Step 6: Retrieve the Cluster API Endpoint and CA Certificate</h3><p>You need two values per cluster: the API server endpoint and the CA certificate. Get them from the GKE cluster description:</p><pre>gcloud container clusters describe demo-workload-cluster \<br>  --region=us-central1 \<br>  --project=demo-workload-project \<br>  --format=&quot;value(endpoint)&quot;</pre><p>Plug those values into the cluster Secret from Step 5 and apply it:</p><pre>kubectl apply -f cluster-secret.yaml</pre><p>ArgoCD will detect the new Secret and the cluster will appear in the cluster list within seconds:</p><pre>argocd cluster list</pre><h3>Step 7: Adding More Clusters</h3><p>Adding a new cluster is now a repeatable three-step operation:</p><ol><li>Grant roles/container.admin on the new cluster&#39;s GCP project (Step 4).</li><li>Retrieve the endpoint and CA certificate (Step 6).</li><li>Apply the cluster Secret (Step 5).</li></ol><p>You do not need to manage token rotation, distribute kubeconfig files, or store static credentials.</p><h3>Verifying the Setup</h3><p>After applying the Secret, verify the cluster connection is working:</p><pre>argocd cluster list<br><br>argocd cluster get https://&lt;cluster-api-endpoint&gt;<br><br>kubectl get secret cluster-my-workload-cluster -n argocd -o jsonpath=&#39;{.data.config}&#39; | base64 -d | python3 -m json.tool</pre><p>You can also validate from ArgoCD’s UI by going to Settings and checking the connection status. A green checkmark means the exec token flow is working end-to-end.</p><h3>Security Considerations</h3><ul><li><strong>Principle of least privilege.</strong> roles/container.admin is broad. If you want finer-grained access, create a custom IAM role or use Kubernetes RBAC with a namespaced service account on the workload cluster side, though ArgoCD typically needs cluster-wide access to manage resources across namespaces.</li><li><strong>One GSA, multiple clusters.</strong> The shared GSA approach is convenient but means compromising one component (e.g., repo-server) doesn’t directly expose cluster credentials since repo-server doesn’t need the cluster access annotation. Keep WI bindings tight to only the SAs that actually need cluster access.</li><li><strong>Token TTL.</strong> GCP access tokens have a 1-hour TTL by default. argocd-k8s-auth fetches a fresh one on every use. There is no caching concern, but you should be aware that each API call to the workload cluster hits the GKE metadata server.</li><li><strong>Cross-project registrations.</strong> The IAM binding on the workload project is at the project level, not the cluster level. If your project hosts multiple GKE clusters, the GSA gains container.admin on all of them. Keep clusters that require stricter isolation in separate projects.</li></ul><h3>Troubleshooting</h3><h3>Cluster shows as “Unknown” or connection fails</h3><pre>kubectl logs -n argocd -l app.kubernetes.io/name=argocd-application-controller --tail=50 | grep -i &quot;error\|denied\|unauthorized&quot;</pre><pre># Verify the WI annotation on the KSA<br>kubectl get serviceaccount argocd-application-controller -n argocd -o yaml | grep iam.gke.io</pre><pre># Test token retrieval manually from within the ArgoCD pod<br>kubectl exec -n argocd deploy/argocd-application-controller -- argocd-k8s-auth gcp</pre><h3>403 Forbidden on workload cluster API</h3><pre># Verify container.admin binding on the workload project<br>gcloud projects get-iam-policy demo-workload-project \<br>  --flatten=&quot;bindings[].members&quot; \<br>  --filter=&quot;bindings.members:argocd-cluster-manager&quot; \<br>  --format=&quot;table(bindings.role)&quot;</pre><h3>Workload Identity not resolving</h3><pre># Check that Workload Identity is enabled on the node pool<br>gcloud container node-pools describe default-pool \<br>  --cluster=demo-management-cluster \<br>  --region=us-central1 \<br>  --project=demo-management-project \<br>  --format=&quot;value(config.workloadMetadataConfig.mode)&quot;<br># Should output: GKE_METADATA</pre><pre># Verify the IAM binding exists<br>gcloud iam service-accounts get-iam-policy \<br>  argocd-cluster-manager@demo-management-project.iam.gserviceaccount.com</pre><h3>Conclusion</h3><p>GCP Workload Identity eliminates the biggest pain point in multi-cluster ArgoCD setups: credential management. The exec provider approach in the cluster Secret is a few lines of JSON, but behind it sits a fully automated token lifecycle that GKE manages for you.</p><p>Once the setup is in place, adding a new cluster is purely an IAM and Secret operation. You don’t need SSH access, a kubeconfig file, or manual credential rotation.</p><p>The next part of this series covers the ApplicationSet pattern that uses these two clusters, with dev and stage on separate namespaces in the first cluster and prod on the second cluster.</p><p>Parts in this series:</p><ul><li><strong>Part 2</strong>: <a href="https://medium.com/@abdelrahmanelshahat00/argocd-applicationsets-for-environment-based-helm-gitops-f7febea2d312?sharedUserId=abdelrahmanelshahat00">ArgoCD ApplicationSets: Environment-Based Helm GitOps with Chart Dependencies</a></li><li><strong>Part 3</strong>: <a href="https://medium.com/@abdelrahmanelshahat00/argocd-image-updater-for-regex-tag-strategies-and-git-write-back-50ec60017d02?sharedUserId=abdelrahmanelshahat00">ArgoCD Image Updater: Regex Tag Strategies, Git Write-Back, and Webhook Integration</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=476fda65cf1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Your Kafka Cluster: Metrics, Dashboards, and Kafka UI]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/monitoring-your-kafka-cluster-metrics-dashboards-and-kafka-ui-75128b418bc6?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/75128b418bc6</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 11:28:35 GMT</pubDate>
            <atom:updated>2026-01-01T11:33:22.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*brkXB2q53NV8xscZ.png" /></figure><p>In The <a href="https://medium.com/@abdelrahmanelshahat00/deploying-production-ready-apache-kafka-on-kubernetes-with-strimzi-kraft-mode-644db3427332"><strong>previous Article</strong></a> , we learned how to deploy a Kafka cluster on Kubernetes using Strimzi.</p><p>Now, we’ll take it one step further.</p><p>In this article, I’ll show you how to monitor and operate the cluster using:</p><ul><li><strong>JMX Prometheus Exporter</strong> for metrics collection</li><li><strong>Grafana Dashboard</strong> for visualization</li><li><strong>Alerts</strong> to detect anomalies</li><li><strong>Kafka UI</strong> for cluster management</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWdyef3q0P30aUj_vLercA.jpeg" /><figcaption><strong>Architecture Overview</strong></figcaption></figure><h3>Prerequisites</h3><ul><li><strong>Kafka Cluster</strong></li><li><strong>Prometheus monitoring stack</strong> with <strong>Alertmanager</strong> configured</li></ul><h4><strong>Configuring JMX Prometheus Exporter</strong></h4><p>Strimzi includes a built-in JMX Prometheus Exporter that converts Kafka’s JMX MBeans into Prometheus metrics. We need to configure which metrics to expose.</p><p>its the same configmap in the<strong> </strong><a href="https://medium.com/@abdelrahmanelshahat00/deploying-production-ready-apache-kafka-on-kubernetes-with-strimzi-kraft-mode-644db3427332"><strong>previous article</strong></a></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: kafka-metrics<br>  namespace: kafka<br>  labels:<br>    app: strimzi<br>data:<br>  kafka-metrics-config.yml: |<br>    lowercaseOutputName: true<br>    rules:<br>    # Special cases and very specific rules<br>    - pattern: kafka.server&lt;type=(.+), name=(.+), clientId=(.+), topic=(.+), partition=(.*)&gt;&lt;&gt;Value<br>      name: kafka_server_$1_$2<br>      type: GAUGE<br>      labels:<br>        clientId: &quot;$3&quot;<br>        topic: &quot;$4&quot;<br>        partition: &quot;$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), name=(.+), clientId=(.+), brokerHost=(.+), brokerPort=(.+)&gt;&lt;&gt;Value<br>      name: kafka_server_$1_$2<br>      type: GAUGE<br>      labels:<br>        clientId: &quot;$3&quot;<br>        broker: &quot;$4:$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), cipher=(.+), protocol=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;connections<br>      name: kafka_server_$1_connections_tls_info<br>      type: GAUGE<br>      labels:<br>        cipher: &quot;$2&quot;<br>        protocol: &quot;$3&quot;<br>        listener: &quot;$4&quot;<br>        networkProcessor: &quot;$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), clientSoftwareName=(.+), clientSoftwareVersion=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;connections<br>      name: kafka_server_$1_connections_software<br>      type: GAUGE<br>      labels:<br>        clientSoftwareName: &quot;$2&quot;<br>        clientSoftwareVersion: &quot;$3&quot;<br>        listener: &quot;$4&quot;<br>        networkProcessor: &quot;$5&quot;<br>    - pattern: &quot;kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+-total):&quot;<br>      name: kafka_server_$1_$4<br>      type: COUNTER<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: &quot;kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_$1_$4<br>      type: GAUGE<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+-total)<br>      name: kafka_server_$1_$4<br>      type: COUNTER<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+)<br>      name: kafka_server_$1_$4<br>      type: GAUGE<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    # Some percent metrics use MeanRate attribute<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*&gt;&lt;&gt;MeanRate<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>    # Generic gauges for percents<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*, (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    # Generic per-second counters with 0-2 key/value pairs<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*, (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*, (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>    # Generic gauges with 0-2 key/value pairs<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>    # Emulate Prometheus &#39;Summary&#39; metrics for the exported &#39;Histogram&#39;s.<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.*), (.+)=(.+)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>        quantile: &quot;0.$8&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.*)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        quantile: &quot;0.$6&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        quantile: &quot;0.$4&quot;<br>    # KRaft overall related metrics<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(.+-total|.+-max):&quot;<br>      name: kafka_server_raftmetrics_$1<br>      type: COUNTER<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(current-state): (.+)&quot;<br>      name: kafka_server_raftmetrics_$1<br>      value: 1<br>      type: UNTYPED<br>      labels:<br>        $1: &quot;$2&quot;<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_raftmetrics_$1<br>      type: GAUGE<br>    - pattern: &quot;kafka.server&lt;type=raft-channel-metrics&gt;&lt;&gt;(.+-total|.+-max):&quot;<br>      name: kafka_server_raftchannelmetrics_$1<br>      type: COUNTER<br>    - pattern: &quot;kafka.server&lt;type=raft-channel-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_raftchannelmetrics_$1<br>      type: GAUGE<br>    - pattern: &quot;kafka.server&lt;type=broker-metadata-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_brokermetadatametrics_$1<br>      type: GAUGE<br>    # Catch all java.lang metrics<br>    - pattern: &quot;java.lang&lt;.*&gt;&quot;</pre><h4>Metrics Explaination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuTR8xk2PqPuMvI14LRyNA.png" /></figure><h4><strong>Setting Up Prometheus Scraping</strong></h4><p><em>For Prometheus to scrape the Kafka metrics, we need to create a </em><strong><em>PodMonitor</em></strong><em> resource</em></p><pre># kafka-podmonitor.yaml<br>apiVersion: monitoring.coreos.com/v1<br>kind: PodMonitor<br>metadata:<br>  name: kafka-metrics<br>  namespace: monitoring  # Where Prometheus is installed<br>  labels:<br>    app: strimzi<br>    release: prometheus  # Match your Prometheus selector labels<br>spec:<br>  namespaceSelector:<br>    matchNames:<br>      - kafka<br>  selector:<br>    matchLabels:<br>      strimzi.io/cluster: my-kafka-cluster<br>      strimzi.io/kind: Kafka<br>  podMetricsEndpoints:<br>    - port: tcp-prometheus<br>      path: /metrics<br>      interval: 30s<br>      relabelings:<br>        # Add pool label (controllers vs brokers)<br>        - sourceLabels: [__meta_kubernetes_pod_label_strimzi_io_pool_name]<br>          targetLabel: pool<br>        # Preserve pod name<br>        - sourceLabels: [__meta_kubernetes_pod_name]<br>          targetLabel: pod<br>        # Preserve namespace<br>        - sourceLabels: [__meta_kubernetes_namespace]<br>          targetLabel: namespace</pre><p>Apply and verify:</p><pre>kubectl apply -f kafka-podmonitor.yaml</pre><pre># Verify Prometheus is scraping<br>kubectl port-forward svc/prometheus 9090:9090 -n monitoring<br># Open http://localhost:9090/targets and look for kafka-metrics</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhxtgHijmsS2XOBho_ClIQ.png" /><figcaption>Target Health on prometheus</figcaption></figure><h4><strong>Import the Grafana Dashboard</strong></h4><p>I’ve created a <a href="https://grafana.com/grafana/dashboards/24626-strimzi-kafka-dashboard-with-jvm-metrics/"><strong>custom Grafana dashboard</strong></a><strong> </strong>that works out-of-the-box with the metrics we configured. It’s based on the official Strimzi dashboard but with fixed label selectors for <strong>java_lang_*</strong> JVM metrics.</p><ul><li>Open Grafana</li><li>Go to <strong>Dashboards</strong> → <strong>Import</strong></li><li>Enter Dashboard ID: <strong>24626</strong></li><li>Select your Prometheus data source</li><li>Click <strong>Import</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhV7Hd9jmFE8zymfKrJC3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHGs5UtsflM-bt9sXr4omw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OJh0LPoaTFQ-uTSabYslg.png" /><figcaption>strimzi kafka Dashboard</figcaption></figure><h3>Deploying Kafka UI</h3><p>Kafka UI is an excellent open-source web interface for managing Kafka clusters. It provides:</p><ul><li>Topic management (create, delete, view messages)</li><li>Consumer group monitoring</li><li>Broker configuration viewing</li></ul><pre># kafka-ui.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: kafka-ui<br>  namespace: kafka<br>  labels:<br>    app: kafka-ui<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: kafka-ui<br>  template:<br>    metadata:<br>      labels:<br>        app: kafka-ui<br>    spec:<br>      containers:<br>        - name: kafka-ui<br>          image: provectuslabs/kafka-ui:latest<br>          ports:<br>            - containerPort: 8080<br>              name: http<br>          env:<br>            - name: KAFKA_CLUSTERS_0_NAME<br>              value: &quot;my-kafka-cluster&quot;<br>            - name: KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS<br>              value: &quot;my-kafka-cluster-kafka-bootstrap:9092&quot;<br>            - name: DYNAMIC_CONFIG_ENABLED<br>              value: &quot;true&quot;<br>            - name: AUTH_TYPE<br>              value: &quot;DISABLED&quot;  # Enable auth in production!<br>          resources:<br>            requests:<br>              memory: 256Mi<br>              cpu: 100m<br>            limits:<br>              memory: 512Mi<br>              cpu: 500m<br>          livenessProbe:<br>            httpGet:<br>              path: /actuator/health<br>              port: 8080<br>            initialDelaySeconds: 30<br>            periodSeconds: 30<br>          readinessProbe:<br>            httpGet:<br>              path: /actuator/health<br>              port: 8080<br>            initialDelaySeconds: 10<br>            periodSeconds: 10<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: kafka-ui<br>  namespace: kafka<br>  labels:<br>    app: kafka-ui<br>spec:<br>  type: ClusterIP<br>  ports:<br>    - port: 8080<br>      targetPort: 8080<br>      protocol: TCP<br>      name: http<br>  selector:<br>    app: kafka-ui</pre><p>Apply and access:</p><pre>kubectl apply -f kafka-ui.yaml<br><br># Port-forward to access locally<br>kubectl port-forward svc/kafka-ui 8080:8080 -n kafka<br><br># Open http://localhost:8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1bTnhK-smLrmKEVy77tzQ.png" /><figcaption>kafka UI</figcaption></figure><h3>Setting Up Alerts</h3><p>Essential Prometheus alerts for Kafka :</p><pre># kafka-alerts.yaml<br>apiVersion: monitoring.coreos.com/v1<br>kind: PrometheusRule<br>metadata:<br>  name: kafka-alerts<br>  namespace: monitoring<br>spec:<br>  groups:<br>    - name: kafka<br>      rules:<br>        - alert: KafkaUnderReplicatedPartitions<br>          expr: kafka_server_replicamanager_underreplicatedpartitions &gt; 0<br>          for: 5m<br>          labels:<br>            severity: warning<br>          annotations:<br>            summary: &quot;Kafka has under-replicated partitions&quot;<br>            description: &quot;{{ $value }} partitions are under-replicated&quot;<br><br>        - alert: KafkaOfflinePartitions<br>          expr: kafka_controller_kafkacontroller_offlinepartitionscount &gt; 0<br>          for: 1m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: &quot;Kafka has offline partitions&quot;<br>            description: &quot;{{ $value }} partitions are offline&quot;<br><br>        - alert: KafkaNoActiveController<br>          expr: kafka_controller_kafkacontroller_activecontrollercount != 1<br>          for: 1m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: &quot;Kafka has no active controller&quot;<br>            description: &quot;Expected 1 active controller, got {{ $value }}&quot;<br><br>        - alert: KafkaBrokerDown<br>          expr: count(kafka_server_replicamanager_leadercount) &lt; 3<br>          for: 5m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: &quot;Kafka broker is down&quot;<br>            description: &quot;Only {{ $value }} brokers are online&quot;</pre><h3>Conclusion</h3><p>We now have comprehensive monitoring for your Strimzi Kafka cluster:</p><ul><li><strong>JMX Metrics</strong> exported via Prometheus</li><li><strong>Grafana Dashboard</strong> for visualization</li><li><strong>Kafka UI</strong> for cluster management</li><li><strong>Alerts</strong> for critical issues</li></ul><h3>Resources</h3><ul><li><a href="https://grafana.com/grafana/dashboards/24626"><strong>Grafana Dashboard (ID: 24626)</strong></a></li><li><a href="https://strimzi.io/docs/"><strong>Strimzi Documentation</strong></a></li><li><a href="https://github.com/provectus/kafka-ui"><strong>Kafka UI GitHub</strong></a></li><li><a href="https://github.com/prometheus/jmx_exporter"><strong>Prometheus JMX Exporter</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75128b418bc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Production-Ready Apache Kafka on Kubernetes with Strimzi (KRaft Mode)]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/deploying-production-ready-apache-kafka-on-kubernetes-with-strimzi-kraft-mode-644db3427332?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/644db3427332</guid>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 13:53:18 GMT</pubDate>
            <atom:updated>2026-01-01T11:01:46.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ahys0ed_Tph2rH-L.png" /></figure><h3>Introduction</h3><p>Apache Kafka is widely used for real-time data streaming. In this article, I’ll walk through deploying and running a Kafka cluster on Kubernetes using <strong>Strimzi</strong>, without ZooKeeper, and with separate controller and broker nodes.</p><h3><strong>Prerequisites</strong></h3><ul><li>A running Kubernetes cluster</li><li>At least 3 worker nodes with 4GB RAM each</li></ul><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrb3X4CyYMA5AaXQbD3l9g.jpeg" /></figure><h3><strong>Understanding KRaft Mode:</strong></h3><p><strong>What is KRaft Mode?</strong></p><p><strong>KRaft</strong> (Kafka Raft) is Kafka’s new consensus protocol that replaces ZooKeeper. Introduced in Kafka 3.3 and production-ready since Kafka 3.5, KRaft offers:</p><ul><li><strong>Simplified architecture: </strong>No external ZooKeeper cluster to manage</li><li><strong>Faster failover: </strong>Controller election happens within seconds</li><li><strong>Better scalability: </strong>Supports millions of partitions</li><li><strong>Reduced operational complexity : </strong>One less system to monitor and maintain</li></ul><h3>Why Separate Controllers and Brokers?</h3><ul><li><strong>Resource Isolation : </strong>Controllers need minimal resources while brokers need maximum resources</li><li><strong>Improved Stability : </strong>Controller issues don’t affect the data</li><li><strong>Independent Scaling : </strong>Scale brokers without touching controllers</li><li><strong>Better Fault Tolerance : </strong>Different failure domains for metadata and data</li></ul><h3>Install the Strimzi Kafka Operator</h3><p><em>create the kafka namespace and install the Strimzi operator:</em></p><pre># Create kafka namespace<br>kubectl create namespace kafka<br># Install Strimzi operator using the official installation file<br>kubectl create -f &#39;https://strimzi.io/install/latest?namespace=kafka&#39; -n kafka</pre><p><em>Verify the operator is running:</em></p><pre>kubectl get pods -n kafka -l name=strimzi-cluster-operator<br># Expected output:<br># NAME                                        READY   STATUS    RESTARTS   AGE<br># strimzi-cluster-operator-xxxxxxxxxx-xxxxx   1/1     Running   0          1m</pre><p>The Strimzi operator watches for Kafka custom resources and automatically manages the Kafka cluster lifecycle.</p><h4><strong>Create the Metrics ConfigMap</strong></h4><p><em>Before deploying the cluster, let’s create the metrics configuration for monitoring:</em></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: kafka-metrics<br>  namespace: kafka<br>  labels:<br>    app: strimzi<br>data:<br>  kafka-metrics-config.yml: |<br>    lowercaseOutputName: true<br>    rules:<br>    # Special cases and very specific rules<br>    - pattern: kafka.server&lt;type=(.+), name=(.+), clientId=(.+), topic=(.+), partition=(.*)&gt;&lt;&gt;Value<br>      name: kafka_server_$1_$2<br>      type: GAUGE<br>      labels:<br>        clientId: &quot;$3&quot;<br>        topic: &quot;$4&quot;<br>        partition: &quot;$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), name=(.+), clientId=(.+), brokerHost=(.+), brokerPort=(.+)&gt;&lt;&gt;Value<br>      name: kafka_server_$1_$2<br>      type: GAUGE<br>      labels:<br>        clientId: &quot;$3&quot;<br>        broker: &quot;$4:$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), cipher=(.+), protocol=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;connections<br>      name: kafka_server_$1_connections_tls_info<br>      type: GAUGE<br>      labels:<br>        cipher: &quot;$2&quot;<br>        protocol: &quot;$3&quot;<br>        listener: &quot;$4&quot;<br>        networkProcessor: &quot;$5&quot;<br>    - pattern: kafka.server&lt;type=(.+), clientSoftwareName=(.+), clientSoftwareVersion=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;connections<br>      name: kafka_server_$1_connections_software<br>      type: GAUGE<br>      labels:<br>        clientSoftwareName: &quot;$2&quot;<br>        clientSoftwareVersion: &quot;$3&quot;<br>        listener: &quot;$4&quot;<br>        networkProcessor: &quot;$5&quot;<br>    - pattern: &quot;kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+-total):&quot;<br>      name: kafka_server_$1_$4<br>      type: COUNTER<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: &quot;kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_$1_$4<br>      type: GAUGE<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+-total)<br>      name: kafka_server_$1_$4<br>      type: COUNTER<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    - pattern: kafka.server&lt;type=(.+), listener=(.+), networkProcessor=(.+)&gt;&lt;&gt;(.+)<br>      name: kafka_server_$1_$4<br>      type: GAUGE<br>      labels:<br>        listener: &quot;$2&quot;<br>        networkProcessor: &quot;$3&quot;<br>    # Some percent metrics use MeanRate attribute<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*&gt;&lt;&gt;MeanRate<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>    # Generic gauges for percents<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)Percent\w*, (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3_percent<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    # Generic per-second counters with 0-2 key/value pairs<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*, (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*, (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)PerSec\w*&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_total<br>      type: COUNTER<br>    # Generic gauges with 0-2 key/value pairs<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;Value<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>    # Emulate Prometheus &#39;Summary&#39; metrics for the exported &#39;Histogram&#39;s.<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.*), (.+)=(.+)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        &quot;$6&quot;: &quot;$7&quot;<br>        quantile: &quot;0.$8&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+), (.+)=(.*)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        &quot;$4&quot;: &quot;$5&quot;<br>        quantile: &quot;0.$6&quot;<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;Count<br>      name: kafka_$1_$2_$3_count<br>      type: COUNTER<br>    - pattern: kafka.(\w+)&lt;type=(.+), name=(.+)&gt;&lt;&gt;(\d+)thPercentile<br>      name: kafka_$1_$2_$3<br>      type: GAUGE<br>      labels:<br>        quantile: &quot;0.$4&quot;<br>    # KRaft overall related metrics<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(.+-total|.+-max):&quot;<br>      name: kafka_server_raftmetrics_$1<br>      type: COUNTER<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(current-state): (.+)&quot;<br>      name: kafka_server_raftmetrics_$1<br>      value: 1<br>      type: UNTYPED<br>      labels:<br>        $1: &quot;$2&quot;<br>    - pattern: &quot;kafka.server&lt;type=raft-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_raftmetrics_$1<br>      type: GAUGE<br>    - pattern: &quot;kafka.server&lt;type=raft-channel-metrics&gt;&lt;&gt;(.+-total|.+-max):&quot;<br>      name: kafka_server_raftchannelmetrics_$1<br>      type: COUNTER<br>    - pattern: &quot;kafka.server&lt;type=raft-channel-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_raftchannelmetrics_$1<br>      type: GAUGE<br>    - pattern: &quot;kafka.server&lt;type=broker-metadata-metrics&gt;&lt;&gt;(.+):&quot;<br>      name: kafka_server_brokermetadatametrics_$1<br>      type: GAUGE<br>    # Catch all java.lang metrics<br>    - pattern: &quot;java.lang&lt;.*&gt;&quot;</pre><p>Apply it :</p><pre>kubectl apply -f metrics-configmap.yaml</pre><p><strong>Deploy the Controller Node Pool</strong></p><p>Controller Node Pool — Manages cluster metadata and leader election</p><pre># controllers_node_pool.yaml<br><br>apiVersion: kafka.strimzi.io/v1<br>kind: KafkaNodePool<br>metadata:<br>  name: controllers<br>  namespace: kafka<br>  labels:<br>    strimzi.io/cluster: my-kafka-cluster<br>spec:<br>  replicas: 3<br>  roles:<br>    - controller<br>  storage:<br>    type: jbod<br>    volumes:<br>      - id: 0<br>        type: persistent-claim<br>        size: 10Gi<br>        deleteClaim: false<br>        kraftMetadata: shared<br>        class: &lt;your-storage-class&gt;  # Adjust to your StorageClass<br>  resources:<br>    requests:<br>      memory: 512Mi<br>      cpu: &quot;250m&quot;<br>    limits:<br>      memory: 1Gi<br>      cpu: &quot;500m&quot;<br>  jvmOptions:<br>    -Xms: 256m<br>    -Xmx: 512m<br>    gcLoggingEnabled: true</pre><p>Apply it :</p><pre>kubectl apply -f controllers_node_pool.yaml</pre><p><strong>Controller Configuration Explained</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STxtnxfYrM9koGrXgs7coQ.png" /></figure><p><strong>Deploy the Broker Node Pool</strong></p><p>Broker Node Pool — Handles data storage and client connections</p><pre># brokers_node_pool.yaml<br>apiVersion: kafka.strimzi.io/v1<br>kind: KafkaNodePool<br>metadata:<br>  name: brokers<br>  namespace: kafka<br>  labels:<br>    strimzi.io/cluster: my-kafka-cluster<br>spec:<br>  replicas: 3<br>  roles:<br>    - broker<br>  storage:<br>    type: jbod<br>    volumes:<br>      - id: 0<br>        type: persistent-claim<br>        size: 100Gi  # Adjust based on your data retention needs<br>        deleteClaim: false<br>        class: &lt;your-storage-class&gt;<br>  resources:<br>    requests:<br>      memory: 2Gi<br>      cpu: &quot;500m&quot;<br>    limits:<br>      memory: 4Gi<br>      cpu: &quot;1500m&quot;<br>  jvmOptions:<br>    -Xms: 1g<br>    -Xmx: 2g<br>    gcLoggingEnabled: true</pre><p>Apply it :</p><pre>kubectl apply -f brokers_node_pool.yaml</pre><p><strong>Broker Configuration Explained</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wjc9VOKZ_xvOyS4UTFAUlA.png" /></figure><p><strong>Deploy the Kafka Cluster Configuration</strong></p><p>Main Kafka Cluster Configuration</p><pre># kafka_cluster.yaml<br>apiVersion: kafka.strimzi.io/v1<br>kind: Kafka<br>metadata:<br>  name: my-kafka-cluster<br>  namespace: kafka<br>  annotations:<br>    strimzi.io/node-pools: enabled<br>    strimzi.io/kraft: enabled  # Enable KRaft mode (no ZooKeeper)<br>spec:<br>  kafka:<br>    version: 4.0.0<br>    metadataVersion: 4.0-IV0<br><br>    listeners:<br>      - name: plain<br>        port: 9092<br>        type: internal<br>        tls: false<br>      - name: tls<br>        port: 9093<br>        type: internal<br>        tls: true<br><br>    config:<br>      # ========================================<br>      # Replication Settings (Fault Tolerance)<br>      # ========================================<br>      offsets.topic.replication.factor: 3<br>      transaction.state.log.replication.factor: 3<br>      transaction.state.log.min.isr: 2<br>      default.replication.factor: 3<br>      min.insync.replicas: 2<br><br>      # ========================================<br>      # Network Optimization<br>      # ========================================<br>      num.network.threads: 8<br>      num.io.threads: 8<br>      socket.send.buffer.bytes: 102400<br>      socket.receive.buffer.bytes: 102400<br>      socket.request.max.bytes: 104857600<br><br>      # ========================================<br>      # Log Retention (3 days)<br>      # ========================================<br>      log.retention.hours: 72<br>      log.segment.bytes: 1073741824  # 1GB segments<br>      log.retention.check.interval.ms: 300000<br>      log.cleaner.enable: true<br><br>      # ========================================<br>      # Performance Tuning<br>      # ========================================<br>      compression.type: lz4<br>      auto.create.topics.enable: false<br>      auto.leader.rebalance.enable: true<br>      leader.imbalance.check.interval.seconds: 300<br><br>      # ========================================<br>      # Replica Fetcher Configuration<br>      # ========================================<br>      replica.fetch.max.bytes: 10485760<br>      replica.fetch.min.bytes: 1<br>      replica.fetch.wait.max.ms: 500<br><br>    metricsConfig:<br>      type: jmxPrometheusExporter<br>      valueFrom:<br>        configMapKeyRef:<br>          name: kafka-metrics<br>          key: kafka-metrics-config.yml<br><br>  entityOperator:<br>    topicOperator:<br>      resources:<br>        requests:<br>          memory: 256Mi<br>          cpu: &quot;100m&quot;<br>        limits:<br>          memory: 512Mi<br>          cpu: &quot;500m&quot;<br>    userOperator:<br>      resources:<br>        requests:<br>          memory: 256Mi<br>          cpu: &quot;100m&quot;<br>        limits:<br>          memory: 512Mi<br>          cpu: &quot;500m&quot;</pre><p>Apply it :</p><pre>kubectl apply -f kafka_cluster.yaml</pre><p><strong>Key Configuration Decisions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb8pbfmb8DT7CjgnYYS4NA.png" /></figure><p><strong>Verify the Deployments</strong></p><pre>kubectl get pods -n kafka </pre><pre>NAME                                          READY   STATUS    RESTARTS   AGE<br>my-kafka-cluster-brokers-0                    1/1     Running   0          5m<br>my-kafka-cluster-brokers-1                    1/1     Running   0          5m<br>my-kafka-cluster-brokers-2                    1/1     Running   0          5m<br>my-kafka-cluster-controllers-3                1/1     Running   0          5m<br>my-kafka-cluster-controllers-4                1/1     Running   0          5m<br>my-kafka-cluster-controllers-5                1/1     Running   0          5m<br>my-kafka-cluster-entity-operator-xxx-xxx      2/2     Running   0          4m<br>strimzi-cluster-operator-xxx-xxx              1/1     Running   0          10m</pre><p><strong>Verify the cluster is ready:</strong></p><pre>kubectl get kafka -n kafka</pre><pre> NAME               READY   METADATA STATE   WARNINGS<br> my-kafka-cluster   True</pre><p><strong>Finally</strong> <strong>Your First Topic:</strong></p><pre># kafka-topic.yaml<br>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaTopic<br>metadata:<br>  name: my-first-topic<br>  namespace: kafka<br>  labels:<br>    strimzi.io/cluster: my-kafka-cluster<br>spec:<br>  partitions: 3<br>  replicas: 3<br>  config:<br>    retention.ms: 259200000  # 3 days<br>    segment.bytes: 1073741824</pre><p>Apply and verify:</p><pre>kubectl apply -f kafka-topic.yaml<br>kubectl get kafkatopics -n kafka</pre><p><strong>Test the Cluster</strong></p><p>Verify the cluster works by producing and consuming messages:</p><pre># Start a producer pod<br>kubectl run kafka-producer -n kafka --rm -it \<br>  --image=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0 \<br>  --restart=Never \<br>  -- bin/kafka-console-producer.sh \<br>  --bootstrap-server my-kafka-cluster-kafka-bootstrap:9092 \<br>  --topic my-first-topic</pre><pre># In another terminal, start a consumer<br>kubectl run kafka-consumer -n kafka --rm -it \<br>  --image=quay.io/strimzi/kafka:0.44.0-kafka-3.8.0 \<br>  --restart=Never \<br>  -- bin/kafka-console-consumer.sh \<br>  --bootstrap-server my-kafka-cluster-kafka-bootstrap:9092 \<br>  --topic my-first-topic \<br>  --from-beginning</pre><p>Type messages in the producer terminal and see them appear in the consumer terminal.</p><h3><strong>Conclusion</strong></h3><p>You now have a Kafka cluster running on Kubernetes with:</p><ul><li>Modern KRaft consensus (no ZooKeeper)</li><li>Separated controllers and brokers</li><li>High availability with 3 replicas</li><li>Optimized configuration for production workloads</li></ul><h3>Additional Resources</h3><ul><li><a href="https://strimzi.io/documentation/"><strong>Strimzi documentaion</strong></a></li><li><a href="https://www.youtube.com/watch?v=B7CwU_tNYIE"><strong>Kafka Crash Course — Hands-On Project</strong></a></li></ul><p>#Kafka #Kubernetes #Strimzi #DevOps #DataEngineering #CloudNative</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644db3427332" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy Production MongoDB on Kubernetes with Percona Operator: Backups, Monitoring, and…]]></title>
            <link>https://medium.com/@abdelrahmanelshahat00/how-to-deploy-production-mongodb-on-kubernetes-with-percona-operator-backups-monitoring-and-c4af1ebd21a4?source=rss-c1e997473fea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4af1ebd21a4</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Abdelrahman ElShahat]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 22:21:17 GMT</pubDate>
            <atom:updated>2025-10-16T08:27:18.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Deploy Production MongoDB on Kubernetes with Percona Operator: Backups, Monitoring, and Security Included</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a-Ri2EfqhrD2cj71.png" /><figcaption>MongoDB in Kubernetes</figcaption></figure><h3>Introduction</h3><p>Deploying MongoDB in production on Kubernetes requires careful consideration of storage, high availability, backups, monitoring, and security. In this comprehensive guide, I’ll walk you through deploying a production-grade MongoDB cluster using the Percona Operator for MongoDB, complete with automated backups to AWS S3, Prometheus monitoring, and proper security configurations.</p><p>By the end of this tutorial, you’ll have a fully functional MongoDB replica set with:</p><ul><li>Persistent storage using AWS EBS</li><li>Automated daily and weekly backups to S3</li><li>Prometheus metrics integration with Grafana dashboards</li><li>TLS security and proper user management</li><li>Production-ready high availability configuration</li></ul><h3>Prerequisites</h3><p>Before we begin, ensure you have:</p><ul><li>A running Kubernetes cluster (EKS, GKE, or any Kubernetes 1.21+)</li><li>kubectl configured to access your cluster</li><li>Helm 3.x installed</li><li>AWS account with S3 access (for backups)</li><li>Basic understanding of Kubernetes concepts</li></ul><h3>Architecture Overview</h3><p>Our setup consists of:</p><ul><li><strong>3-node MongoDB replica set</strong> for high availability</li><li><strong>AWS EBS persistent volumes</strong> for data storage</li><li><strong>MongoDB Exporter sidecar</strong> for metrics collection</li><li><strong>Automated backup jobs</strong> to AWS S3</li><li><strong>Prometheus &amp; Grafana</strong> for monitoring</li></ul><h3>Step 1: Storage Class and Persistent Volume</h3><p>The foundation of any stateful application on Kubernetes is proper storage configuration. We’ll use AWS EBS with encryption enabled and a retain policy to prevent accidental data loss.</p><p>Create storageClass.yaml:</p><pre>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: percona-mongo-ebs<br>provisioner: ebs.csi.aws.com<br>parameters:<br>  type: gp3<br>  encrypted: &quot;true&quot;<br>reclaimPolicy: Retain<br>volumeBindingMode: WaitForFirstConsumer<br>allowVolumeExpansion: true</pre><p><strong>Key configuration choices:</strong></p><ul><li><strong>reclaimPolicy: Retain</strong>: Prevents automatic deletion of volumes when PVCs are deleted</li><li><strong>encrypted: &quot;true&quot;</strong>: Ensures data at rest encryption</li><li><strong>volumeBindingMode: WaitForFirstConsumer</strong>: Delays volume binding until a pod is scheduled, ensuring proper availability zone placement</li><li><strong>allowVolumeExpansion: true</strong>: Enables storage expansion without downtime</li></ul><p>Apply the storage configuration:</p><pre>kubectl apply -f storageClass.yaml</pre><h3>Step 2: Database Users Configuration</h3><p>MongoDB requires several system users for different operational purposes. We’ll store these credentials securely in Kubernetes secrets using base64 encoding.</p><p>Create users.yaml:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: internal-&lt;user-db-name&gt;-users<br>  namespace: mongodb<br>type: Opaque<br>data:<br>  # Cluster Administration<br>  MONGODB_CLUSTER_ADMIN_USER: Y2x1c3RlckFkbWlu<br>  MONGODB_CLUSTER_ADMIN_PASSWORD: Y2x1c3RlclBhc3N3b3Jk<br>  <br>  # Monitoring User (for metrics exporter)<br>  MONGODB_CLUSTER_MONITOR_USER: Y2x1c3Rlck1vbml0b3I=<br>  MONGODB_CLUSTER_MONITOR_PASSWORD: bW9uaXRvclBhc3N3b3Jk<br>  <br>  # User Administration<br>  MONGODB_USER_ADMIN_USER: dXNlckFkbWlu<br>  MONGODB_USER_ADMIN_PASSWORD: dXNlclBhc3N3b3Jk<br>  <br>  # Backup User<br>  MONGODB_BACKUP_USER: YmFja3VwVXNlcg==<br>  MONGODB_BACKUP_PASSWORD: YmFja3VwUGFzc3dvcmQ=<br>  <br>  # Database Administration<br>  MONGODB_DATABASE_ADMIN_USER: ZGF0YWJhc2VBZG1pbg==<br>  MONGODB_DATABASE_ADMIN_PASSWORD: ZGF0YWJhc2VQYXNzd29yZA==<br>  <br>  # Application User<br>  TESTDATA_ADMIN_PASSWORD: ZGF0YVBhc3N3b3Jk</pre><p><strong>Important:</strong> These are example credentials. In production, generate strong passwords and encode them:</p><pre>echo -n &#39;your-strong-password&#39; | base64</pre><p>Create the namespace and apply the secret:</p><pre>kubectl create namespace mongodb<br>kubectl apply -f users.yaml</pre><h3>Step 3: AWS IAM User for Backups</h3><p>For S3 backups, we need AWS credentials. Create an IAM user with S3 permissions and store the credentials in a Kubernetes secret.</p><p>Create aws_backup_iam_user.yaml:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: backup-user<br>  namespace: mongodb<br>type: Opaque<br>data:<br>  AWS_ACCESS_KEY_ID: &lt;base64-encoded-access-key&gt;<br>  AWS_SECRET_ACCESS_KEY: &lt;base64-encoded-secret-key&gt;</pre><p><strong>AWS IAM Policy for the backup user:</strong></p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:ListBucket&quot;,<br>        &quot;s3:GetBucketLocation&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::database-backups-1760441888&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:PutObject&quot;,<br>        &quot;s3:GetObject&quot;,<br>        &quot;s3:DeleteObject&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::database-backups-1760441888/*&quot;<br>    }<br>  ]<br>}</pre><p>Apply the secret:</p><pre>kubectl apply -f aws_backup_iam_user.yaml</pre><h3>Step 4: Installing Percona Operator</h3><p>Install the Percona Operator for MongoDB using Helm:</p><pre># Add Percona Helm repository<br>helm repo add percona https://percona.github.io/percona-helm-charts/<br>helm repo update</pre><pre># Install the operator<br>helm install percona-operator percona/psmdb-operator \<br>  --namespace mongodb \<br>  --create-namespace</pre><p>Verify the operator is running:</p><pre>kubectl get pods -n mongodb</pre><h3>Step 5: Customizing the Operator with Helm Values</h3><p>Now comes the core configuration. We’ll create a comprehensive values.yaml file that configures all aspects of our MongoDB deployment.</p><h3>5.1 Name Override and Full Name Override</h3><pre>nameOverride: &lt;db-name&gt;<br>fullnameOverride: &lt;db-name&gt;</pre><p>These settings control the naming of resources. Setting both ensures consistent, predictable resource names like &lt;db-name&gt;-rs0-0 instead of the default verbose names.</p><h3>5.2 Unsafe Flags</h3><pre>unsafeFlags:<br>  tls: false<br>  replsetSize: false<br>  mongosSize: false<br>  terminationGracePeriod: false<br>  backupIfUnhealthy: false</pre><p><strong>Understanding unsafe flags:</strong></p><ul><li><strong>tls: false</strong>: Allows TLS configuration changes. Set to false to enable TLS modifications</li><li><strong>replsetSize: false</strong>: disable changing replica set size</li><li><strong>mongosSize: false</strong>: Controls mongos scaling (not needed for replica sets)</li><li><strong>backupIfUnhealthy: false</strong>: Prevents backups when cluster is unhealthy (good practice)</li></ul><h3>5.3 TLS Configuration</h3><pre>tls:<br>  mode: preferTLS<br>  certManager:<br>    issuer: selfsigned-issuer<br>    issuerKind: Issuer</pre><p>We use preferTLS mode, which accepts both TLS and non-TLS connections. This is useful during migration or for internal services. For strict security, use requireTLS.</p><p><strong>The operator automatically handles all TLS certificate generation and management. You don’t need to configure cert-manager or create any issuers manually .</strong></p><h3>5.4 Secrets Reference</h3><pre>secrets:<br>  users: internal-&lt;db-name&gt;-users</pre><p>This references the user secret we created earlier, allowing the operator to manage MongoDB users.</p><h3>5.5 Replica Set Configuration</h3><pre>replsets:<br>  rs0:<br>    name: rs0<br>    size: 3<br>    <br>    livenessProbe:<br>      failureThreshold: 6<br>      initialDelaySeconds: 120<br>      periodSeconds: 30<br>      timeoutSeconds: 30<br>    <br>    readinessProbe:<br>      failureThreshold: 10<br>      initialDelaySeconds: 30<br>      periodSeconds: 10<br>      successThreshold: 1<br>      timeoutSeconds: 30</pre><p><strong>Key decisions:</strong></p><ul><li><strong>size: 3</strong>: Provides fault tolerance (can survive 1 node failure)</li><li><strong>initialDelaySeconds: 120</strong>: Gives MongoDB time to start before health checks</li><li><strong>failureThreshold: 6</strong>: Prevents premature pod restarts during normal operations</li></ul><p><strong>Storage engine configuration:</strong></p><pre>storage:<br>      engine: wiredTiger<br>      wiredTiger:<br>        engineConfig:<br>          cacheSizeRatio: 0.5<br>          directoryForIndexes: false<br>          journalCompressor: snappy<br>        collectionConfig:<br>          blockCompressor: snappy<br>        indexConfig:<br>          prefixCompression: true</pre><ul><li><strong>cacheSizeRatio: 0.5</strong>: Uses 50% of available RAM for cache</li><li><strong>journalCompressor: snappy</strong>: Fast compression for WAL</li><li><strong>blockCompressor: snappy</strong>: Balances compression ratio with performance</li></ul><p>You can adjust <strong>Storage engine configuration </strong>based on your database performance</p><p><strong>Volume specification:</strong></p><pre>volumeSpec:<br>      pvc:<br>        storageClassName: percona-mongo-ebs<br>        accessModes: [&quot;ReadWriteOnce&quot;]<br>        resources:<br>          requests:<br>            storage: &lt; db-size&gt;</pre><p>Adjust storage size based on your data requirements. Start conservative and use allowVolumeExpansion to grow later.</p><h3>5.6 MongoDB Exporter vs PMM Client</h3><p>The Percona Operator supports two monitoring solutions:</p><ul><li><strong>PMM (Percona Monitoring and Management)</strong>: Full-featured monitoring platform</li><li><strong>MongoDB Exporter</strong>: Lightweight Prometheus exporter</li></ul><p><strong>Why I chose MongoDB Exporter:</strong></p><ol><li><strong>Simplicity</strong>: Integrates directly with existing Prometheus/Grafana stack</li><li><strong>Resource efficiency</strong>: Lighter weight than full PMM</li><li><strong>Flexibility</strong>: Works with any Prometheus setup</li><li><strong>Open source</strong>: No vendor lock-in</li></ol><p><strong>MongoDB Exporter sidecar configuration:</strong></p><pre>sidecars:<br>    - image: percona/mongodb_exporter:0.36<br>      name: metrics<br>      env:<br>      - name: EXPORTER_USER<br>        valueFrom:<br>          secretKeyRef:<br>            name: internal-my-db-users<br>            key: MONGODB_CLUSTER_MONITOR_USER<br>      - name: EXPORTER_PASS<br>        valueFrom:<br>          secretKeyRef:<br>            name: internal-my-db-users<br>            key: MONGODB_CLUSTER_MONITOR_PASSWORD<br>      - name: POD_IP<br>        valueFrom:<br>          fieldRef:<br>            fieldPath: status.podIP<br>      - name: MONGODB_URI<br>        value: &quot;mongodb://$(EXPORTER_USER):$(EXPORTER_PASS)@localhost:27017/?directConnection=true&quot;<br>      volumeMounts:<br>      - name: ssl<br>        mountPath: /etc/mongodb-ssl<br>        readOnly: true<br>      args:<br>        - &quot;--discovering-mode&quot;<br>        - &quot;--compatible-mode&quot;<br>        - &quot;--collect-all&quot;<br>        - &quot;--log.level=info&quot;<br>        - &quot;--mongodb.uri=$(MONGODB_URI)&quot;</pre><p><strong>Exporter arguments explained:</strong></p><ul><li><strong>--discovering-mode</strong>: Automatically discovers databases and collections</li><li><strong>--compatible-mode</strong>: Ensures compatibility with newer MongoDB versions</li><li><strong>--collect-all</strong>: Gathers comprehensive metrics</li><li><strong>directConnection=true</strong>: Connects to specific replica set member</li></ul><p>If you prefer PMM, configure it like this:</p><pre>pmm:<br>  enabled: true<br>  image:<br>    repository: percona/pmm-client<br>    tag: 3.4.0<br>  serverHost: monitoring-service.monitoring.svc.cluster.local:8443</pre><h3>5.7 Application Users and Database Permissions</h3><pre>users:<br>- name: testdata-admin<br>  db: my-database<br>  passwordSecretRef:<br>    name: internal-my-db-users<br>    key: TESTDATA_ADMIN_PASSWORD<br>  roles:<br>    - name: dbOwner<br>      db: my-database<br>    - name: readWrite<br>      db: my-database</pre><p>This creates an application user with full access to my-database. The operator automatically:</p><ol><li>Creates the database if it doesn’t exist</li><li>Creates the user with specified roles</li><li>Manages password updates from the secret</li></ol><p><strong>Common role combinations:</strong></p><ul><li><strong>Development</strong>: dbOwner (full database control)</li><li><strong>Application</strong>: readWrite (data access only)</li><li><strong>Analytics</strong>: read (read-only access)</li><li><strong>Admin</strong>: dbAdminAnyDatabase, readWriteAnyDatabase</li></ul><h3>5.8 Configuring Backups and Jobs</h3><pre>backup:<br>  enabled: true<br>  image:<br>    repository: percona/percona-backup-mongodb<br>    tag: 2.9.1<br>  <br>  storages:<br>    s3-north-1:<br>      main: true<br>      type: s3<br>      s3:<br>        bucket: database-backups-1760441888<br>        credentialsSecret: backup-user<br>        region: us-east-1<br>  <br>  pitr:<br>    enabled: false<br>    oplogOnly: false<br>  <br>  tasks:<br>  - name: daily-s3-north-1-backup<br>    enabled: true<br>    schedule: &quot;0 0 * * *&quot;<br>    keep: 7<br>    storageName: s3-north-1<br>    compressionType: gzip<br>  <br>  - name: weekly-s3-north-1-backup<br>    enabled: true<br>    schedule: &quot;0 1 * * 0&quot;<br>    keep: 4<br>    storageName: s3-north-1<br>    compressionType: gzip</pre><p><strong>Backup strategy breakdown:</strong></p><p><strong>Daily backups:</strong></p><ul><li><strong>Schedule</strong>: 0 0 * * * (midnight daily)</li><li><strong>Retention</strong>: 7 days (one week of daily recovery points)</li><li><strong>Compression</strong>: gzip (good balance of speed and size)</li></ul><p><strong>Weekly backups:</strong></p><ul><li><strong>Schedule</strong>: 0 1 * * 0 (1 AM every Sunday)</li><li><strong>Retention</strong>: 4 weeks (one month of weekly recovery points)</li><li><strong>Use case</strong>: Long-term retention and compliance</li></ul><p><strong>Point-in-Time Recovery (PITR):</strong></p><pre>pitr:<br>    enabled: false<br>    oplogOnly: false</pre><p>PITR is disabled to reduce storage costs and complexity. Enable it when you need to restore to any specific moment:</p><pre>pitr:<br>    enabled: true<br>    oplogOnly: false<br>    oplogSpanMin: 10<br>    compressionType: gzip</pre><h3>Step 6: Deploying MongoDB</h3><p>Save all the configuration in values.yaml and deploy:</p><pre>helm install &lt;db-name&gt; percona/psmdb-db \<br>  --namespace mongodb \<br>  --values values.yaml</pre><p>Monitor the deployment:</p><pre># Watch pods come up<br>kubectl get pods -n mongodb -w</pre><pre># Check operator logs<br>kubectl logs -n mongodb -l app.kubernetes.io/name=psmdb-operator</pre><pre># Verify replica set status<br>kubectl exec -n mongodb my-db-rs0-0 -- mongosh --eval &quot;rs.status()&quot;</pre><h3>Step 7: Deploying Prometheus Stack</h3><p>Install the kube-prometheus-stack for comprehensive Kubernetes monitoring:</p><pre>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts<br>helm repo update</pre><pre>helm install monitoring prometheus-community/kube-prometheus-stack \<br>  --namespace monitoring \<br>  --create-namespace \<br>  --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false</pre><p><strong>Important flag:</strong> serviceMonitorSelectorNilUsesHelmValues=false allows Prometheus to discover ServiceMonitors in all namespaces.</p><h3>Step 8: Applying Metric Service for Prometheus Scraping</h3><p>Create metric-service.yaml to expose MongoDB metrics to Prometheus:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: psmdb-metrics<br>  namespace: mongodb<br>  labels:<br>    app: psmdb-metrics-db<br>  annotations:<br>    prometheus.io/path: /metrics<br>    prometheus.io/port: &#39;9216&#39;<br>    prometheus.io/scrape: &#39;true&#39;<br>spec:<br>  ports:<br>  - name: http-metrics<br>    port: 9216<br>    targetPort: 9216<br>    protocol: TCP<br>  selector:<br>    app.kubernetes.io/instance: my-db<br>    app.kubernetes.io/name: percona-server-mongodb<br>---<br>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  name: psmdb-metrics-servicemonitor<br>  namespace: monitoring<br>  labels:<br>    release: monitoring<br>spec:<br>  namespaceSelector:<br>    matchNames:<br>      - mongodb<br>  selector:<br>    matchLabels:<br>      app: psmdb-metrics-db<br>  endpoints:<br>  - port: http-metrics<br>    interval: 15s</pre><p><strong>How this works:</strong></p><ol><li><strong>Service</strong>: Exposes port 9216 from the MongoDB Exporter sidecar</li><li><strong>ServiceMonitor</strong>: Tells Prometheus where to scrape metrics</li><li><strong>Selector</strong>: Matches our MongoDB pods using labels</li><li><strong>Interval</strong>: Scrapes metrics every 15 seconds</li></ol><p>Apply the configuration:</p><pre>kubectl apply -f metric-service.yaml</pre><p>Verify Prometheus is scraping metrics:</p><pre># Port-forward to Prometheus<br>kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090:9090</pre><pre># Visit <a href="http://localhost:9090/">http://localhost:9090</a> and search for &quot;mongodb_&quot; metrics</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65l5fTB7DA4HMkxAJuraVA.png" /><figcaption>mongodb-metrics health on Prometheus</figcaption></figure><h3>Step 9: MongoDB Grafana Dashboard</h3><p>Access Grafana and import the official MongoDB dashboard:</p><pre># Get Grafana admin password<br>kubectl get secret -n monitoring monitoring-grafana -o jsonpath=&quot;{.data.admin-password}&quot; | base64 -d</pre><pre># Port-forward to Grafana<br>kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80</pre><p>Visit http://localhost:3000 and login with:</p><ul><li>Username: admin</li><li>Password: (from the command above)</li></ul><p><strong>Import MongoDB dashboard:</strong></p><ol><li>Click <strong>+</strong> → <strong>Import</strong></li><li>Enter dashboard ID: <strong>7353</strong> (Percona MongoDB) or use custom dashboard based on the same ID , the file located in <a href="https://github.com/AbdelrahmanElshahat/percona-mongodb-operator">Github</a></li><li>Select your Prometheus datasource</li><li>Click <strong>Import</strong></li></ol><p><strong>Key metrics to monitor:</strong></p><ul><li><strong>Operations per second</strong>: Query performance</li><li><strong>Connections</strong>: Connection pool health</li><li><strong>Replication lag</strong>: Data consistency across replicas</li><li><strong>Cache utilization</strong>: Memory efficiency</li><li><strong>Disk I/O</strong>: Storage performance</li><li><strong>Oplog window</strong>: Backup and replication health</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQXS2zB1WD_pQobZIoPGKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCVppH030r150iz3_n0jjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t67iWodDFy-1YuoagDTfUA.png" /><figcaption>Mongodb Dashboard on Grafana</figcaption></figure><h3>Test Backup Manually</h3><pre># Trigger manual backup<br>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: psmdb.percona.com/v1<br>kind: PerconaServerMongoDBBackup<br>metadata:<br>  name: manual-backup-$(date +%Y%m%d-%H%M%S)<br>  namespace: mongodb<br>spec:<br>  clusterName: &lt;db-name&gt;<br>  storageName: s3-north-1<br>EOF</pre><pre># Check backup status<br>kubectl get psmdb-backup -n mongodb</pre><h3>Verify Metrics Collection</h3><pre># Check MongoDB Exporter logs<br>kubectl logs -n mongodb &lt;db-name&gt;-rs0-0 -c metrics</pre><pre># Query Prometheus for MongoDB metrics<br>curl <a href="http://localhost:9090/api/v1/query?query=mongodb_up">http://localhost:9090/api/v1/query?query=mongodb_up</a></pre><h3>Test High Availability</h3><pre># Delete primary pod<br>kubectl delete pod -n mongodb &lt;db-name&gt;-rs0-0</pre><pre># Watch failover<br>kubectl exec -n mongodb my-db-rs0-1 -- mongosh --eval &quot;rs.status()&quot;</pre><pre># Verify application continues working<br>kubectl exec -n mongodb my-db-rs0-1 -- mongosh my-database --eval &quot;db.test.find()&quot;</pre><h3>Monitoring and Alerting</h3><p>Configure Prometheus alerts:</p><pre>apiVersion: monitoring.coreos.com/v1<br>kind: PrometheusRule<br>metadata:<br>  name: mongodb-alerts<br>  namespace: monitoring<br>spec:<br>  groups:<br>  - name: mongodb.rules<br>    rules:<br>      - alert: MongoDBDown<br>        expr: |<br>          # No mongodb_up samples in the last 5 minutes =&gt; likely down / missing scrape<br>          (count_over_time(mongodb_up[5m]) == 0)<br>          or<br>          # All observed mongodb_up series are 0 (only evaluate if any series exist)<br>          ((count(mongodb_up) &gt; 0) and (max without(job) (mongodb_up) == 0))<br>        for: 0m<br>        labels:<br>          severity: critical<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;MongoDB {{ $labels.service_name }} on {{ $labels.node_name }} is down.&quot;<br>          summary: &quot;MongoDB down ({{ $labels.service_name }})&quot;<br><br>      - alert: mongodb_replset_no_primary<br>        expr: avg(mongodb_ss_repl_isWritablePrimary) by(cluster,rs_nm) == 0<br>        for: 0m<br>        labels:<br>          severity: critical<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;MongoDB has NO Primary for ReplSet {{ $labels.rs_nm }} in {{ $labels.cluster }} cluster..&quot;<br>          summary: &quot;MongoDB has NO Primary for ReplSet ({{ $labels.rs_nm }})&quot;<br>      <br>      - alert: mongodb_replset_primary_changed<br>        expr: min by (set)(changes(mongodb_mongod_replset_my_state[10m]) &gt; 0)<br>        for: 0m<br>        labels:<br>          severity: warning<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;Replica set {{ $labels.set }} has undergone a primary change in the last 10 minutes&quot;<br>          summary: &quot;Primary changed in {{ $labels.set }}&quot;<br><br>      - alert: mongodb_unusual_state<br>        expr: group(mongodb_rs_members_state != 1 and mongodb_rs_members_state != 2 and mongodb_rs_members_state != 7 and mongodb_rs_members_state != 8) by (cluster,member_idx,member_state,rs_nm)<br>        for: 0m<br>        labels:<br>          severity: warning<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;MongoDB replicaSet member ({{ $labels.member_idx }}) is in \&quot;{{ $labels.member_state }}\&quot; state for cluster {{ $labels.cluster }}.&quot;<br>          summary: &quot;MongoDB replicaSet member is in unusual state for ({{ $labels.member_idx }})&quot;<br><br>      - alert: mongodb_high_memory_usage<br>        expr: |<br>          (<br>            sum by (node_name, service_name) (mongodb_ss_mem_resident * 1024 * 1024)<br>            /<br>            clamp_min(sum by (node_name) (node_memory_MemTotal_bytes), 1)<br>          ) * 100 &gt; 80<br>        for: 0m<br>        labels:<br>          severity: warning<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;{{ $value }}% of memory (more than 80%) is used by {{ $labels.service_name }} on {{ $labels.node_name }}.&quot;<br>          summary: &quot;MongoDB high memory usage ({{ $labels.service_name }})&quot;<br><br>      - alert: mongodb_restarted<br>        expr: |<br>          # Prefer detecting restarts by observing a change in the start time<br>          (changes(mongodb_instance_start_time_seconds[5m]) &gt; 0)<br>          or<br>          # Fallback when start_time metric is not present: very low uptime observed<br>          (<br>            count(mongodb_instance_start_time_seconds) == 0<br>            and<br>            mongodb_instance_uptime_seconds &lt; 300<br>          )<br>        for: 1m<br>        labels:<br>          severity: warning<br>          namespace: monitoring<br>        annotations:<br>          description: &quot;MongoDB {{ $labels.service_name }} on {{ $labels.node_name }} was restarted recently.&quot;<br>          summary: &quot;MongoDB restarted ({{ $labels.service_name }})&quot;</pre><h3>Backup Verification</h3><p>Regularly test restore procedures:</p><pre># List backups<br>kubectl get psmdb-backup -n mongodb</pre><pre># Restore to test cluster<br>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: psmdb.percona.com/v1<br>kind: PerconaServerMongoDBRestore<br>metadata:<br>  name: restore-test-$(date +%Y%m%d)<br>  namespace: mongodb<br>spec:<br>  clusterName: &lt;db-name&gt;<br>  backupName: &lt;backup-name&gt;<br>EOF</pre><h3>Troubleshooting Common Issues</h3><h3>Pods Not Starting</h3><pre># Check events<br>kubectl describe pod -n mongodb &lt;db-name&gt;-rs0-0</pre><pre># Check operator logs<br>kubectl logs -n mongodb -l app.kubernetes.io/name=psmdb-operator --tail=100</pre><pre># Common issues:<br># - Storage class not found<br># - Insufficient resources<br># - Image pull errors</pre><h3>Backup Failures</h3><pre># Check backup pod logs<br>kubectl logs -n mongodb -l job-name=backup-&lt;job-name&gt;</pre><pre># Verify AWS credentials<br>kubectl get secret -n mongodb backup-user -o yaml</pre><pre># Common issues:<br># - Invalid AWS credentials<br># - S3 bucket permissions<br># - Network connectivity to S3</pre><h3>Metrics Not Appearing in Prometheus</h3><pre># Verify exporter is running<br>kubectl get pods -n mongodb -o wide</pre><pre># Check exporter metrics endpoint<br>kubectl port-forward -n mongodb my-db-rs0-0 9216:9216<br>curl <a href="http://localhost:9216/metrics">http://localhost:9216/metrics</a></pre><pre># Verify ServiceMonitor<br>kubectl get servicemonitor -n monitoring psmdb-metrics-servicemonitor</pre><pre># Check Prometheus targets<br># Visit Prometheus UI → Status → Targets</pre><h3>Replication Issues</h3><pre># Check replica set configuration<br>kubectl exec -n mongodb &lt;db-name&gt;-rs0-0 -- mongosh --eval &quot;rs.conf()&quot;</pre><pre># Check replication status<br>kubectl exec -n mongodb my-db-rs0-0 -- mongosh --eval &quot;rs.status()&quot;</pre><pre># Check oplog size<br>kubectl exec -n mongodb my-db-rs0-0 -- mongosh --eval &quot;db.getReplicationInfo()&quot;</pre><h3>Cleanup</h3><p>To remove the deployment:</p><pre># Delete MongoDB cluster<br>helm uninstall &lt;db-name&gt; -n mongodb</pre><pre># Delete operator<br>helm uninstall percona-operator -n mongodb</pre><pre># Delete monitoring stack (optional)<br>helm uninstall monitoring -n monitoring</pre><pre># Delete namespaces<br>kubectl delete namespace mongodb monitoring</pre><h3>Conclusion</h3><p>You now have a production-grade MongoDB deployment on Kubernetes with:</p><ul><li>High availability with 3-node replica set</li><li>Encrypted persistent storage with AWS EBS</li><li>Automated daily and weekly backups to S3</li><li>Comprehensive monitoring with Prometheus and Grafana</li><li>Secure TLS communication</li><li>Proper user management and role-based access control</li></ul><p>This setup provides a solid foundation for running MongoDB in production. Remember to:</p><ul><li>Regularly test backups and restore procedures</li><li>Monitor metrics and set up alerts</li><li>Keep operators and MongoDB versions updated</li><li>Review security policies quarterly</li><li>Document your specific customizations</li></ul><p>The Percona Operator handles the heavy lifting of MongoDB management, allowing you to focus on your application while maintaining enterprise-grade database infrastructure.</p><h3>Quick Start Repository</h3><p>Want to get started quickly? All the configuration files from this tutorial are available in a ready-to-use repository:</p><p><a href="https://github.com/AbdelrahmanElshahat/percona-mongodb-operator"><strong>percona-mongodb-operator</strong></a></p><p>This repository includes:</p><ul><li>All YAML configuration files</li><li>Complete values.yaml for Helm deployment</li><li>Step-by-step deployment scripts</li><li>Pre-configured monitoring setup</li><li>Ready-to-use backup configurations</li></ul><h3>Additional Resources</h3><ul><li><a href="https://docs.percona.com/percona-operator-for-mongodb/">Percona Operator Documentation</a></li><li><a href="https://docs.mongodb.com/manual/administration/production-notes/">MongoDB Production Notes</a></li><li><a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Kubernetes Storage Best Practices</a></li><li><a href="https://github.com/percona/mongodb_exporter">Prometheus MongoDB Exporter</a></li><li><a href="https://grafana.com/grafana/dashboards/">Grafana Dashboards</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4af1ebd21a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>