<?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 Qua Zi Xian on Medium]]></title>
        <description><![CDATA[Stories by Qua Zi Xian on Medium]]></description>
        <link>https://medium.com/@ZiXianZeroX?source=rss-3f5cd3b0e6ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4YgroNUa0z-GYs14hR-9ag.jpeg</url>
            <title>Stories by Qua Zi Xian on Medium</title>
            <link>https://medium.com/@ZiXianZeroX?source=rss-3f5cd3b0e6ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:58:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ZiXianZeroX/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[Set up 3-Node Compact OpenShift Cluster on vSphere VMs using Agent-Based Installer with External…]]></title>
            <link>https://medium.com/@ZiXianZeroX/set-up-3-node-compact-openshift-cluster-on-vsphere-vms-using-agent-based-installer-with-external-569e66ca1052?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/569e66ca1052</guid>
            <category><![CDATA[openshift-4]]></category>
            <category><![CDATA[agent-based-installation]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[red-hat-openshift]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 05:19:39 GMT</pubDate>
            <atom:updated>2026-09-05T05:19:39.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Set up 3-Node Compact OpenShift Cluster on vSphere VMs using Agent-Based Installer with External Load Balancer</h3><h3>Pre-amble</h3><p>This post is a technical sharing of a problem I encountered when setting up an OpenShift cluster at work and the workaround/hack/fix to make it work.</p><p>I will also share as best as I can my journey with Claude Pro to arrive at this discovery.</p><h3>Architecture</h3><figure><img alt="Intended cluster architecture" src="https://cdn-images-1.medium.com/max/928/1*RiRMyvoHzVloN6rRnT5jtA.png" /></figure><ul><li>3 vSphere VM nodes functioning as master and worker nodes (a.k.a compact nodes)</li><li>Network VLAN_702 (IP range: 10.70.2.0/24)</li><li>Node IPs: 10.70.2.3 to 10.70.2.5</li><li>API Server VIP 10.70.2.250 and Ingress VIP 10.70.2.251</li><li>vCenter platform for built-in vCenter CSI driver on cluster creation</li></ul><h3>Setup Summary</h3><p>This will be a redacted writeup covering only high-level and critical steps. Specific details and configuration setup, use OpenShift official documentation and openshift-install explain command to discover. The fields are all decision points you have to make.</p><p>Run commands from a bastion/bootstrap server with network access to the cluster network, vCenter and mirror registry (if applicable/disconnected environment).</p><ol><li>Prepare RHCOS ISO file renamed as coreos cache in ~/.cache/agent/image_cache/coreos-x86_64.iso (verify actual name in your own machine after 1 agent create image run), agent-config and install config YAML files backed up in a separate folder on the bastion machine.</li><li>Prepare a new folder for generating ISO image. Copy over agent-config.yaml and install-config.yaml . Navigate to the new folder.</li><li>Run openshift-install agent create image --dir $PWD from <strong>inside the new folder</strong>.</li><li>Boot the 3 nodes using the generated agent.x86_64.iso file.</li><li>Run openshift-install agent wait-for bootstrap-complete --dir $PWD --log-level DEBUG . Once successfully completed, run openshift-install agent wait-for install-complete --dir $PWD --log-level DEBUG .</li></ol><h3>Problem Encountered</h3><p>Rendezvous node says cluster install stopped with reason “Insufficient”.</p><p>A check using openshift-install agent wait-for bootstrap-complete --dir $PWD --log-level DEBUG shows warning about API server and Ingress VIPs being in use (by the external load balancers).</p><p>SSH into rendezvous node and inspecting assisted-installer logs shows a large JSON object with validation gate for VIP not in use <strong>failed</strong>.</p><h3>Fix</h3><p>Instead of straightaway using openshift-install agent create image , break into 2–3 parts.</p><ol><li>openshift-install agent create cluster-manifests --dir $PWD to generate ZTP-style manifests.</li><li>Edit cluster-manifests/agent-install-cluster.yaml to set spec.loadBalancer.type: Usermanaged .</li><li>openshift-install agent create image --dir $PWD to finish ISO creation.</li></ol><p>If you are here for the fix, you can stop reading. Read on if you are interested in the problem-solving and discovery journey I went through.</p><h3>Journey</h3><p>I got stuck without progress for 3 full working days, neglecting all of my other operational work tasks. I had to stop work on this for the next 2 days to meet a promised deadline for another track in the project.</p><p>When I got back to this the next week, I got an insight or spark from what I read in the chat contents already there and somehow things worked out.</p><h4>Disclaimer</h4><p>Claude Pro is my personal subscription. It is not an allowed AI tool in my company (Microsoft Copilot is) and I have no access to it on my work laptop. Nevertheless, for this type of highly-technical troubleshooting requiring no context about organisational knowledge (to heck with the weird rules and standards to comply with the security standards that actually make sense), I find that Anthoripic’s harness does a better job at researching more thoroughly, allowing discovery of creative ideas. While keeping to official sources, it was able to go the off-beat path and dig into source code and any publicly-available developer tools to search for known bug reports.</p><p>Without much ado, let’s go!</p><h4>Stuck</h4><p>I tried the happy path from documentation. Checking the rendzvous node’s console, I saw the messaage at login screen, “Insufficient”.</p><p>The output of openshift-install agent wait-for bootstrap-complete --dir $PWD --log-level DEBUG shows warning that says the specified VIPs are in use.</p><h4><strong>Cause Identification</strong></h4><p>Inital response indicated that this is the built-in behaviour of OpenShift Installer or the Assisted Installer.</p><p>A check into rendezvous node via SSH shows assisted installer logs marking the VIP in use as a failed validation check.</p><p>Looking into the rendezvous node’s cluster install file (cannot remember where, gone after reboot as part of cluster installation) shows that the actual value of load balancer type is OpenShiftClusterManaged .</p><p>This seems off.</p><h4>Checking for difference/gap in configuration</h4><p>I asked Claude to come up with complete setup guide for my use case. It brought up the use of platform.vsphere.loadBalancer.type: UserManaged . This looked like what I needed.</p><p>I was skeptical about it and asked it look up documentation for verification. It came back with findings from OpenShift-Install’s Github repo Golang code. I looked into the documentation and verified it IS VALID. Verified with openshift-install explain installconfig.platform.vsphere and confirmed there is such a field, just that it says it is Tech Preview only.</p><h4>Considering options and hesitations</h4><p>I considered running Tech Preview but rejected it because the cluster is for developers to use and I will not want to recreate cluster just to upgrade OpenShift version.</p><p>Rejected proposal for platform.none: {} as well because I want to use vSphere for CSI driver out of the box without manual setup later.</p><h4>Backtrack: Compare against successful OCP cluster meant to run Multicluster Engine</h4><p>I mentioned to Claude about another OCP cluster I created before without error. Claude asked to check a few things and it sparked a thought to verify the pods in the cluster.</p><p>Ran oc get pods -n openshift-vsphere-infraand found that there are keepalived pods on control plane nodes in that working cluster. I went on to clarify with my network team to confirm that the load balancer request was never processed, so there is no load balancer at all.</p><blockquote>I felt like I was living a lie the whole time since the successful installation of that OCP cluster!</blockquote><h4>Catching on to discrepancy between API change already in GA and OpenShift Installer’s behaviour</h4><p>Claude mentioned that user managed load balancer item has graduated to GA in OpenShift API, but the validation check was never removed in OpenShift Install. I asked if this is baked into some image or in the openshift-install command itself, and the reply was the latter.</p><p>I further probed into how the openshift-install command and assisted installer works. Claude explained that the openshift-install command converts my YAML files into a set of ZTP-style manifests. The latter get baked into the ISO file and are read by the assisted installer.</p><p>Since specifying user-managed load balancer typeis already part of GA OpenShift API, the assisted installer just needs to read the correct load balancer type value during run time. This requires the file contents in the ISO file to be correct.</p><blockquote>I just need a way to right the wrongs of OpenShift Installer before packing things into the ISO file!</blockquote><h4>Finishing touch: Finding the know-how to create this opening</h4><p>Claude generated commands (albeit a bit off) to generate the manifests and inspect for myself. The agent install cluster file really omitted the load balancer type config (defaults to cluster-managed)! Time to add it back in and see how it goes.</p><p>Problem solved!</p><h3>Extra bonus: Claude’s generated blog post draft</h3><p>Leaving it in this post because I found the structure quite good, despite not being exactly what I want. Enjoy the saucy part of the documents that Claude dug up.</p><h3>First attempt: it just hangs at “insufficient”</h3><p>Booting all three nodes off the agent ISO with a standard vSphere platform config (apiVIPs/ingressVIPs set to the F5&#39;s addresses, everything else default) left the rendezvous host stuck reporting hosts as insufficient, with warnings that the API and Ingress VIPs were &quot;already in use.&quot;</p><p><strong>Root cause:</strong> by default, platform.vsphere load balancing is OpenShiftManagedDefault — OpenShift deploys its own keepalived + haproxy static pods on the control-plane nodes, which claim the VIP via VRRP/gratuitous ARP. When the F5 already owns and answers ARP for that exact address, the assisted-service&#39;s network validation sees a live collision and refuses to let the hosts become known. This is a real, documented failure mode, tracked upstream as <a href="https://issues.redhat.com/browse/OCPBUGS-43352">OCPBUGS-43352</a> (&quot;IP collision validation, due to a Proxy ARP request&quot;).</p><p>Two independent devices claiming the same IP on one L2 segment isn’t a soft problem, either — it causes genuine ARP/MAC flapping, nondeterministic per-connection routing, and live connections dying on re-ARP events. The validation isn’t being overly cautious; it’s catching a real unsound network state.</p><p><strong>How to confirm this diagnosis for certain, rather than guess:</strong> query the assisted-service running locally on the rendezvous host directly:</p><pre>CLUSTER_ID=$(curl -s http://&lt;rendezvous-ip&gt;:8090/api/assisted-install/v2/clusters | jq -r &#39;.[0].id&#39;)<br>curl -s http://&lt;rendezvous-ip&gt;:8090/api/assisted-install/v2/clusters/$CLUSTER_ID/hosts \<br>  | jq &#39;.[] | {hostname: .requested_hostname, status, status_info, validations: (.validations_info | fromjson)}&#39;</pre><p>This surfaces exactly which validation is failing per host — don’t rely on the CLI’s terse insufficient message alone.</p><h3>The fix that should work: loadBalancer.type: UserManaged</h3><p>vSphere’s install-config platform block does support telling OpenShift <em>not</em> to run its own keepalived-claimed VIP:</p><pre>platform:<br>  vsphere:<br>    apiVIPs: [10.70.2.250]<br>    ingressVIPs: [10.70.2.251]<br>    loadBalancer:<br>      type: UserManaged</pre><p>This field is real — confirmed straight from the installer’s own Go validation source (pkg/types/vsphere/validation/platform.go), not just documentation. With UserManaged, OpenShift never deploys keepalived to fight over the address; it trusts that whatever&#39;s already answering (the F5) legitimately owns it. apiVIPs/ingressVIPs stay set to the F5&#39;s actual addresses — same values, different meaning: &quot;this is where DNS should point,&quot; not &quot;this is what OpenShift should claim.&quot;</p><h3>The gotcha: it’s Tech Preview</h3><p>Digging into openshift/api history: <a href="https://github.com/openshift/api/pull/1757">PR #1757</a> promoted PlatformLoadBalancer to GA for bare-metal and vSphere at the <em>API type</em> level, targeting OpenShift 4.16. But that&#39;s only half the story — openshift/installer has to independently honor that promotion in its own validation code, and a linked attempt to do exactly that (<a href="https://github.com/openshift/installer/pull/8100">installer#8100</a>) was closed without merging. Whatever the reason, the gate is still live in 4.22.6&#39;s binary, three major versions past the GA target the API-level change implies. Trust your own binary&#39;s behavior over any changelog — run the same create cluster-manifests test against newer openshift-install releases side by side if you want to check whether a given version has actually lifted it:</p><pre>mkdir -p ~/ocp-installers/4.23.0 &amp;&amp; cd ~/ocp-installers/4.23.0<br>curl -sL -o oi.tar.gz &quot;https://mirror.openshift.com/pub/openshift-v4/x86_64/clients/ocp/4.23.0/openshift-install-linux.tar.gz&quot;<br>tar -xzf oi.tar.gz</pre><p><strong>The obvious workaround — </strong><strong>featureSet: TechPreviewNoUpgrade — is not actually free.</strong> It&#39;s a cluster-wide, irreversible FeatureGate, not an installer-only switch:</p><ul><li>Patch (z-stream) upgrades within the same minor version still work.</li><li>Minor-version upgrades are permanently blocked — the cluster-version-operator’s Upgradeable condition fails with FeatureGatesUpgradeable: &quot;TechPreviewNoUpgrade&quot; does not allow updates (<a href="https://access.redhat.com/solutions/7061869">Red Hat KB 7061869</a>).</li><li>It can’t be reverted to Default on a live cluster.</li><li>It’s not scoped to just this one field — the entire Tech Preview bundle for that release comes along.</li><li>A Tech Preview cluster is explicitly unsupported for production per Red Hat policy.</li></ul><p>That’s a real, permanent architectural commitment for one load-balancer config field. Worth ruling out entirely before accepting it.</p><h3>The path considered and rejected: platform: none</h3><p>platform: none sidesteps the whole VIP-ownership question — it tells the installer that DNS and load balancing are already fully external, no keepalived, no VIP fields at all:</p><pre>platform:<br>  none: {}</pre><p>GA today, no Tech Preview, works cleanly with an external F5. <strong>The catch:</strong> the in-box, Red Hat-supported VMware vSphere CSI Driver Operator will never activate. This isn’t a “configure it later” gap — Red Hat’s own documentation states the operator “is supported only on clusters deployed with platform: vsphere in the installation manifest,&quot; and this is confirmed empirically too: a real-world platform: none install on vSphere shows oc get pod -n openshift-cluster-csi-drivers returning nothing. The Infrastructure CR&#39;s platform type is fixed at install time and isn&#39;t a supported day-2 change, so there&#39;s no route back to the built-in operator afterward.</p><p>If vSphere-backed CSI storage is a hard requirement — it was here — platform: none trades one problem for another: VMware&#39;s own separately-maintained CSI/CPI operator becomes the fallback, shifting support responsibility to VMware/Broadcom for that component. Not free either.</p><p><strong>A tempting middle ground that doesn’t actually work here:</strong> give keepalived two <em>different</em> addresses than the F5’s (e.g., .250/.251 for apiVIPs/ingressVIPs, with only api-int pointed at the internal VIP and api/*.apps pointed at the F5). This avoids the IP collision with zero Tech Preview — but only if you have spare IPs. On a tight subnet where nearly every address is already consumed by nodes, bastion, and the two LB VIPs, this simply isn&#39;t available. Getting two more addresses allocated is worth a direct ask before ruling this out.</p><h3>What actually worked: edit the manifest after generation</h3><p>openshift-install&#39;s Tech Preview gate lives entirely in its own client-side validation of install-config.yaml — it fires during manifest generation, before any cluster infrastructure exists, before the ISO is even built. It has nothing to do with any mirrored registry content. The gate is specifically keyed on install-config.yaml containing a loadBalancer field; if that field is simply absent from install-config.yaml, the check never runs at all.</p><p>Separately: the assisted-service that actually drives cluster bring-up doesn’t read install-config.yaml directly. It reads a converted manifest — agent-cluster-install.yaml — that openshift-install writes out during agent create cluster-manifests. <strong>Assisted-service does not re-enforce the installer&#39;s own Tech Preview restriction when consuming that manifest.</strong> So:</p><ol><li>Leave loadBalancer out of install-config.yaml entirely (keep apiVIPs/ingressVIPs set to the F5 addresses — those are always required and never gated).</li><li>Generate manifests normally — this passes cleanly, since there’s no loadBalancer field for the validator to object to.<br>openshift-install --dir ocp-install agent create cluster-manifests</li><li>Edit the generated manifest directly, adding the field assisted-service will actually honor:<br>vi ocp-install/cluster-manifests/agent-cluster-install.yaml</li><li>Proceed to image generation as normal:<br>openshift-install --dir ocp-install agent create image</li><li>The result: UserManaged load balancing behavior, full vSphere CSI (platform: vsphere throughout), no featureSet: TechPreviewNoUpgrade, no cluster-wide upgrade lock. <strong>Caveat, stated plainly:</strong> this works because a client-side speed bump happens to not be mirrored downstream, not because the feature is officially supported this way. There&#39;s no Red Hat documentation endorsing this specific sequence, and future installer versions could easily start re-validating agent-cluster-install.yaml the same way and close this gap. Treat it as a workaround discovered through testing, not a supported pattern — re-verify it against any new installer version before relying on it, and if this is headed to production, it&#39;s worth a support case or RFE with Red Hat rather than standing on an undocumented gap indefinitely.</li></ol><h3>Lessons</h3><ul><li>A “Tech Preview” label on one install-config field doesn’t mean the whole feature is unusable — it means the <em>client-side path</em> your installer version takes to enable it is gated. The underlying cluster-side behavior (what assisted-service and the running cluster actually do) may not enforce the same restriction, and the gap between those two enforcement points is exactly where a workaround like this lives.</li><li>Read the installer’s own validation errors and Go source before trusting docs or blog posts (including this one) — doc pages lag behind binaries, and binaries are what actually run your install.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=569e66ca1052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a “Sandboxed” remote development environment with Coder on Kubernetes]]></title>
            <link>https://medium.com/@ZiXianZeroX/deploying-a-sandboxed-remote-development-environment-with-coder-on-kubernetes-6c134c2dfffa?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c134c2dfffa</guid>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 17:33:41 GMT</pubDate>
            <atom:updated>2026-02-21T17:33:41.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently my work laptop got locked down with security hardening. As a result, I lost access to many essential and productivity tools that I have grown so used to. This was the final push factor that got me to stop procrastinating and start researching into using <strong>Coder</strong> as a way to standardize remote development environment and tools.</p><p>Another benefit for this is the possibility of preparing standardized environments for participants when we conduct internal technical workshops.</p><p>This post walks through the technical process of configuring and deploying <strong>Coder</strong> as the remote development environment platform, plus my thought process and struggles at various parts of the journey.</p><h3>The End State</h3><p>Let’s start with the list of requirements and desired outcome I had in mind. Note that some of them are quite strict and may be unnecessary but more security and less entropy is always welcome, especially when trying to convince security that the environment is well-controlled.</p><ul><li>Coder and workspace running in Kubernetes cluster</li><li>Access to Coder via URL <a href="https://coder.localtest.me:30443/">https://coder.localtest.me:30443</a></li><li>Workspace has Terminal, Visual Studio Code (via Code Server), and Docker for a minimal development environment</li></ul><h3>Tools and Deployment Environment</h3><ul><li>Podman Desktop for for all containerization needs</li><li>KinD cluster as Kubernetes cluster</li></ul><h3>Setting up Coder Platform</h3><p>Key steps:</p><ol><li>Create namespace for Coder, and Postgres for this PoC.</li><li>Create namespace to house all workspaces.</li><li>Set up Postgres database.</li><li>Configure and deploy Coder server.</li><li>Set up ingress solution for Coder server.</li></ol><p>Refer to <a href="https://coder.com/docs/install/kubernetes">official guide</a> for steps 3 and 4.</p><p>Minimal Coder values file.</p><pre># values.yaml<br>coder:<br>  env:<br>    - name: CODER_ACCESS_URL<br>      value: https://coder.localtest.me:30443<br>    - name: CODER_PG_CONNECTION_URL<br>      value: &lt;connection_string&gt;<br>    - name: CODER_OAUTH2_GITHUB_DEFAULT_PROVIDER_ENABLE<br>      value: &quot;false&quot;<br>  serviceAccount:<br>    workspaceNamespaces:<br>      - name: dev-ws<br>  service:<br>    enable: true<br>    type: ClusterIP<br>  certs:<br>    secrets:<br>      - name: localtest-ca-bundle<br>        key: ca-bundle.crt</pre><h3>Preparing Workspace Template</h3><p>Template is essentially a self-contained Terraform code that Coder will apply to provision resources representing a workspace.</p><p>For my setup:</p><ul><li>Kubernetes deployment running container image that has all my required tools</li><li>Persistent volumes to keep certain data across workspace sessions</li><li>Coder agent that runs in the deployment pod and registers the workspace for use</li><li>Code Server app that is published by Coder agent</li></ul><p>My container image is a Debian Slim OS with Docker and Code Server installed.</p><p>Redacted Terraform file.</p><pre># main.tf<br>provider &quot;coder&quot; {<br>  url = &quot;https://coder.localtest.me:30443&quot;<br>}<br><br>provider &quot;kubernetes&quot; {<br>  host                   = &quot;https://kubernetes.default.svc&quot;<br>  cluster_ca_certificate = file(&quot;/var/run/secrets/kubernetes.io/serviceaccount/ca.crt&quot;)<br>  token                  = file(&quot;/var/run/secrets/kubernetes.io/serviceaccount/token&quot;)<br>}<br><br># Data sources<br>data &quot;coder_workspace&quot; &quot;me&quot; {}<br>data &quot;coder_workspace_owner&quot; &quot;me&quot; {}<br><br># Configurable parameters when creating workspace<br>data &quot;coder_parameter&quot; &quot;custom_ca_certificates&quot; {<br>  # Redacted<br>}<br><br># Coder Agent<br>resource &quot;coder_agent&quot; &quot;main&quot; {<br>  # Redacted<br>}<br><br># Coder App for code-server web access<br># Shows up as code-server app in workspace<br>resource &quot;coder_app&quot; &quot;code_server&quot; {<br>  agent_id     = coder_agent.main.id<br>  # Redacted<br>}<br><br># Kubernetes Deployment with code-server and dockerd containers<br>resource &quot;kubernetes_deployment_v1&quot; &quot;coder_workspace&quot; {<br>  count = data.coder_workspace.me.start_count &gt; 0 ? 1 : 0<br>  metadata {<br>    name      = lower(data.coder_workspace.me.name)<br>    namespace = &quot;dev-ws&quot;<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot;      = &quot;coder-workspace&quot;<br>      &quot;app.kubernetes.io/instance&quot;  = lower(data.coder_workspace.me.name)<br>      &quot;coder.io/workspace-id&quot;       = data.coder_workspace.me.id<br>      &quot;coder.io/workspace-name&quot;     = data.coder_workspace.me.name<br>      &quot;coder.io/workspace-owner&quot;    = data.coder_workspace_owner.me.name<br>      &quot;coder.io/workspace-owner-id&quot; = data.coder_workspace_owner.me.id<br>    }<br>  }<br><br>  spec {<br>    replicas = 1<br><br>    strategy {<br>      type = &quot;Recreate&quot;<br>    }<br><br>    selector {<br>      match_labels = {<br>        &quot;app.kubernetes.io/name&quot;     = &quot;coder-workspace&quot;<br>        &quot;app.kubernetes.io/instance&quot; = lower(data.coder_workspace.me.name)<br>      }<br>    }<br><br>    template {<br>      metadata {<br>        labels = {<br>          &quot;app.kubernetes.io/name&quot;     = &quot;coder-workspace&quot;<br>          &quot;app.kubernetes.io/instance&quot; = lower(data.coder_workspace.me.name)<br>        }<br>      }<br><br>      spec {<br>        # code-server container (runs Coder agent)<br>        container {<br>          name              = &quot;code-server&quot;<br><br>          # Coder agent environment variables<br>          env {<br>            name  = &quot;CODER_AGENT_TOKEN&quot;<br>            value = coder_agent.main.token<br>          }<br><br>          env {<br>            name  = &quot;CODER_AGENT_URL&quot;<br>            value = &quot;https://coder.localtest.me:30443&quot;<br>          }<br><br>          env {<br>            name  = &quot;CODER_AGENT_SUBSYSTEM&quot;<br>            value = &quot;envbox&quot;<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Export the template as TAR file and upload to Coder via web UI.</p><pre>tar -cvf mytemplate.tar main.tf</pre><p>Press Build and then Publish on successful build to finish creating a template.</p><h3>Free Home-lab Pitfalls &amp; Learnings</h3><h4>How Coder agent and workspace work</h4><p>Coder runs Terraform using the template’s Terraform code to provision the resources needed to run the workspace.</p><p>The workspace infrastructure runs Coder agent’s init script to</p><ol><li>Set up the agent</li><li>Register itself to Coder server</li><li>Check that all registered apps are alive</li><li>Run any given startup scripts</li></ol><p>If any step fails, the subsequent steps will not run.</p><blockquote>Conclusion: Start up all daemons serving apps’ healthcheck endpoints before starting Coder agent.</blockquote><h4>Pitfall 1: Unable to access Coder through specified port number</h4><p>May not be a problem if you use MetalLB as load balancer in KinD cluster setup.</p><p>If using Envoy Gateway with NodePort Service, EnvoyProxy will map the listener’s port 443 to some random NodePort range.</p><p>To access from the host running KinD cluster, force the NodePort Service (done via EnvoyProxy envoyService patch) to use the port that has mapping to the host (done via KinD cluster config YAML).</p><pre># KinD config<br>nodes:<br>- role: control-plane<br>- role: worker<br>  extraPortMappings:<br>  - containerPort: 30443<br>    hostPort: 30443<br>    listenAddress: &quot;0.0.0.0&quot;<br>    protocol: TCP<br>  kubeadmConfigPatches:<br>  - |<br>    kind: JoinConfiguration<br>    nodeRegistration:<br>      kubeletExtraArgs:<br>        node-labels: &quot;ingress-ready=true&quot;<br><br># EnvoyProxy config<br>spec:<br>  provider:<br>    type: Kubernetes<br>    kubernetes:<br>      envoyService:<br>        type: NodePort<br>        patch: # Needed as Proxy&#39;s Service spec does not have fields for NodePort<br>          type: StrategicMerge<br>          value:<br>            spec:<br>              ports:<br>                - name: https<br>                  port: 30443<br>                  targetPort: 443<br>                  nodePort: 30443 # Make sure to match ingress node&#39;s port mapping for HTTPS</pre><h4>Pitfall 2: Coder is accessible but fails healthcheck in healthcheck page</h4><p>Coder calls its healthcheck endpoint using the configured access URL as base.</p><p>For my setup, Coder will end up calling 127.0.0.1:30443, which it does not listen to.</p><p>To get around this, tweak CoreDNS’ ConfigMap (coredns)to resolve coder.localtest.me to the ClusterIP of the Service fronting your ingress solution. See the snippet for an illustration on how to edit.</p><pre>.:53 {  <br>  ready<br>  hosts {<br>    &lt;service_cluster_ip&gt; coder.localtest.me<br>    fallthrough<br>  }<br>  kubernetes cluster.local ... {<br>    ...<br>  }</pre><p>Restart CoreDNS deployment after updating ConfigMap.</p><h4>Pitfall 3: Coder Server still says own healthcheck fails</h4><p>UI or pod error logs will show that it is due to X509 issue from using self-signed certificate to serve Coder server.</p><p>In Coder Helm chart, there is an option to upload custom CA bundles to its trust store.</p><pre># values.yaml<br>coder:<br>  certs:<br>    secrets:<br>      - name: localtest-ca-bundle<br>        key: ca-bundle.crt</pre><h4>Pitfall 4: Code Server’s integrated terminal is incompatible with Alpine Linux</h4><p>It just doesn’t work with Alpine’s Musl.</p><h4>Pitfall 5: Rootless Docker is not possible if true host does not support userns sysctl</h4><p>Any attempt by rootless Docker toolkit will fail at trying to create new uid map.</p><p>KinD cluster nodes are not true Linux hosts, neither can the underlying Windows and (maybe) Mac OS hosts. So sysctl parameters for user namespace cannot be configured.</p><p>For cloud Kubernetes nodes, not really recommended to tweak Kubelet just for this.</p><blockquote>Conclusion: Have to go with privileged container to run Docker daemon.</blockquote><h4>Pitfall 6: Coder agent fails to connect to Coder server due to X509</h4><p>Problems with self-signed certificates bites again.</p><p>Either bake the custom CA certificate into the workspace container image or install it before running Coder agent init script.</p><p>I prefer the latter. Certificates expire and that means I need to rebuild and push to registry. The install before agent option is more of tweaking the container’s entrypoint and command parameters. Terraform handles the task of passing long multiline shell scripts as command very well.</p><pre>locals {<br>  workspace_launch_script = &lt;&lt;-EOT<br>    #!/bin/bash<br>    set -e<br><br>    # Install all custom CA certificates<br>    %{for i, cert in data.coder_parameter.custom_ca_certificates.value}<br>    %{if cert != &quot;&quot;}<br>    echo &quot;${cert}&quot; | base64 -d &gt; /usr/local/share/ca-certificates/${i}.crt<br>    %{endif}<br>    %{endfor}<br>    update-ca-certificates<br><br>    # Start Docker daemon in the background as root<br>    /usr/bin/dockerd &amp;<br><br>    # To-Do: Install other configured tools like Golang, kubectl, helm, etc. here<br><br>    # Set up and run code-server<br>    gosu coder /bin/bash &lt;&lt;&#39;EOC&#39;<br>      set -e<br><br>      # Start code-server in the background<br>      /usr/local/bin/code-server --bind-addr 0.0.0.0:8080 --auth none &amp;<br><br>      # Start coder agent<br>      ${coder_agent.main.init_script}<br>    EOC<br>  EOT<br>}<br><br># Kubernetes Deployment with code-server and dockerd containers<br># Many fields omitted for brevity<br>resource &quot;kubernetes_deployment_v1&quot; &quot;coder_workspace&quot; {<br>  count = data.coder_workspace.me.start_count &gt; 0 ? 1 : 0<br>  metadata {<br>    name      = lower(data.coder_workspace.me.name)<br>    namespace = local.workspace_namepace<br>  }<br><br>  spec {<br>    template {<br>      spec {<br>        # code-server container (runs Coder agent)<br>        container {<br>          name              = &quot;code-server&quot;<br>          command           = [&quot;/usr/bin/tini&quot;, &quot;--&quot;, &quot;/bin/bash&quot;, &quot;-c&quot;]<br>          args = [<br>            local.workspace_startup_script,<br>          ]<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Conclusion</h3><p>This setup is a first step towards a curated, yet more productive, development environment than my hardened laptop.</p><p>The process of figuring things out also helped me understand how this system works under the hood.</p><p>I hope this post helps you to quickly get started with rolling out a remote development environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c134c2dfffa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Gateway API in Kubernetes cluster]]></title>
            <link>https://medium.com/@ZiXianZeroX/setting-up-gateway-api-in-kubernetes-cluster-6e913f6a6b5c?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e913f6a6b5c</guid>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 09:41:52 GMT</pubDate>
            <atom:updated>2026-02-22T03:37:45.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background and motivation</h3><p>A month or two ago, I was informed of the <a href="https://kubernetes.io/blog/2025/11/11/ingress-nginx-retirement/">news about retiring of Ingress Nginx Controller</a>, which we are using as our Ingress solution in Kubernetes clusters.</p><p>We have to start looking for alternatives to migrate to, but even more so for formulating a well-reasoned strategy of picking ingress solution for various “flavours” of Kubernetes clusters we will have in the future. One aspect is Ingress vs Gateway API. Gateway API is very new to us and needs some exploration and experiential feedback before we can reason for or against it in our discussions.</p><p>Thus, this post is here to serve as a simple quickstart guide to get a Gateway API implementation ready to serve a simple application outside of the cluster.</p><p>Hope this post helps save some work figuring out the configuration for the gateway so you can get straight into trying it out on your applications.</p><h3>Outline</h3><p>I am using Terraform with some manifest files (for custom resources) throughout this setup.</p><ul><li>Deploy Envoy Gateway as Gateway API implementation</li><li>Deploy a single Gateway instance based on Envoy. This will act as the centralised gateway for all applications in the cluster in this context.</li><li>Test application reachability using a simple web application</li></ul><h3>Doing the work</h3><blockquote>Edit: I have updated the code/configuration to account for the case where resource quota is enforced on envoy namespace. I ran into problems rolling it out at work because all our namespaces need to have resource quota to control resource usage. This took a lot of time digging through Envoy Gateway’s Helm chart Github repository to figure out.<br>I have also changed the EnvoyProxy setting from class-wide into attaching to Gateway instances.<br>Last but not least, references for configuring load balancer for AKS is also added.</blockquote><p>Ensure how have a Kubernetes cluster up and running, with proper Kubeconfig set up to access this cluster. I am using Kubernetes-in-Docker (KinD) cluster with Podman as my container runtime on my Macbook. This shouldn’t matter but some details may require this for reference or need to change depending on the underlying setup.</p><p>Create a namespace envoy to hold the Envoy gateway controller and other centralized resources.</p><pre>kubectl create ns envoy</pre><h4>Deploy Gateway controller</h4><p>Deploy Envoy Gateway controller and CRDs using Helm (via Terraform).</p><pre>resource &quot;helm_release&quot; &quot;envoy_gateway&quot; {<br>  name          = &quot;envoy-gateway&quot;<br>  repository    = &quot;oci://docker.io/envoyproxy&quot;<br>  chart         = &quot;gateway-helm&quot;<br>  namespace     = &quot;envoy&quot;<br>  values        = [file(&quot;${path.module}/configs/envoy-gateway-values.yaml&quot;)]<br>  version       = &quot;v1.6.1&quot;<br>  recreate_pods = true<br>}</pre><pre># Full reference at https://github.com/envoyproxy/gateway/blob/main/charts/gateway-helm/values.tmpl.yaml<br>deployment:<br>  envoyGateway:<br>    resources:<br>      limits:<br>        cpu: 200m<br>        memory: 1024Mi<br>service:<br>  type: ClusterIP<br>certgen:<br>  job:<br>    resources:<br>      limits:<br>        cpu: 100m<br>        memory: 128Mi<br>      requests:<br>        cpu: 30m<br>        memory: 64Mi</pre><p>I am using ClusterIP Service type because my KinD cluster does not have anything to support LoadBalancer Service type. Attempting to use LoadBalancer Service will cause the Helm installation to hang due to service waiting for external IP. So far I do not see any real need for the Gateway controller to be accessible from outside the cluster, but I do not have enough usage experience to back this claim.</p><h4>Setting up common Gateway</h4><p>I will be setting up a Gateway to serve all application traffic in the cluster, using the hostname domain example.local . 1 listener for HTTP and 1 for HTTPS as TLS termination endpoint.</p><pre># Self-signed certificate to serve *.example.local domain<br>resource &quot;tls_private_key&quot; &quot;example_local&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 2048<br>}<br><br>resource &quot;tls_self_signed_cert&quot; &quot;example_local&quot; {<br>  private_key_pem = tls_private_key.example_local.private_key_pem<br><br>  subject {<br>    common_name  = &quot;*.example.local&quot;<br>    organization = &quot;Example Org&quot;<br>  }<br><br>  validity_period_hours = 8760<br>  early_renewal_hours   = 168<br><br>  allowed_uses = [<br>    &quot;key_encipherment&quot;,<br>    &quot;digital_signature&quot;,<br>    &quot;server_auth&quot;,<br>  ]<br><br>  dns_names = [&quot;*.example.local&quot;]<br>}<br><br>resource &quot;kubernetes_secret&quot; &quot;example_local_tls&quot; {<br>  metadata {<br>    name      = &quot;example-local-tls&quot;<br>    namespace = module.envoy_namespace.name<br>  }<br><br>  data = {<br>    &quot;tls.crt&quot; = tls_self_signed_cert.example_local.cert_pem<br>    &quot;tls.key&quot; = tls_private_key.example_local.private_key_pem<br>  }<br><br>  type = &quot;kubernetes.io/tls&quot;<br>}<br><br># Proxy config to fix Service type for<br># the Gateway resource being created<br>resource &quot;kubernetes_manifest&quot; &quot;envoy_proxy_config&quot; {<br>  depends_on = [helm_release.envoy_gateway]<br>  manifest   = yamldecode(file(&quot;${path.module}/configs/envoy-proxy.yaml&quot;))<br>}<br><br># Deploy Gateway Class so that the common Gateway can use<br>resource &quot;kubernetes_manifest&quot; &quot;gateway_class&quot; {<br>  depends_on = [helm_release.envoy_gateway]<br>  manifest   = yamldecode(file(&quot;${path.module}/configs/gatewayclass.yaml&quot;))<br>}<br><br>resource &quot;kubernetes_manifest&quot; &quot;gateway&quot; {<br>  depends_on = [<br>    kubernetes_manifest.gateway_class,<br>    kubernetes_manifest.envoy_proxy_config,<br>    kubernetes_secret.example_local_tls,<br>  ]<br>  manifest = yamldecode(file(&quot;${path.module}/configs/common-envoy-gateway.yaml&quot;))<br>}</pre><pre># envoy-proxy.yaml<br># Tells controller how to set up the associated Gateway<br><br>apiVersion: gateway.envoyproxy.io/v1alpha1<br>kind: EnvoyProxy<br>metadata:<br>  namespace: envoy<br>  name: envoy-proxy<br>spec:<br>  provider:<br>    type: Kubernetes<br>    kubernetes:<br>      envoyDeployment:<br>        # Modified from https://github.com/envoyproxy/gateway/blob/a2702cc5a92c436d218aeb5a8a2ef113b8ffd4da/site/content/en/v1.1/tasks/operations/customize-envoyproxy.md?plain=1#L801<br>        # to resolve errors about resource limits not set for common gateway pod shutdown-manager container<br>        # This error comes about due to our common standards of imposing resource quota on namespaces<br>        patch:<br>          type: StrategicMerge<br>          value:<br>            spec:<br>              template:<br>                spec:<br>                  containers:<br>                    - name: shutdown-manager<br>                      resources:<br>                        limits:<br>                          cpu: 500m<br>                          memory: 64Mi<br>        # Sets resource requests and limits for envoy container<br>        # No need to patch this one in patch section above<br>        container:<br>          resources:<br>            limits:<br>              cpu: 200m<br>              memory: 768Mi<br>            requests:<br>              cpu: 100m<br>              memory: 512Mi<br>      envoyService:<br>        # Avoid having problems with Gateway Service waiting for external IP with LoadBalancer Service<br>        type: ClusterIP<br>        # # Reference for LoadBalancer type<br>        # type: LoadBservice.beta.kubernetes.io/azure-load-balancer-internal: &quot;true&quot;service.beta.kubernetes.io/azure-load-balancer-internal: &quot;true&quot;alancer<br>        # # For AKS internal load balancer<br>        # annotations:<br>        #   service.beta.kubernetes.io/azure-load-balancer-internal: &quot;true&quot;<br>        # Not all load balancer implementations expose a class<br>        # loadBalancerClass: metallb<br>        # # Set this if setup allows/requires you to request specific IP address<br>        # loadBalancerIP: 192.168.77.123</pre><pre># gateway-class.yaml<br><br>apiVersion: gateway.networking.k8s.io/v1<br>kind: GatewayClass<br>metadata:<br>  name: envoy<br>spec:<br>  controllerName: gateway.envoyproxy.io/gatewayclass-controller<br>  # Reference in case you want all Gateways using this class<br>  # to have certain fixed configurations<br>  # Not very good if you need to set loadBalancerIP for the Gateway<br>  # Not sure whether it is possible to partially configure in the<br>  # EnvoyProxy used here and then merge the EnvoyProxy attached to the<br>  # specific Gateway<br>  # parametersRef:<br>  #   group: gateway.envoyproxy.io<br>  #   kind: EnvoyProxy<br>  #   namespace: envoy<br>  #   name: envoy-proxy</pre><pre># common-envoy-gateway.yaml<br><br>apiVersion: gateway.networking.k8s.io/v1<br>kind: Gateway<br>metadata:<br>  name: envoy-common<br>  namespace: envoy<br>spec:<br>  gatewayClassName: envoy<br>  # Use the EnvoyProxy resource from above to configure all<br>  # Kubernetes resources needed to run this Gateway<br>  infrastructure:<br>    parametersRef:<br>      group: gateway.envoyproxy.io<br>      kind: EnvoyProxy<br>      name: envoy-proxy<br>  listeners:<br>    - name: example-local-http<br>      hostname: &quot;*.example.local&quot;<br>      protocol: HTTP<br>      port: 80<br>      allowedRoutes:<br>        namespaces:<br>          from: All<br>    - name: example-local-https<br>      hostname: &quot;*.example.local&quot;<br>      protocol: HTTPS<br>      port: 443<br>      allowedRoutes:<br>        namespaces:<br>          from: All<br>      tls:<br>        # Use Passthrough to let backend Pods do TLS termination instead<br>        mode: Terminate<br>        certificateRefs: # Remove if using Passthrough<br>          - kind: Secret<br>            name: example-local-tls</pre><h4>Validating deployment success</h4><pre>% kubectl -n envoy get deployments<br>NAME                                READY   UP-TO-DATE   AVAILABLE   AGE<br>envoy-envoy-envoy-common-d2b6d240   1/1     1            1           25h<br>envoy-gateway                       1/1     1            1           27h<br>% kubectl -n envoy get svc        <br>NAME                                TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                                            AGE<br>envoy-envoy-envoy-common-d2b6d240   ClusterIP   10.96.133.191   &lt;none&gt;        80/TCP,443/TCP                                     25h<br>envoy-gateway                       ClusterIP   10.96.25.232    &lt;none&gt;        18000/TCP,18001/TCP,18002/TCP,19001/TCP,9443/TCP   27h<br>% kubectl -n envoy get gateway<br>NAME           CLASS   ADDRESS         PROGRAMMED   AGE<br>envoy-common   envoy   10.96.133.191   True         26h</pre><h4>Deploying application and exposing via Gateway API</h4><p>Can ignore the resources, security context, and volumes if removing them does not cause the deployment/pod to fail.</p><p>Do adjust/fix the Deployment manifest accordingly. Did not thoroughly test whether this will have permission issue chmod-ing files or binding to port 80.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: nginx:latest<br>          ports:<br>            - containerPort: 80<br>          securityContext:<br>            allowPrivilegeEscalation: false<br>            capabilities:<br>              add:<br>                - NET_BIND_SERVICE<br>              drop:<br>                - ALL<br>          resources:<br>            requests:<br>              cpu: 100m<br>              memory: 128Mi<br>            limits:<br>              cpu: 100m<br>              memory: 128Mi<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-service<br>spec:<br>  selector:<br>    app: nginx<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80<br>  type: ClusterIP<br>---<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: testapp<br>spec:<br>  parentRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      namespace: envoy<br>      name: envoy-common<br>      sectionName: example-local-https<br>  hostnames:<br>    - &quot;web.example.local&quot;<br>  rules:<br>    - name: catch-all<br>      matches:<br>        - path:<br>            type: PathPrefix<br>            value: /<br>      backendRefs:<br>        - kind: Service<br>          name: nginx-service<br>          port: 80<br>      timeouts:<br>        request: 11s<br>        backendRequest: 10s</pre><p>There should be HTTPRoute created.</p><pre>% kubectl get httproute<br>NAME      HOSTNAMES               AGE<br>testapp   [&quot;web.example.local&quot;]   47h<br>% kubectl get deployment<br>NAME               READY   UP-TO-DATE   AVAILABLE   AGE<br>nginx-deployment   3/3     3            3           47h<br>% kubectl get svc       <br>NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE<br>kubernetes      ClusterIP   10.96.0.1     &lt;none&gt;        443/TCP   4d6h<br>nginx-service   ClusterIP   10.96.79.48   &lt;none&gt;        80/TCP    47h</pre><h4>Testing that the ingress traffic works</h4><p>First run a port-forward to the Gateway Service HTTPS listener in the background.</p><pre>kubectl -n envoy port-forward service/envoy-envoy-envoy-common-d2b6d240 8443:443 &amp;</pre><p>Then, use Curl to access the web app without needing to set up hosts file or certificate trust chain. It should show a response HTML of the default Nginx web page.</p><pre>curl -kv --resolve web.example.local:8443:127.0.0.1 https://web.example.local:8443</pre><h3>Gotchas</h3><p>This setup works for simple HTTPS fronting with HTTP backend.</p><h4>HTTPS backend</h4><blockquote>Added in Jan 2026</blockquote><p>A use case for this is a Hashicorp Vault Helm installation, where I want clients to connect in via vault.example.local but internally the clusters see each other as *.vault.internal or something.</p><p>In this case, the active pod can be accessed via vault-active service, with FQDN vault-active.vault . I made sure my internal certificate is also signed for this domain.</p><p>The Gateway API setup for Vault looks like this.</p><pre>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  namespace: vault<br>  name: vault<br>spec:<br>  parentRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      namespace: envoy<br>      name: envoy-common<br>      sectionName: example-local-https<br>  hostnames:<br>    - &quot;vault.example.local&quot;<br>  rules:<br>    - name: catch-all<br>      matches:<br>        - path:<br>            type: PathPrefix<br>            value: /<br>      backendRefs:<br>        - kind: Service<br>          namespace: vault<br>          name: vault-active<br>          port: 8200<br>          protocol: HTTPS<br>      timeouts:<br>        request: 11s<br>        backendRequest: 10s</pre><p>Here is the additional configuration needed to make Envoy Gateway instance talk to Vault backend correctly using HTTPS.</p><pre>apiVersion: gateway.networking.k8s.io/v1<br>kind: BackendTLSPolicy<br>metadata:<br>  namespace: vault<br>  name: vault-backend-tls-policy<br>spec:<br>  # Must point to Service in the same namespace<br>  # See https://gateway-api.sigs.k8s.io/api-types/backendtlspolicy/#spec<br>  targetRefs:<br>    - group: &quot;&quot;<br>      kind: Service<br>      name: vault-active<br>  validation:<br>    caCertificateRefs:<br>      - group: &quot;&quot;<br>        kind: ConfigMap<br>        name: vault-internal-ca<br>    hostname: vault-active.vault</pre><p>The main catch is that BackendTLSPolicy should only point to Service objects being targeted by HTTPRoute. I only realized this after gen AI came up with this suggestion and I went to read up official documentation for verification.</p><h4>Load-balancer level health-check</h4><blockquote>Added on 2 Feb 2026.</blockquote><p>I have an Azure Application Gateway with a listener for a wildcard subdomain to front all application projects on AKS (scrimping on Application Gateway limits). For the health probe, it is not wise to point to any specific application backend because what if it closes shop. So I need something more generic that will always stay at the Gateway level.</p><p>After looking around and with AI’s help, I found out that it is possible to have a HTTPRoute that does direct response (Envoy Gateway specific). Here’s how it looks like.</p><pre>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: healthcheck<br>  namespace: envoy<br>spec:<br>  parentRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      namespace: envoy<br>      name: envoy-common<br>      sectionName: localtest-me-http<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      namespace: envoy<br>      name: envoy-common<br>      sectionName: localtest-me-https<br>  hostnames:<br>    - &quot;healthcheck.localtest.me&quot;<br>  rules:<br>    - name: catch-all<br>      matches:<br>        - path:<br>            type: Exact<br>            value: /healthz<br>      filters:<br>        - type: ExtensionRef<br>          extensionRef:<br>            group: gateway.envoyproxy.io<br>            kind: HTTPRouteFilter<br>            name: healthcheck-route-filter<br>      timeouts:<br>        request: 1s<br>        backendRequest: 1s<br>---<br>apiVersion: gateway.envoyproxy.io/v1alpha1 <br>kind: HTTPRouteFilter<br>metadata:<br>  name: healthcheck-route-filter<br>  namespace: envoy<br>spec:<br>  directResponse:<br>    contentType: &quot;text/plain&quot;<br>    statusCode: 200<br>    body:<br>      inline: &quot;OK&quot;</pre><p>The health probe URLs becomes <a href="http://healthcheck.localtest.me/healthz">http://healthcheck.localtest.me/healthz</a> and <a href="https://healthcheck.localtest.me/healthz">https://healthcheck.localtest.me/healthz</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e913f6a6b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MetalLB Setup and Configuration in Kubernetes via Terraform]]></title>
            <link>https://medium.com/@ZiXianZeroX/metallb-setup-and-configuration-in-kubernetes-via-terraform-c5021117784b?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5021117784b</guid>
            <category><![CDATA[terraform-provisioners]]></category>
            <category><![CDATA[metallb]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 02:24:44 GMT</pubDate>
            <atom:updated>2025-03-02T02:24:44.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to revisit <a href="https://medium.com/p/8e3a6b415387">this post</a> for setting up a makeshift load balancer plus ingress controller in a Kubernetes cluster. The setup uses mainly Terraform and other infrastructure/configuration as code technologies, so the added requirement is to be able to manage this setup using Terraform.</p><p>As written in MetalLB’s setup documentation, after deploying MetalLB pods, you will need to define IP address pools and a means of advertising these pools using custom resources. This needs to be done AFTER MetalLB deployment is complete, in particular the CRDs are created.</p><p>I attempted the following Terraform code in an attempt to setup everything in 1 Terraform run.</p><pre>resource &quot;helm_release&quot; &quot;metallb&quot; {<br>  # Omitted for brevity<br>}<br><br>resource &quot;kubernetes_manifest&quot; &quot;metallb_ip_pool_1&quot; {<br>  manifest {<br>    apiVersion = &quot;metallb.io/v1beta1&quot;<br>    kind = &quot;IPAddressPool&quot;<br>    # Omitted for brevity<br>  }<br>}</pre><p>The above code fails at plan-time with error saying that the resource type does not exist. This is because, the Helm chart for MetalLB has not been successfully installed yet (Terraform state is currently empty). What I want is to manage MetalLB and all its related resource in a single Terraform root module, deployed and possibly destroyed in just 1 Terraform run each. Also, it makes the experience better if Terraform can pick up changes in custom resources like IP address pool and apply the changes as well.</p><p>How do I make Terraform notice and manage the changes made to the IP address pool while not attempting to do a dry run against Kubernetes during plan time?</p><p>Having come across someone else’s code for another task involving resources without official provider resource, the idea of local-exec provisioner came into consideration.</p><p>The following is my initial code snippet.</p><pre># metallb-config.yaml<br>apiVersion: metallb.io/v1beta1<br>kind: IPAddressPool<br>metadata:<br>  name: lb-addresses<br>  namespace: metallb-system<br>spec:<br>  addresses:<br>    - 172.19.255.200-172.19.255.250<br>---<br>apiVersion: metallb.io/v1beta1<br>kind: L2Advertisement<br>metadata:<br>  name: lb-addresses<br>  namespace: metallb-system<br>spec:<br>  ipAddressPools:<br>    - lb-addresses<br><br># metallb.tf<br>resource &quot;terraform_data&quot; &quot;metallb_configs&quot; {<br>  depends_on = [helm_release.metallb]<br>  input      = file(&quot;./metallb-config.yaml&quot;)<br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;echo &#39;${self.input}&#39; | kubectl apply -f -&quot;<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>  provisioner &quot;local-exec&quot; {<br>    when        = destroy<br>    command     = &quot;echo &#39;${self.input}&#39; | kubectl delete -f -&quot;<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>}</pre><p>terraform_data is a replacement/successor to null_resource , starting from Terraform 1.4. Though, null_resource is not yet known to be deprecated. I am preferring Terraform data because I can put the whole manifest configuration as input , which Terraform can track the diffs in state file.</p><p>When running Terraform apply, you will see that the IPAddressPool and L2Advertisement resources got created. However, if you try to add another IP address range to the pool or comment out the terraform_data resource, there is no update nor deletion using Kubectl when running Terraform apply.</p><p>Provisioners are either create-time or destroy-time. So any attempt to change the IP address pool object will only update state data and not trigger any provisioner.</p><p>For destroying, it seems like Terraform removes the object from state file first before using the provider to delete the resource, then it tries to process the destroy-time provisioner. Since the resource no longer exists in state file, Terraform will not know to run the destroy-time provisioner. The workaround is to set count = 0 on the terraform_data resource. More details can be found in <a href="https://developer.hashicorp.com/terraform/language/resources/provisioners/syntax#destroy-time-provisioners">official documentation</a>. Then again, if you want to uninstall MetalLB completely, comment out this and the helm_release resource will make Kubernetes delete all these IP address pool resources as the CRDs for them no longer exists after MetalLB Helm chart is uninstalled.</p><p>What about update? Is there a way to make Terraform run Kubectl apply when resource definition changes? After some thought, I decided to exploit the triggering condition of create-time provisioner. This requires the resource that the provisioner is in to be re-created when the contents of the YAML file changes. However, terraform_data does not re-create itself when its input changes. So the create-time provisioner has to be pulled out into another resource. The new resource needs to be defined to trigger replacement when the terraform_data resource defined above changes. The new resource looks something like this.</p><pre>resource &quot;terraform_data&quot; &quot;apply_metallb_configs&quot; {<br>  depends_on = [terraform_data.metallb_configs]<br>  lifecycle {<br>    replace_triggered_by = [terraform_data.metallb_configs]<br>  }<br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;echo &#39;${terraform_data.metallb_configs.output}&#39; | kubectl apply -f -&quot;<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>}</pre><p>Here, the input field is left empty since it is optional and this resource’s job is not tracking the YAML file contents, but trigger replace when the other terraform_data resource changes. Try adding a new IP address range to the IPAddressPool object in the YAML file and do a Terraform run. You should see output lines saying the resource is configured.</p><p>The final code snippet looks something like this. Notice that the create-time provisioner is removed from terraform_data.metallb_configs as it is handled in the other terraform_data resource.</p><pre># metallb.tf<br>resource &quot;terraform_data&quot; &quot;metallb_configs&quot; {<br>  # Uncomment this first if intending to uninstall and cleanup MetalLB<br>  # count      = 0<br>  depends_on = [helm_release.metallb]<br>  input      = file(&quot;./metallb-config.yaml&quot;)<br>  provisioner &quot;local-exec&quot; {<br>    when        = destroy<br>    command     = &quot;echo &#39;${self.input}&#39; | kubectl delete -f -&quot;<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>}<br><br># To comment out when setting count = 0 on terraform_data.metallb_configs<br>resource &quot;terraform_data&quot; &quot;apply_metallb_configs&quot; {<br>  depends_on = [terraform_data.metallb_configs]<br>  lifecycle {<br>    replace_triggered_by = [terraform_data.metallb_configs]<br>  }<br>  provisioner &quot;local-exec&quot; {<br>    command     = &quot;echo &#39;${terraform_data.metallb_configs.output}&#39; | kubectl apply -f -&quot;<br>    interpreter = [&quot;/bin/bash&quot;, &quot;-c&quot;]<br>  }<br>}</pre><h3>Wrapping Up</h3><p>This whole post is about me using some workarounds and Terraform resource lifecycle management to achieve what I believe to be the desirable resource management experience using Terraform. The definition of desirable experience is subjective, but I hope this helps you with using Terraform to deploy something that needs its own custom resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5021117784b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set Up Dockerized Salt API Server Alongside Existing Dockerized Salt Master]]></title>
            <link>https://medium.com/@ZiXianZeroX/set-up-dockerized-salt-api-server-alongside-existing-dockerized-salt-master-2f550dbec98?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f550dbec98</guid>
            <category><![CDATA[saltstack]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 13:03:50 GMT</pubDate>
            <atom:updated>2023-02-23T13:05:25.305Z</atom:updated>
            <content:encoded><![CDATA[<p>This post serves as a learning journey documentation for the relatively long process to figure out the missing parts to make a containerized Salt API server work alongside Salt Master container on the same host.</p><p>As a beginner with very low Salt usage experience being tasked to explore using Salt API to do VM reboots, Salt’s documentation and presence in forums isn’t that great in my humble opinion. So I hope this post helps anyone looking to do similar set up.</p><h3>Pre-requisites</h3><p>A Linux (Virtual) Machine with Docker installed. If you are using other containerization tools, you will have to figure out how to tweak the guide to achieve the equivalent effect for your containerization tool.</p><p>A Docker container running Salt Master process(let’s call the container name salt-master). Assuming that all the stuff required to run Salt Master and also Salt API are already built into the container image.</p><p>At least 1 minion that is connected and managed by Salt Master. Here, we will identify the minion as minion1.</p><h3>Preparing the shared folders</h3><p>Salt API sends job requests to job queue for Salt Master to dispatch, and later receives job response from the job queue/cache. With default settings, Salt API also uses Unix sockets for IPC with Salt master, so Unix socket files also need to be shared. This part is what caused me to spend a long time looking up online to find out why Salt API is unable to access certain data.</p><p>The following files and folders are configured to be used for Salt Master(via host mount) in my specific case, change these accordingly if you configured Salt Master differently.</p><ul><li>/src/.ssh: For SSH-related stuff to minions</li><li>/srv/file: Contains truststore, not sure what it is for</li><li>/etc/salt: Salt configs</li><li>/etc/pki: For certificate trust chain</li><li>/var/run/salt/master: For IPC sockets</li><li>/var/cache/salt/master: For job queue/cache</li></ul><p>If any of the above is not a host-mount volume for Salt Master container, copy it out from Salt Master container, ensure that the folders can be modified by the user running inside the container, and then updating the Salt Master container to use the host-mount volume.</p><pre>docker cp -a salt-master:&lt;intended_path&gt; &lt;designated_path&gt;<br>chown -R &lt;container_user&gt; &lt;designated_path&gt;<br>docker stop salt-master<br>docker rm salt-master<br>docker run --name salt-master -d --network=host \<br>  &lt;list_of_required_env_variables&gt; \<br>  &lt;redacted_list_of_other_host-mount_volumes&gt; \<br>  -v &lt;designated_path&gt;:&lt;intended_path&gt; \<br>  &lt;container_image&gt; \<br>  /usr/local/bin/salt-master</pre><p>Check that Salt Master is up and running. If it doesn’t, check container logs to find out what might have gone wrong.</p><h3>Configure Salt API</h3><p>Open the file that corresponds to the Salt Master container’s /etc/salt/master.d/&lt;master_config_file&gt;.conf and add the following to configure the Salt API component.</p><pre>external_auth:<br>  file:<br>    ^filename: /etc/salt/api-users<br>    ^hashtype: md5<br>    jenkins: # Feel free to change the username<br>    - .* # List of API permissions jenkins user is allowed to use. This means all APIs<br>rest_cherrypy:<br>  port: 8080<br>  host: 0.0.0.0<br>  ssl_crt: /etc/pki/tls/certs/localhost.crt<br>  ssl_key: /etc/pki/tls/certs/localhost.key</pre><p>Here, I am using file-based authentication as it is easier to set up compared to PAM for containerized environment. You are free to use LDAP authentication if you wish to.</p><p>You can find common external authentication reference <a href="https://docs.saltproject.io/en/latest/topics/eauth/index.html">here</a>. For file-based authentication, you can find the reference <a href="https://docs.saltproject.io/en/latest/ref/auth/all/salt.auth.file.html">here</a> if you want to customize how the password file is to be formatted etc.</p><p>For file-based authentication, create a file api-users (configured from the above configuration file) with the following content in the folder that corresponds to /etc/salt in Salt Master container.</p><pre>jenkins:&lt;md5_hash_of_password&gt;</pre><p>The password section can be changed if you decide to use another hash type.</p><h3>Generate HTTPS Certificate</h3><p>It is essential to secure the connection between the client and the Salt API server as credentials are sent over the wire during the authentication process. Here, we will use self-signed certificate for convenience.</p><p>In Salt Master container, run a Salt command to create self-signed certificate. This will create self-signed certificate as /etc/pki/tls/certs/localhost.crt and private key as /etc/pki/tls/certs/localhost.key respectively in Salt Master container.</p><pre>docker exec -it salt-master bash -c &quot;salt-call --local tls.create_self_signed_cert&quot;</pre><p>Since the previous steps already make /etc/pki folder host-mounted volume for Salt Master container, the Salt API will have access to the certificate by host-mounting the same folder.</p><h3>Start up Salt API Server</h3><pre>docker run --name salt-api --network=host -d \<br>  &lt;same_set_of_env_variables_as_salt_master&gt; \<br>  &lt;same_list_of_redacted_list_of_other_host-mount_volumes_as_salt_master&gt; \<br>  &lt;container_image&gt; \<br>  /usr/local/bin/salt-api</pre><p>Note that here I am using host networking for the container. This is to facilitate easy connection between Salt Master and minions, and for Salt API to share the same master-minion connection if it really does need the connection. You might be able to find a more secure solution than this.</p><p>Check that the container is running properly. It should be listening to port 8080 on all interfaces. Use the container logs to debug if it is not up for some reason.</p><h3>Test out with a simple Curl Request</h3><p>Time to verify that we are able to operate on Salt minions using Salt API.</p><p>First, authenticate to the API server to obtain a token. We need to be authenticated as a user with sufficient permission to call certain APIs against the minions. Make sure jq command is installed as we will be using it to process JSON response from Salt API server.</p><pre>export TOKEN=$(curl -sSk https://localhost:8080/login \<br>    -H &quot;Accept: application/json&quot; \<br>    -d eauth=file \<br>    -d username=jenkins \<br>    -d password=password \<br>    -d client=local | jq &#39;.return[0].token&#39; | tr -d &#39;&quot;&#39;)<br>curl -sSk https://localhost:8080 \<br>    -H &quot;X-Auth-Token: ${TOKEN}&quot; \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -H &quot;Accept: application/json&quot; \<br>    -d &#39;[{&quot;client&quot;: &quot;local&quot;, &quot;fun&quot;: &quot;cmd.run&quot;, &quot;tgt&quot;: &quot;minion1&quot;, &quot;kwarg&quot;: {&quot;cmd&quot;: &quot;whoami&quot;}}]&#39;</pre><p>The returned response will look something like this.</p><pre>{&quot;return&quot;: [{&quot;minion1&quot;: &quot;root&quot;}]}</pre><h3>Troubleshooting</h3><p>This section summarizes the troubleshooting steps and references used to resolve the constant false replies by Salt API, which was frustrating because I did not know what was wrong with the setup.</p><ul><li>Configure Salt Master’s log level to debug.<br>This enables information like job ID to appear in Salt Master’s logs, which you can use to query for things like error messages from job information.</li><li>Obtain details of a certain job issued by Salt API using<br>salt-run jobs.print_job &lt;jid&gt; --out=json <br>It can tell you things like invalid arguments/parameters passed, so you know whether the problem lies with the request body or the connectivity between Salt Master and Salt API.</li></ul><h3>Wrapping Up</h3><p>At this point, we have a working Salt Master and Salt API setup, where we are able to remotely tell Salt Master to operate on Salt minions.</p><p>Hope this guide helped you move a step closer towards automating infrastructure maintenance work.</p><h3>References and Useful Information</h3><ul><li>Location of Salt Master socket directory for IPC: <a href="https://docs.saltproject.io/en/latest/ref/configuration/master.html#sock-dir">https://docs.saltproject.io/en/latest/ref/configuration/master.html#sock-dir</a></li><li>Determining if the equivalent Salt command of you API call is meant to succeed: <a href="https://github.com/saltstack/salt/issues/32859#issuecomment-214928483">https://github.com/saltstack/salt/issues/32859#issuecomment-214928483</a></li><li>Getting response data from Salt Master’s job queue/cache: <a href="https://docs.saltproject.io/en/latest/ref/configuration/master.html#job-cache">https://docs.saltproject.io/en/latest/ref/configuration/master.html#job-cache</a></li><li>Sample of how to use Curl to invoke Salt API: <a href="https://gist.github.com/mchugh19/61cd93440660ccbfc709">https://gist.github.com/mchugh19/61cd93440660ccbfc709</a></li><li>List of usable functions over Salt API: <a href="https://docs.saltproject.io/en/latest/ref/modules/all/index.html">https://docs.saltproject.io/en/latest/ref/modules/all/index.html</a><br>Recommended to use kwargs instead of args so you don’t have to pull your hair out over positional issues.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f550dbec98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient LRU Cache Implementation for Fixed-Size Cache Pool]]></title>
            <link>https://medium.com/@ZiXianZeroX/efficient-lru-cache-implementation-for-fixed-size-cache-pool-ea8646f0bd14?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea8646f0bd14</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[lru-cache]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 07:13:27 GMT</pubDate>
            <atom:updated>2022-01-05T07:13:27.155Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>Had a coding test interview earlier where I was asked to implement LRU(least-recently used) cache. It was both fortunate and unfortunate. Fortunate because I had implemented this before, but unfortunately, that was many years ago back when I was an undergraduate, so I clean forgotten how my most efficient implementation was like. In the end, I could only come up with an implementation that has O(n) time complexity for both get(key) and put(key, val) operations.</p><h3>My Thoughts on the Problem</h3><p>Not sure what the difficulty level of this problem is in general, but I think it is at least medium-hard, simply due to the complexity from the amount of manipulation needed to maintain the LRU data structure, making it very error-prone, especially during live-coding.</p><h3>Implementation Outline</h3><p>At the core lies an array-based implementation of a doubly-linked list. Each array index represents a linked list node. We then use 2 arrays to implement pointers to previous and next nodes. For example, prev[i] contains the index of the node that comes before node i, and next[i] contains the index of the node that comes after node i. We use index value of -1 to represent non-existent node. We also maintain a pointer to the first and last nodes of the linked list.</p><p>Since keys can be of any value(even if they are integers), we need to narrow down the problem by mapping them to array indices so we can represent the key with a linked list node. Using binary-search tree causes overall time complexity of O(log n) while hashmap causes overall amortized time complexity of O(1). This is entirely up to you to choose.</p><p>The most complex part is to shift any arbitrary node to the front of the linked list. With standard linked list, this will take O(n) time complexity. The data structure mapping keys to array indices helps by allowing direct access to the linked list node in the form of array index. From here on, it is simply O(1) time complexity manipulation of array index pointers.</p><p>When evicting, we need to make sure to update the key-index mapping data structure so that we do not mistakenly manipulate the LRU for non-existent keys. To do so, we attach another property to each linked list node, called key, in the form of another array, where each element value is the key associated with the linked list node.</p><h3>Implementation(in C++)</h3><p>Here is the implementation in C++. Uncomment the print functions to print out the state of the LRU data structure for verification of correctness by hand.</p><p>Edit the main function to run further tests.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;map&gt;<br>using namespace std;</pre><pre>class LRUCache {<br>private:<br>  /*<br>   * first and last point to vector indices of MRU and LRU respectively.<br>   * cap is the total number of cache slots available.<br>   * numFilled tracks how many of the cache slots is in use. Caps at cap.<br>   */<br>  int first, last, cap, numFilled;<br>  <br>  /*<br>   * Each vector index represents a linked list node(not necessarily in running order).<br>   * keys is used to look up indexMap for the key to be deleted. Set the vector type accordingly if the keys are not int type.<br>   * next and prev are index pointers to the next and previous linked list nodes respectively.<br>   * These 2 vectors, together with first and last variables, implement an &quot;array-based&quot; doubly-linked list.<br>   * -1 is used to indicate an invalid linked list node.<br>   * values can be taken out of this implementation, to be implemented by the<br>   * user of the LRU cache instead.<br>   */<br>  vector&lt;int&gt; keys, values, next, prev;<br>  <br>  /*<br>   * Maps keys to vector indices.<br>   * Change the first int to the corresponding type of the key.<br>   * Get and set operations are all O(log n)<br>   */<br>  map&lt;int, int&gt; indexMap;<br>  <br>  /*<br>   * O(1) shift of linked list node to front,<br>   * purely by manipulating index pointers.<br>   * Prone to implementation mistakes and corner cases.<br>   */<br>  void shiftToMRU(int idx) {<br>    if (last == idx) last = prev[idx];<br>    if (prev[idx] != -1) next[prev[idx]] = next[idx]; // if have previous, point its next to this&#39; next<br>    if (next[idx] != -1) prev[next[idx]] = prev[idx]; // if have next, point its prev to this&#39; prev<br>    next[idx] = first; // point this&#39; next to first<br>    prev[idx] = -1; // clear this&#39; prev pointer<br>    if (first != -1) prev[first] = idx; // point first&#39;s prev to this<br>    first = idx;<br>    if (last == -1) last = idx;<br>  }<br>  <br>  /*<br>   * Removes and returnsthe last element of the linked list in O(1) time.<br>   * Remember to pass the returned value to shiftToMRU to add back to the front of the LRU list.<br>   * DO NOT call when numFilled&lt;cap!<br>   */<br>  int evictLRU() {<br>    int idx{last};<br>    last = prev[idx];<br>    if (prev[idx] != -1) next[prev[idx]] = -1;<br>    prev[idx] = -1;<br>    return idx;<br>  }<br>  <br>  void printLRU() {<br>    cout&lt;&lt;&quot;first is &quot;&lt;&lt;first&lt;&lt;endl;<br>    cout&lt;&lt;&quot;last is &quot;&lt;&lt;last&lt;&lt;endl;<br>    cout&lt;&lt;&quot;next: &quot;;<br>    for (int i: next) cout&lt;&lt;i&lt;&lt;&#39;\t&#39;;<br>    cout&lt;&lt;endl;<br>    cout&lt;&lt;&quot;prev: &quot;;<br>    for (int i: prev) cout&lt;&lt;i&lt;&lt;&#39;\t&#39;;<br>    cout&lt;&lt;endl;<br>  }<br>  <br>  void printKeysAndValues() {<br>    cout&lt;&lt;&quot;keys: &quot;;<br>    for (int i: keys) cout&lt;&lt;i&lt;&lt;&#39;\t&#39;;<br>    cout&lt;&lt;endl;<br>    cout&lt;&lt;&quot;values: &quot;;<br>    for (int i: values) cout&lt;&lt;i&lt;&lt;&#39;\t&#39;;<br>    cout&lt;&lt;endl;<br>  }<br>  <br>  void printIndexMap() {<br>    cout&lt;&lt;&quot;indexes: &quot;;<br>    for (auto &amp;[k, v]: indexMap) {<br>      cout&lt;&lt;k&lt;&lt;&#39;\t&#39;;<br>    }<br>    cout&lt;&lt;endl;<br>  }<br>  <br> public:<br>  LRUCache(int capacity) : first(-1), last(-1), cap(capacity), numFilled(0) {<br>    keys = vector&lt;int&gt;(cap);<br>    values = vector&lt;int&gt;(cap);<br>    prev = vector&lt;int&gt;(cap, -1);<br>    next = vector&lt;int&gt;(cap, -1);<br>    indexMap = map&lt;int, int&gt;();<br>  }<br>  <br>  /*<br>   * Overall time complexity: O(log n)<br>   */<br>  int get(int key) {<br>    map&lt;int, int&gt;::iterator itr = indexMap.find(key); // O(log n)<br>    if (itr != indexMap.end()) {<br>      int idx{itr-&gt;second};<br>      shiftToMRU(idx); // O(1)<br>      // printLRU();<br>      return values[idx];<br>    }<br>    return -1;<br>  }<br>  <br>  /*<br>   * Overall time complexity: O(log n)<br>   */<br>  void put(int key, int val) {<br>    map&lt;int, int&gt;::iterator itr = indexMap.find(key); // O(log n)<br>    if (itr != indexMap.end()) {<br>      int idx{itr-&gt;second};<br>      shiftToMRU(idx); // O(1)<br>      keys[idx] = key;<br>      values[idx] = val;<br>    } else if (numFilled &lt; cap) {<br>      indexMap[key] = numFilled;<br>      keys[numFilled] = key;<br>      values[numFilled] = val;<br>      shiftToMRU(numFilled); // O(1)<br>      numFilled++;<br>    } else {<br>      int idx{evictLRU()};<br>      cout&lt;&lt;&quot;evicting cache at index &quot;&lt;&lt;idx&lt;&lt;endl;<br>      indexMap.erase(keys[idx]);<br>      indexMap[key] = idx;<br>      keys[idx] = key;<br>      values[idx] = val;<br>      shiftToMRU(idx); // O(1)<br>      // printIndexMap();<br>    }<br>    // printLRU();<br>    // printKeysAndValues();<br>  }<br>};</pre><pre>int main() {<br>  int val;<br>  LRUCache lru(4);<br>  lru.put(2, 5);<br>  lru.put(6, 3);<br>  lru.put(7, 9);<br>  lru.put(4, 7);<br>  val = lru.get(3);<br>  cout&lt;&lt;&quot;value for key 3 is &quot;&lt;&lt;val&lt;&lt;endl;<br>  val = lru.get(6);<br>  cout&lt;&lt;&quot;value for key 6 is &quot;&lt;&lt;val&lt;&lt;endl;<br>  lru.put(2, 1);<br>  lru.put(8, 10);<br>  return 0;<br>}</pre><h3>Closing Statements</h3><p>Hope this helps you out for technical interviews. It is almost impossible to implement a bug-free version on the spot, but at least find a way to succinctly describe this implementation for a better chance at passing the interview.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea8646f0bd14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Gitlab Project on GKE Cluster]]></title>
            <link>https://awstip.com/deploying-a-gitlab-project-on-gke-cluster-bcba857f63e4?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcba857f63e4</guid>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[gitlab-kubernetes-agent]]></category>
            <category><![CDATA[google-kubernetes-engine]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 18:14:41 GMT</pubDate>
            <atom:updated>2021-12-21T06:12:14.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>As part of an interview process, I was given a take home assignment to do, with an optional task being to host the application publicly. Since I am dabbling with Kubernetes applications these days, I decided to try deploying it on a public cloud that supports Kubernetes cluster. I picked Google Kubernetes Engine(GKE from here on) as I had wanted to try it out but no meaningful project to justify spending my $300 free trial credits on.</p><p>Not sure how long ago this was introduced, but GKE has this Autopilot mode where you do not have to manage the cluster nodes provisioned to you. This includes changing the cluster size(increasing/decreasing nodes), configuring the control-plane and worker nodes etc. All you need to concern yourself with are kubectl commands and object definition manifests.</p><p>On hindsight, most of what this post covers should be applicable to other Kubernetes clusters as well, such as Amazon EKS and even on-premise clusters. The main differences are firewall rules affecting inbound traffic, presence/absence of public IP/NAT for outbound traffic, load balancers, external IP address to expose the application to public Internet, and serveral more. Here, I will just cover based on my experience with GKE private Autopilot cluster.</p><h3>Overview of project setup and deployment process</h3><p>This forms the basis for the decisions made in the guide. Different deployment styles affect the setup of the various tools and pipelines used. The deployment style described here is what I use at work to keep my pre-release administrative work to a minimum, though it may or may not be a best practice in terms of DevOps.</p><ul><li>Use Git tags on master branch to trigger production deployment. Tag names strictly follow semantic versioning format.</li><li>All manually-built images to be deployed on Kubernetes cluster have image tag names set as ${CI_COMMIT_TAG} . For example, in a Pod’s container definition: image: registry.gitlab.com/mynamespace/myproject:${CI_COMMIT_TAG}. This is to cut out the need for extra commit to update the image version in Kubernetes manifest files before triggering the production pipeline.</li><li>Deploy to Kubernetes cluster <strong>ONLY</strong> after ensuring that image build succeeds, all tests passed, and no other unforeseen causes of error that can break current running production application. This means to trigger the deployment job manually.</li></ul><h3>Restrictions of choice of cluster</h3><p>Being a private cluster, all nodes spawned by the platform to run pods have no public IP address, preventing them from reaching to public Internet to pull images from Docker Hub or any other registry. We will get around this by attaching an NAT service to the cluster.</p><p>Enabling control-plane authorized networks makes it very difficult to run kubectl commands from Gitlab Runner. In recent(already introduced for quite some time) releases, Gitlab introduced the <a href="https://docs.gitlab.com/ee/user/clusters/agent/">Gitlab Kubernetes Agent</a>. The linked page describes the core usage. Here, we will tweak the behaviour of the agent a bit to give us more controlled deployment while minimizing the number of repositories to just the project’s. This is done by using <a href="https://docs.gitlab.com/ee/user/clusters/agent/ci_cd_tunnel.html">CI/CD tunneling</a> provided by the agent. This allows use to run kubectl commands against the cluster from within our CI job.</p><h3>The setup process</h3><h4>Setting Up Internet access for GKE cluster nodes</h4><p>In the GCP dashboard, go to <em>Network Services</em> -&gt; <em>Cloud NAT</em>.</p><p>Create an NAT gateway, selecting your GKE cluster’s network from the dropdown list, picking the same region as the GKE cluster, and creating a cloud router for it(assuming none exists yet). For NAT IP addresses, select <em>Automatic</em>. This saves you the hassle of having to predict(you cannot for GKE Autopilot) the size of the cluster/subnet and manually reserving static public IP addresses. I am not sure how many nodes’ outbound connections a single NAT IP address supports. You can find out more about GCP’s Cloud NAT IP addresses <a href="https://cloud.google.com/nat/docs/ports-and-addresses#addresses">here</a>.</p><p>It will take some time for NAT to be up. If there is no pod deployed on the cluster yet. there is no node to test. So we create a simple pod to test the provisioned node’s ability to pull images from Docker Hub.</p><p>Create a pod with this definition.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-pod<br>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx:latest</pre><p>Use kubectl describe pod &lt;pod_name&gt; to check if the assigned node is able to pull the Nginx image. The events section should say that the image is successfully pulled. Feel free to delete the pod after use. We do not want to get billed for unnecessary pods.</p><p>If it fails, it might be possible that egress firewall rule is required for the cluster’s network.</p><p>Under <em>Kubernetes Engine</em> -&gt; <em>Clusters</em> -&gt; your cluster, in <em>Networking</em> section, click on the cluster’s <em>Network</em>. Go to <em>Firewall</em> and create firewall rule. For traffic direction, select <strong>Egress</strong> and <strong>Allow</strong> <em>on match</em>. For targets, select <strong>All instances in the network</strong> since we cannot really tag any nodes as they are dynamically provisioned based on workload. For <em>source IPv4 ranges</em>, just put <strong>0.0.0.0/0</strong> for convenience, considering the restrictions placed by GKE Autopilot mode. For <em>Protocols and ports</em>, feel free to set fine-grained control if you know what you are doing. Here, I just select <strong>Allow all</strong>.</p><h4>Set up Gitlab Kubernetes Agent</h4><p>In your project’s default(typically master) branch, create this file .gitlab/agents/&lt;agent_name&gt;/config.yaml with the following content.</p><pre>gitops:<br>  manifest_projects:<br>  - id: &lt;namespace&gt;/&lt;project_name&gt;<br>    default_namespace: default<br>ci_access:<br>  projects:<br>  - id: &lt;namespace&gt;/&lt;project_name&gt;</pre><p>Set gitops.manifest_projects to the correct manifest project, and ci_access.projects[0].id to your actual application project. For gitops.default_namespace , it is similar to setting the default namespace in Kubeconfig’s contexts. No manifest file path is set since our workflow does not want the agent to sync the manifest files to the Kubernetes cluster on every commit as they will be invalid and the production images may not have been built.</p><p>Commit the file and push to the default branch on Gitlab.</p><p>On Gitlab, in your project, go to <em>Infrastructure</em> -&gt; <em>Kubernetes clusters</em>. The configured agent should be listed in a dropdown when trying to install a new agent. On completion, Gitlab presents you with a registration token. Copy and save it in a text file as we will need it in a later step and this is the <strong>ONLY</strong> chance to see the token in plaintext.</p><p>On the Kubernetes cluster, create a namespace to deploy Gitlab Kubernetes Agent in.</p><pre>kubectl create ns gitlab-kubernetes agent</pre><p>Create the secret from the registration token. This will be used by the agent to register itself with KAS.</p><pre>kubectl create secret generic -n gitlab-kubernetes-agent gitlab-kubernetes-agent-token --from-literal=token=&#39;&lt;YOUR_AGENT_TOKEN&gt;&#39;</pre><p>Grab the deployment manifest files <a href="https://docs.gitlab.com/ee/user/clusters/agent/install/#example-resourcesyml-file">here</a>. Remove the namespace object. For the deployment object, set the namespace to gitlab-kubernetes-agent . For the deployment’s container args, set the websocket URL accordingly. For Gitlab.com projects, use wss://kas.gitlab.com . This is documented in the example manifest file you just downloaded.</p><p>Apply the manifest file and check that the pod runs with no errors in logs.</p><h4>Set up the CI/CD pipeline</h4><p>In .gitlab-ci.yaml , define build jobs that push your built images to a registry. If the registry is private, you have to create a secret of type kubernetes.io/dockerconfigjson with correct Docker credentials that has pull access to the registry, and then use this secret in your Pod’s imagePullSecrets. If using Gitlab’s container registry, you can go to the project’s <em>Settings</em> -&gt; <em>Repository</em> -&gt; <em>Deploy keys</em> and create a deploy key. This deploy key token is the password used for docker login command while the username is the one passed into the form during the process of making a deploy key. To convert it to Base64 encoding, run docker login against the registry, print the Docker config file and pass it through tr -d &quot;[:space:]&quot; before going through base64 -w 0 command. An example will be</p><pre>cat ~/.docker/config.json | tr -d &quot;[:space:]&quot; | base64 -w 0</pre><h4>Build our own Kubectl image</h4><p>There is already a bitnami/kubectl image out there. However, it does not fit into our use case here as we depend on envsubst command to set our application image tag in Kubernetes manifest file before applying it to the Kubernetes cluster.</p><p>Define a Dockerfile named Dockerfile-deploy with the following content.</p><pre>FROM alpine:latest<br>RUN set -e; \<br>  apk update; \<br>  apk add --no-cache \<br>    bash \<br>    curl \<br>    gettext \<br>  ; \<br>  rm -rf /var/cache/apk/*; \<br>  curl -LO &quot;https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl&quot;; \<br>  curl -LO &quot;https://dl.k8s.io/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256&quot;; \<br>  echo &quot;$(cat kubectl.sha256)  kubectl&quot; | sha256sum -c; \<br>  install -m 0755 kubectl /usr/local/bin/kubectl; \<br>  kubectl version --client; \<br>  adduser -h /home/dev -s /bin/bash -D -u 1001 dev;<br>USER dev<br>WORKDIR /home/dev<br>ENTRYPOINT [&quot;/bin/bash&quot;, &quot;-c&quot;]</pre><p>Add a CI job that builds using this Dockerfile and pushes it to the registry.</p><h4>Create deploy job</h4><p>Create an initial deploy job that looks something like this.</p><pre>deploy:<br>  stage: deploy<br>  image: &lt;your_kubectl_image&gt;<br>  tags:<br>  - linux<br>  - docker<br>  script:<br>  - kubectl config get-contexts</pre><p>Trigger this job and check the job logs for the proper context name/path to use. Then change the job to look something like this.</p><pre>deploy:<br>  stage: deploy<br>  image: &lt;your_kubectl_image&gt;<br>  tags:<br>  - linux<br>  - docker<br>  only:<br>  - /^\d+\.\d+\.\d+$/<br>  when: manual<br>  before_script:<br>  - kubectl config use-context &lt;context_path&gt;<br>  script:<br>  - envsubst &lt; ${CI_PROJECT_DIR}/&lt;path_to_manifest&gt; | kubectl apply -f -<br>  - sleep 10<br>  - kubectl get pods</pre><p>Try creating a tag to trigger the production pipeline and check that the deploy job succeeds. Do remember to manually trigger this deploy job. Go to the Kubernetes cluster to check that all the application components are up and running.</p><h4>Exposing the application to the public</h4><p>This part is highly platform-specific. In line with the post’s title, I will only cover the case for GKE.</p><p>Create a load balancer service pointing to your application’s deployment pods.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-application<br>spec:<br>  ports:<br>  - name: http<br>    port: 80<br>    targetPort: http<br>  selector:<br>    # use same label set as your deployment<br>    app: my-app<br>  type: LoadBalancer</pre><p>By creating a load balancer service, GKE provisions a layer 4 load balancer that assigns an external IP address to your service. Note that this is a regional IP address(I am not very sure on the difference between regional and global).</p><p>For global IP address, create an Ingress instead.</p><p>Under your GKE cluster’s VPC network, go to <em>External IP addresses</em>. You should see 2 entries: 1 for the cloud NAT router, and the other for the Service/Ingress. Try to access the application using the latter’s external address.</p><h3>Closing statement(s)</h3><p>I hope this learning experience of mine helps you save significant amount of time figuring out how to link up your Kubernetes cluster to your Gitlab project, and also synchronizing the Kubernetes manifest files between your project repository and the Kubernetes cluster in a controlled manner.</p><p>Leave a like and some good comments if you found it useful. Do leave some constructive feedbacks on how I can improve/correct on this guide as well.</p><p>Thanks for making it all the way here after a long read.</p><h3>References</h3><ul><li>Gitlab Kubernetes Agent installation: <a href="https://docs.gitlab.com/ee/user/clusters/agent/install/">https://docs.gitlab.com/ee/user/clusters/agent/install/</a></li><li>Gitlab Kubernetes Agent configuration: <a href="https://docs.gitlab.com/ee/user/clusters/agent/repository.html">https://docs.gitlab.com/ee/user/clusters/agent/repository.html</a></li><li>Gitlab Kubernetes Agent CI/CD Tunneling: <a href="https://docs.gitlab.com/ee/user/clusters/agent/ci_cd_tunnel.html">https://docs.gitlab.com/ee/user/clusters/agent/ci_cd_tunnel.html</a></li><li>Gitlab deploy token: <a href="https://docs.gitlab.com/ee/user/project/deploy_tokens/">https://docs.gitlab.com/ee/user/project/deploy_tokens/</a></li><li>Exposing applications on GKE: <a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/configuring-domain-name-static-ip#exposing_your_application">https://cloud.google.com/kubernetes-engine/docs/tutorials/configuring-domain-name-static-ip#exposing_your_application</a></li><li>Cloud NAT for GKE: <a href="https://cloud.google.com/nat/docs/gke-example">https://cloud.google.com/nat/docs/gke-example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcba857f63e4" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-a-gitlab-project-on-gke-cluster-bcba857f63e4">Deploying a Gitlab Project on GKE Cluster</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Network Driver not found in new Ubuntu Server installation]]></title>
            <link>https://medium.com/@ZiXianZeroX/fixing-network-driver-not-found-in-new-ubuntu-server-installation-2ffbedbb2333?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffbedbb2333</guid>
            <category><![CDATA[ubuntu-server]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Tue, 07 Dec 2021 07:58:38 GMT</pubDate>
            <atom:updated>2021-12-07T07:58:38.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>Recently received a new PC on which I was to install Ubuntu Server.</p><p>The on-board LAN adapter(Intel I219-V) quite new, so driver not included in Ubuntu Server installer(installer cannot detect any any network interface). I only found this out after some Google search involving Ubuntu and Intel I219-V.</p><p>Turns out that there is this thing called Hardware Enablement Stack that keeps a bunch of updated drivers for various devices. This is because for LTS versions, in order to maintain stability, do not get updated as often, resulting in drivers that are released AFTER the OS image is created being left out. Installing the Hardware Enablement Stack fixes this issue.</p><h3>Steps</h3><p>On a functioning Ubuntu server, download the HWE package but not install it. The 20.04 part will change in the future when the LTS version changes.</p><pre>sudo apt install --download-only --install-recommends linux-generic-hwe-20.04</pre><p>Plug in and mount the USB drive, and then move all the downloaded .deb files from /var/cache/apt/archives/ into a folder on the USB drive.</p><p>Move the USB drive to the Ubuntu server to be fixed and mount it.</p><p>Navigate to the folder on the USB drive with the .deb files and install them.</p><pre>sudo dpkg -i *</pre><p>Restart is required since it involves generating new initramfs file.</p><h3>After</h3><p>Check that the network adapter is now detected by the OS.</p><pre>ip a</pre><p>Use this chance to get the name of the network interface. It is needed when setting up network configuration later.</p><p>Set up the network connection via netplan. For example,</p><pre>### /etc/netplan/00-installer-config.yaml<br>network:<br>  version: 2<br>  renderer: networkd<br>  ethernets:<br>    enp0s31f6:<br>      dhcp4: false<br>      addresses:<br>      - 192.168.1.3/24<br>      nameservers:<br>        addresses: [8.8.8.8]<br>      gateway4: 192.168.1.1</pre><p>Apply the network configuration and check that the settings are applied.</p><pre>sudo netplan apply<br>ip a</pre><h3>References</h3><ul><li><a href="https://ostechnix.com/download-packages-dependencies-locally-ubuntu/">Downloading APT packages but not installing them</a></li><li><a href="https://askubuntu.com/questions/1344156/ubuntu-20-04-2-and-onboard-intel-i219-v">Installing Ubuntu Server HWE for Intel I219-V On-board LAN adapter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffbedbb2333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disaster Recovery for NFS Volumes on Kubernetes Cluster]]></title>
            <link>https://medium.com/@ZiXianZeroX/disaster-recovery-for-nfs-volumes-on-kubernetes-cluster-d9b255ed00c7?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b255ed00c7</guid>
            <category><![CDATA[disaster-recovery]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[fn]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 11:02:50 GMT</pubDate>
            <atom:updated>2021-11-23T11:02:50.933Z</atom:updated>
            <content:encoded><![CDATA[<p>After setting up an on-premise Kubernetes cluster and deploying a few applications’ staging environments on it, it is time to work on persistent data storage solution for these applications.</p><p>The choice of NFS for volumes is due to the relative ease of setting up, compared to other open-source solutions(I have much trouble absorbing all the concepts and setup guides).</p><p>A big problem of using NFS is that you have to specify server IP address. So if the server goes down permanently(eg. got hit by ransomware), all applications that use this NFS for volumes will be affected. This post will be about how to move applications to use data from backup server.</p><h3>Pre-Notes</h3><ul><li>If your NFS servers are already on high-availability setup(eg. TrueNAS Core HA license), this post will not be relevant</li><li>If you are already using some other more robust solutions like Ceph/Rook, OpenEBS etc., you will likely not need this</li><li>This guide can be very tiring to pull off, having to repeat all the steps for each application pod/persistent-volume-claim(PVC)/persistent-volume(PV)</li></ul><h3>Context</h3><ul><li>2x TrueNAS Core servers<br>- 192.168.60.16/24 for the main server, 192.168.60.17/24 for the backup server<br>- Any NFS server will do, as long as you know how to set up the exports and the user mapping and permissions<br>- The 2 servers need to be synced in terms of the exported folders</li><li>A working Kubernetes cluster<br>- Refer to <a href="https://medium.com/@ZiXianZeroX/setting-up-an-on-premise-kubernetes-cluster-from-scratch-8e3a6b415387">this post</a> on how to set up one</li><li>NFS storage class and controller setup<br>- Here, I used <a href="https://github.com/kubernetes-sigs/nfs-subdir-external-provisioner">nfs-subdir-client-provisioner</a> for my NFS storage volume solution, using namespace storage</li><li>Application myapp running on cluster<br>- Consists of deployment myapp and statefulset myapp-db , both of which use NFS volumes via the storage class</li></ul><h3>The Actual Work</h3><h4>Simulating the ransomware attack</h4><p>Shutdown the NFS service on the main NFS server. Powering-off the server is NOT necessary. All applications using NFS volumes will now have IO errors.</p><h4>Stop and Edit the Storage Class Controller</h4><p>Check which node the storage class controller is deployed on.</p><pre>kubectl -n storage describe pod &lt;controller_pod_name&gt;</pre><p>Stop the storage class controller pod by scaling the deployment replicas to 0.</p><pre>kubectl -n storage scale --replicas=0 deployments/nfs-client-provisioner</pre><p>This will cause the pod to be stuck in Terminating state. To fix this, go to the node the pod was running on and force unmount the NFS mount.</p><p>Check where the NFS mount for the storage class controller is mounted at.</p><pre># mount | grep &#39;192.168.60.16&#39;<br>192.168.60.16:/mnt/data/nfs on /var/lib/kubelet/pods/665df8d1-91b2-431d-92ad-bb51a9c0ce99/volumes/kubernetes.io~nfs/nfs-client-root type nfs4</pre><p>Force unmount the mount point.</p><pre>sudo umount -f -l /var/lib/kubelet/pods/665df8d1-91b2-431d-92ad-bb51a9c0ce99/volumes/kubernetes.io~nfs/nfs-client-root</pre><p>The storage class controller pod should be gone now.</p><p>Open the deployment file for the storage class controller and replace all instances of 192.168.60.16 with 192.168.60.17 .</p><h4>Clean Up Application Pods</h4><p>Manually collate a list of all the nodes the application pods are running on.</p><pre>kubectl get pods<br>kubectl describe pod &lt;myapp_pod_name&gt;<br>kubectl describe pod &lt;myapp_db_pod_name&gt;</pre><p>Delete the pods by scaling the deployment/stateful set replica count to 0.</p><pre>kubectl scale --replicas=0 deployments/myapp<br>kubectl scale --replicas=0 statefulsets/myapp-db</pre><p>The pods will be stuck in Terminating state.</p><h4>Unmount from Nodes</h4><p>On each of the nodes in the list collated from previous section, unmount all NFS mounts associated with the affected pods. The following is an example output of the mount points of affected pods on the node.</p><pre># mount | grep &#39;192.168.60.16&#39;<br>192.168.60.16:/mnt/data/nfs/default-myapp-db-volume-myapp-db-0-pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd on /var/lib/kubelet/pods/0977ec22-96b3-46dd-9d42-e774a9a138fc/volumes/kubernetes.io~nfs/pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd type nfs4 ...<br>192.168.60.16:/mnt/data/nfs/default-myapp-data-pvc-f8b91a18-f028-4916-9b87-5d54dda1960f on /var/lib/kubelet/pods/47e226c2-de70-49d1-8de5-9f61e06fbff7/volumes/kubernetes.io~nfs/pvc-f8b91a18-f028-4916-9b87-5d54dda1960f type nfs4 ...<br># sudo umount -f -l /var/lib/kubelet/pods/0977ec22-96b3-46dd-9d42-e774a9a138fc/volumes/kubernetes.io~nfs/pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd<br># sudo umount -f -l /var/lib/kubelet/pods/47e226c2-de70-49d1-8de5-9f61e06fbff7/volumes/kubernetes.io~nfs/pvc-f8b91a18-f028-4916-9b87-5d54dda1960f</pre><p>The pods are still stuck in Terminating state, because Kubernetes has trouble cleaning up the PVs and PVCs.</p><h4>Backup and Delete PVs and PVCs</h4><p>Backup the PVCs’ definitions to file. If your statefulset has more than 1 replicas, do this for <strong>EVERY</strong> replica’s PVC.</p><pre># kubectl get pvc<br>NAME                           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE<br>myapp-db-volume-myapp-db-0   Bound    pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd   1Gi        RWO            nfs-storage    164m<br>myapp-data       Bound    pvc-f8b91a18-f028-4916-9b87-5d54dda1960f   2Gi        RWO            nfs-storage    138m<br># kubectl get pvc myapp-data -o yaml &gt; web-pvc.yaml<br># kubectl get pvc myapp-db-colume-myapp-db-0 -o yaml &gt; db-pvc.yaml</pre><p>In each of the PVC definition files, delete the following fields.</p><ul><li>pv.kubernetes.io/bind-completed: “yes” annotation</li><li>status field</li></ul><p>Backup the PVs as well. If the PV is not manually reconstructed when the PVC is created, the storage class controller will generate a new PV with new UID, resulting in the application starting out fresh on a new volume.</p><pre># kubectl get pv<br>NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                                  STORAGECLASS   REASON   AGE<br>pvc-f8b91a18-f028-4916-9b87-5d54dda1960f   2Gi        RWO            Delete           Bound    default/makina-staging-ssl-certs       nfs-storage             57m<br>pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd   1Gi        RWO            Delete           Bound    default/makina-db-volume-makina-db-0   nfs-storage             93m<br># kubectl get pv pvc-f8b91a18-f028-4916-9b87-5d54dda1960f -o yaml &gt; web-pv.yaml<br># kubectl get pv pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd -o yaml &gt; db-pv.yaml</pre><p>In each of the PV definition files, delete the following fields.</p><ul><li>spec.claimRef field</li><li>status field</li></ul><p>Also, change the IP address of the spec.nfs.server field to the backup server’s IP address(192.168.60.17).</p><p>Delete the PVCs.</p><pre>kubectl delete pvc myapp-data<br>kubectl delete pvc myapp-db-volume-myapp-db-0</pre><p>Check that the PVCs, PVs, and pods are gone.</p><pre>kubectl get pvc<br>kubectl get pv<br>kubectl get pods</pre><p>If the PVs somehow do not get deleted, try deleting them manually.</p><pre>kubectl delete pv pvc-f8b91a18-f028-4916-9b87-5d54dda1960f<br>kubectl delete pv pvc-d052ce0e-7c06-4378-a580-6cc8548fc3bd</pre><p>Without the unmounting in previous section, the above commands will show the objects stuck in Terminating status.</p><p>For statefulsets, such as MySQL database containers, all related resources(Pod, PVC, PV) may get stuck at Terminating indefinitely due to some shutdown procedures that do not return unless it finishes. But since the backing volume storage is already gone, there is nothing to lose. For most cases, it might be worthwhile to wait a while, but if have to, force delete the pod will “fix” the issue.</p><pre>kubectl delete pod myapp-db-0 --grace-period=0 --force</pre><p>This can leave lingering processes of the deleted pod on the node that stays invisible to Kubernetes cluster, causing zombie load on the node, so do not use this command unless out of options.</p><h4>Repeat the Above Steps</h4><p>Repeat until all pods dependent on NFS volumes are down and all relevant PVCs are backed up into YAML files before proceeding.</p><h4>Restart the Storage Class Controller</h4><p>We kept the storage class controller down during deletion because if it were up, the deletion might cause the storage class controller to delete the data on the backup server! This is due to replication causing the file paths on the backup server to match the path defined in the PV.</p><p>Although if you take a close look at the PV with kubectl get pv &lt;pv_name&gt; , you will find that the server IP address is still pointing to the “dead” main NFS server, so this should not be an issue.</p><pre>kubectl apply -f deployment.yaml</pre><h4>Reconstruct the PVs and PVCs</h4><p>Since the storage class controller has been redeployed to use the backup server, recreating the PVs and PVCs will end up with volumes using existing data on the backup server.</p><p>The backup step in previous section is important because we want to preserve the UID in the PV and PVC names. nfs-subdir-client-provisioner uses these UIDs to generate folder paths on the NFS server. Here, we assume folder structure is replicated exactly from the main to backup server.</p><pre>kubectl apply -f db-pvc.yaml<br>kubectl apply -f web-pvc.yaml<br>kubectl get pv<br>kubectl get pvc</pre><p>Repeat this step for all other affected applications before proceeding.</p><h4>Restore the Pods</h4><p>Finally, work towards reverting the application pods to their initial state before the disaster happened. Restart the statefulsets/deployments in dependency order so the pods don’t fail because another pod is not up yet.</p><pre>kubectl scale --replicas=1 statefulsets/myapp-db<br>kubectl scale --replicas=1 deployments/myapp</pre><h3>Closing Words</h3><p>Hope this post is useful for anyone working with a 100% on-premise Kubernetes cluster using on-premise NFS server for volume storage backing.</p><p>Let me know in the comments if there is any typo, anything factually wrong in the post, or anything that can be improved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b255ed00c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Calico CNI Plugin for Kubernetes Cluster]]></title>
            <link>https://medium.com/@ZiXianZeroX/upgrading-calico-cni-plugin-for-kubernetes-cluster-e6e63992486?source=rss-3f5cd3b0e6ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e63992486</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[calico]]></category>
            <category><![CDATA[cni]]></category>
            <dc:creator><![CDATA[Qua Zi Xian]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 14:37:06 GMT</pubDate>
            <atom:updated>2021-11-02T14:37:06.817Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is a quick summary of the information from the official Calico website. Mainly a consolidated note for myself, but if it helps you, it’s great too!</p><h3>Calico Installed using Calico/Tigera Operator</h3><p>This one is pretty straightforward. Follow the instructions <a href="https://docs.projectcalico.org/maintenance/kubernetes-upgrade#upgrading-an-installation-that-uses-the-operator">here</a> and it is done. As I have not tried it myself, I will update this post when I get the context and opportunity to try it out.</p><h3>Calico Installed using Manifest</h3><p>Essentially, follow <a href="https://docs.projectcalico.org/maintenance/kubernetes-upgrade#upgrading-an-installation-that-uses-manifests-and-the-kubernetes-api-datastore">this guide</a>. However, before you start, it is recommended to make a backup of the current manifest file, because you will need to transfer the changes made in this current manifest file into the new manifest file.</p><p>The changes to be brought over are the IPAM config in cni_network_config of calico-config ConfigMap, and the environment variable CALICO_IPV4POOL_CIDR.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e63992486" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>