<?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 Dhiman Halder on Medium]]></title>
        <description><![CDATA[Stories by Dhiman Halder on Medium]]></description>
        <link>https://medium.com/@dhimanhalder?source=rss-9a2534f46e45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X9vv1b0OWskVjH_i.</url>
            <title>Stories by Dhiman Halder on Medium</title>
            <link>https://medium.com/@dhimanhalder?source=rss-9a2534f46e45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:05:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhimanhalder/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[Build a Kubernetes Dynamic Admission Controller for Container Registry Whitelisting]]></title>
            <link>https://medium.com/@dhimanhalder/build-a-kubernetes-dynamic-admission-controller-for-container-registry-whitelisting-b46fe020e22d?source=rss-9a2534f46e45------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46fe020e22d</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[admission-controller]]></category>
            <category><![CDATA[amazon-eks]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Dhiman Halder]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 02:56:42 GMT</pubDate>
            <atom:updated>2021-01-20T02:56:42.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fNyL-DByIVAU3DrS" /><figcaption>Photo by <a href="https://unsplash.com/@teapowered?utm_source=medium&amp;utm_medium=referral">Patrick Robert Doyle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is a Kubernetes Admission Controller?</h3><p>Kubernetes admission controllers are plugins that act as gatekeepers by intercepting authenticated requests to the Kubernetes API server and processing them before any object data gets persisted to the etcd datastore.</p><p>The admission controllers can <em>mutate</em>/ change a request object (Mutating Admission Controllers) or allow/disallow a request (Validating Admission Controllers) and sometimes do both. The Mutating admission controllers get executed before the Validating admission controllers to allow the Validating admission controllers to act on any changes the Mutating admission controllers may have made to an incoming request. If any admission controller disallows a request, the entire request gets rejected, and an error message is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ie21guKxjoQHArtbFdg1SQ.png" /><figcaption>Admission Controller Phases — High Level</figcaption></figure><p>The <em>kube-apiserver </em>binary comes pre-compiled with more than 30 useful admission controllers (the <a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#what-does-each-admission-controller-do">entire list here</a>), some of which operate by default while the others can be enabled/ configured by the cluster administrator. In this list, there are two special “dynamic” controllers — the <strong><em>ValidatingAdmissionWebhook</em></strong> and the <strong><em>MutatingAdmissionWebhook</em></strong><em>. </em>These two controllers don’t implement any fixed logic; instead, they allow us the flexibility to implement and execute our custom logic via webhooks each time a Kubernetes resource gets created, updated, or deleted in our cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtLirGJa9B5v6OTRJ6pP1Q.png" /><figcaption>Admission Controller Phases — Detailed</figcaption></figure><h3>Why do we care about it?</h3><p>Admission Controllers can help improve the Security, Governance, Cost, and Configuration Management of a Kubernetes cluster. It can help organizations adhere to best practices, meet legal requirements, and enforce company policies on their Kubernetes cluster. For example, one may use the built-in <strong><em>PodSecurityPolicy</em></strong> admission controller to prevent containers from running as the root user or ensure the container root filesystem is mounted read-only. Similarly, the built-in <strong><em>LimitRanger</em></strong> admission controller can help enforce or add pod resource requests and limits. Custom admission controllers can help extend these functionalities further to realize additional use cases that may not be covered by built-in controllers like:</p><ul><li>Enforce or add specific labels or annotations to various objects. For example, each Pod must be assigned to a project or cost-center using annotations or must at the very least have an app label.</li><li>Allow container images from whitelisted/ corporate registries only while denying pulling from unknown image registries.</li><li>Ensure Pods in production are not using the <em>latest</em> tag.</li><li>Enforce a minimum number of replicas of a Deployment for High Availability.</li><li>Inject sidecar containers into Pods.</li></ul><h3>Sounds great? How do we build our own?</h3><p>I am glad that I got you interested in it. We will build an Admission Controller to demonstrate one of the use cases we discussed previously — to allow Pods to be created using container images from whitelisted registries only and deny pulling from untrusted image registries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tREWiIexzsM0m8jVjQvDfQ.png" /><figcaption>Use case — Do not allow Pods to be created when pulling from untrusted registries.</figcaption></figure><p>To accomplish the above use case, we will build a Validating Admission Controller and register it with our Kubernetes API Server. Before that, we need to first understand the structure of the request we will receive from the Kubernetes API server through a registered webhook, and what would be the structure of our response back to the Kubernetes API server. The Kubernetes API server uses an object of type <em>AdmissionReview</em> both for sending a request to our custom application and to receive a response. For every request, inside the top-level <em>AdmissionReview</em> structure, there is a <em>request</em> node of type <em>AdmissionRequest.</em> The <em>request</em> node encapsulates the details of the original request sent to the API server. Inside this <em>request</em> node, we are interested in the <em>object</em> field that contains the JSON payload of the Kubernetes object like a Pod, Deployment, etc., that is being created/ updated, or deleted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2d251a6e960eff0f2b6cbf057846544/href">https://medium.com/media/f2d251a6e960eff0f2b6cbf057846544/href</a></iframe><p>In the case of a Validating Admission Controller, our application has to receive an <em>AdmissionReview</em> object, process it to determine whether to allow/ disallow the request and return our decision by populating an <em>AdmissionReview</em> structure with a <em>response</em> node of type <em>AdmissionResponse</em> within it. Inside the <em>response</em> node, we convey our decision using the <em>allowed</em> boolean field. We optionally can also include an HTTP status <em>code</em> and a <em>message</em> to relay additional information back to the client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69457e32899d9ba3a479b81cc8d2603a/href">https://medium.com/media/69457e32899d9ba3a479b81cc8d2603a/href</a></iframe><p>If we are building a Mutating Admission Controller, we send back any mutations/ changes using a JSONPatch type object as part of the <em>response</em> node of the <em>AdmissionReview</em> response. The original request will be modified using this JSON patch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa248f35bd08ef8db69ebe1afaeb72bb/href">https://medium.com/media/fa248f35bd08ef8db69ebe1afaeb72bb/href</a></iframe><p>Here is the documentation to the entire structure of <em>AdmissionReview</em> for your reference — <a href="https://github.com/kubernetes/api/blob/master/admission/v1/types.go">https://github.com/kubernetes/api/blob/master/admission/v1/types.go</a></p><h3>Cluster Setup</h3><p>I will be using an Amazon EKS based Kubernetes cluster for this demo, but feel free to use any other Kubernetes distribution if you like. However, if you are using a different Kubernetes distribution, you may have to perform an added step to enable the <em>ValidatingAdmissionController</em> plugin on your Kubernetes cluster following the instructions <a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#how-do-i-turn-on-an-admission-controller">here</a>.)</p><p>Install and configure the aws cli, eksctl, kubectl, docker, OpenSSL, and Node.js locally on your computer to follow along with the rest of the article.</p><p>We create a brand new EKS cluster using the eksctl tool. It takes a few minutes to spin up the cluster. Once created, eksctl adds the cluster credentials in ~/.kube/config, so the kubectl tool is ready for immediate use.</p><pre><strong>&gt; eksctl create cluster</strong></pre><h3>Code Walkthrough</h3><p>Clone the repo <a href="https://github.com/dhiman-halder/whitelist-registry">https://github.com/dhiman-halder/whitelist-registry</a> to download the entire source code used in this article.</p><h4>app/server.js</h4><p>We have a Node.js application that will listen on port 443 for incoming HTTPS POST requests. In the POST method, we expect to receive an <em>AdmissionReview</em> object as an input. Our application will inspect the definition of the Pod that is being created. If any of the container images referenced in the pod spec does not reference one of the whitelisted registry names, our application will reject the request and return an error to disallow the operation; else, will allow it. The response is also wrapped in an <em>AdmissionReview</em> object. Our application reads the whitelisted registry names from an environmental variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f82af4f3891a41482fbe70e1846829ac/href">https://medium.com/media/f82af4f3891a41482fbe70e1846829ac/href</a></iframe><h4>gencerts.sh</h4><p>Our Node.js application, which will act as a server, must be exposed over HTTPS with a server certificate configured on it. The <em>gencerts.sh</em> script in the source code repo can generate the necessary TLS certificates and keys for it. As part of the script, we first establish a Certificate Authority (CA) to be able to self-sign our server certificate. We generate a CA private key and a CA certificate in PEM format. Next, we create a server-side private key. Then we build a Certificate Signing Request (CSR) with the Common Name (CN) <em>whitelist-registry.default.svc</em>. The Common Name (CN) indicates to a client that it can trust the server available on that DNS name. For Kubernetes API Server to call our server application, the common name (CN) on the server certificate must match the Kubernetes service name in the format <em>service.namespace.svc</em>, i.e., <em>whitelist-registry.default.svc</em> in our case. Finally, we create the server certificate in PEM format using the Certificate Signing Request and self-sign it using our CA key and CA certificate. We will not run our Node.js application container as the root user as a security best practice, hence we change file permission on the certificates and keys to allow a non-root unprivileged user to read them. We copy the CA certificate, the server certificate, and the server key to the app folder to bundle them inside the docker container image when it gets built.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab702ea6e274d51e84d9f04728f3b4b0/href">https://medium.com/media/ab702ea6e274d51e84d9f04728f3b4b0/href</a></iframe><h4>Dockerfile</h4><p>We will build our docker image from the Node 14 LTS version. We create a working directory to hold our application code, TLS certificates, and keys inside the image. We install the app dependencies using npm and bundle our app’s source code within the image. We bind our application to port 8443. Finally, we start our application using CMD instruction; and run the process as a non-root user as a security best practice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8255b86212a2dbcfd6057258359121f/href">https://medium.com/media/a8255b86212a2dbcfd6057258359121f/href</a></iframe><h4>webhook-deploy.yaml</h4><p>Here is the Deployment plus Service definition for deploying our containerized Node.js application to our Kubernetes cluster. We have externalized the set of whitelisted registries using an environment variable WHITELISTED_REGISTRIES that we configure on the Pod spec. The service must listen on 443 since it’s not configurable when used as a webhook service. You have to update the container image reference on the Pod spec in the template below to match yours before running it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bb48845f252dfa9d15e9993e94fc49e/href">https://medium.com/media/4bb48845f252dfa9d15e9993e94fc49e/href</a></iframe><h4>webhook-registration.yaml</h4><p>We will register our Node.js application as a Validating Admission Controller with our Kubernetes server using a Kubernetes object of kind <em>ValidatingWebhookAdmissionConfiguration</em>. If we were registering a Mutating Admission Controller instead, we would be using an object of kind <em>MutatingWebhookAdmissionConfiguration</em>. In this case, as shown below, we will name our webhook <em>com.foo.whitelist-registry;</em> it can be named anything as long as the name is unique across all the webhooks in the cluster. Under the rules section, we specify under what conditions this webhook gets invoked, in this case, we plan on calling our webhook only when a Pod is being created. Under the <em>ClientConfig</em> section, we will specify how the Kubernetes API Server can find our Node.js server application. We will expose our application through a service named <em>whitelist-registry</em> in the <em>default</em> namespace. The <em>caBundle </em>refers to a PEM encoded CA bundle that the Kubernetes API Server as a client can use to validate the server certificate on the Node.js application. Before registering this webhook, we will create a Base64 encoded version of the <em>ca.crt</em> file and replace the CA_BUNDLE placeholder with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4adaf53ce92adefb540fba3976171aa/href">https://medium.com/media/d4adaf53ce92adefb540fba3976171aa/href</a></iframe><h3>Build</h3><h4>Generate TLS Certificates and Keys</h4><p>We run the gencerts.sh script to generate and copy TLS certificates and keys.</p><pre>&gt; bash gencerts.sh</pre><h4>Build a Docker Container Image</h4><p>We will log in to Dockerhub, build our Docker container image locally, tag, and then push the image to Dockerhub using the below commands. Do adjust the Docker Account name in the commands below to match yours.</p><pre>&gt; docker login<br>&gt; docker build -t whitelist-registry:1.0 .<br>&gt; docker tag whitelist-registry:1.0 dhimanhalder/whitelist-registry:1.0<br>&gt; docker push dhimanhalder/whitelist-registry:1.0</pre><h4>Deploy Webhook Server Application</h4><p>We will deploy our Node.js application and expose it through a ClusterIP service. Do not forget to update the container image reference in the template to match your docker account name.</p><pre><strong>&gt; kubectl apply -f webhook-deploy.yaml</strong></pre><pre>service/whitelist-registry created<br>pod/whitelist-registry created</pre><h4>Register Webhook with Kubernetes API Server</h4><p>We create a Base64 encoded version of the <em>ca.crt</em> file and replace the CA_BUNDLE placeholder within the <em>webhook-registration.yaml</em> with it.</p><pre><strong>&gt; cat ca.crt | base64</strong></pre><pre>LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMyakNDQWNJQ0NRQ0dlUlJjZWI3...THVUQU5CZ2txaGtpRzl3MEJBUXNGQURBdk1TMHdLd1lEVlFRRERDUlgKYUdsMFpXeHBjM1FnVW1WbmFYTjBjbmtnUTI5VRFLS0tLS0K</pre><p>Finally, we will register the webhook with the Kubernetes API Server.</p><pre><strong>&gt; kubectl apply -f webhook-registration.yaml</strong></pre><pre>validatingwebhookconfiguration.admissionregistration.k8s.io/com.foo.whitelist-registry created</pre><h3>Test!</h3><p>We can test our <strong><em>Whitelist-Registry </em></strong><em>Validating Admission Controller</em> using two pod definitions included in our source code repo. The first one is <em>test-pod-1.yaml</em> which uses a container image from <em>docker.io</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3e160391a15bf457326154b08d29d2/href">https://medium.com/media/9a3e160391a15bf457326154b08d29d2/href</a></iframe><p>If we try to create a pod using this pod definition, our request is allowed since the container image comes from one of the “trusted” whitelisted registries! Note that one side effect to this Validating controller is that we must explicitly specify the <em>docker.io</em> registry host even when pulling from a docker public repo.</p><pre><strong>&gt; kubectl apply -f test-pod-1.yaml</strong></pre><pre>pod/test-pod-1 created</pre><p>Here is another example — <em>test-pod-2.yaml</em>. In this case, the container image comes from <em>xyz.io</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0558ca42c2829d8fe5a17ed62b56d2b4/href">https://medium.com/media/0558ca42c2829d8fe5a17ed62b56d2b4/href</a></iframe><p>If we try to create a pod using this pod definition, we get the below error message.</p><pre><strong>&gt; kubectl apply -f test-pod-2.yaml</strong></pre><pre>Error from server: error when creating &quot;test-pod-2.yaml&quot;: admission webhook &quot;com.foo.whitelist-registry&quot; denied the request: nginx image comes from an untrusted registry! (xyz.io/nginx:latest). Only images from docker.io,gcr.io are allowed.</pre><h3>Cleanup</h3><p>We deregister the webhook and delete the webhook server application.</p><pre><strong>&gt; kubectl delete -f webhook-registration.yaml</strong></pre><pre>validatingwebhookconfiguration.admissionregistration.k8s.io &quot;com.foo.whitelist-registry&quot; deleted</pre><pre><strong>&gt; kubectl delete -f webhook-deploy.yaml</strong></pre><pre>deployment.apps &quot;whitelist-registry&quot; deleted<br>service &quot;whitelist-registry&quot; deleted</pre><h3>Conclusion</h3><p>I hope you have enjoyed building your Admission controller for Kubernetes. While we can keep writing such controllers to realize different use cases, it is probably very inefficient since we have to write too much code. In the next post, we will be looking at the <a href="https://github.com/open-policy-agent/gatekeeper">Open Policy Agent Gatekeeper</a> project that provides a way to realize similar use cases through policy configurations instead of writing code.</p><h4>References</h4><ul><li><a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/">https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/</a></li><li><a href="https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/">https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/</a></li></ul><p><em>Found this article useful? Hit that clap button. Really like it? Hold the clap, give it two, or fifty! Follow Slalom Technology and read more articles on thought leadership in Technology.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46fe020e22d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trunk-based development Enabled by Kubernetes Accelerator]]></title>
            <link>https://medium.com/@dhimanhalder/trunk-based-development-enabled-by-kubernetes-accelerator-7a45069340ed?source=rss-9a2534f46e45------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a45069340ed</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[trunk-based-development]]></category>
            <category><![CDATA[amazon-eks]]></category>
            <dc:creator><![CDATA[Dhiman Halder]]></dc:creator>
            <pubDate>Wed, 06 May 2020 04:22:22 GMT</pubDate>
            <atom:updated>2020-05-06T04:22:22.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8r4O0f2xok-sIOTv" /><figcaption>Photo by <a href="https://unsplash.com/@vidarnm?utm_source=medium&amp;utm_medium=referral">Vidar Nordli-Mathisen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Containers enable us to build modern applications or package existing applications for increased portability and reduce environment drift. Container orchestrators like Kubernetes allow us to distribute the containers intelligently across our infrastructure, either in the cloud or on-premises. Furthermore, container orchestrators simplify deployment processes, ensure high availability, provide scaling capabilities, and may abstract capabilities from the application itself. This reduced overhead lets developers reclaim time and energy that can be spent on developing great products.</p><h3>Container Orchestrator</h3><p>Some of the benefits of a Container orchestrator like Kubernetes are:</p><p>· <strong>Maximize Compute Infrastructure — </strong>Container orchestrators intelligently schedule containers on machines to maximize the utilization of the host.</p><p>· <strong>Flexible Scaling — </strong>Applications can be scaled automatically by adjusting capacity.</p><p>· <strong>Automated High Availability — </strong>Container orchestrators provide high availability and resilience; if a node or host dies, the containers will automatically get rescheduled in another available node.</p><p>· <strong>Lower Risk Deployments — </strong>Not only do containers ensure that the code will work the same way in every environment, container orchestrators allow for rolling zero-downtime deployments.</p><h3>Why use Kubernetes?</h3><p>Kubernetes is the leading container orchestrator tool today. Kubernetes exhibits all the great qualities of a good container orchestrator, i.e., intelligent scheduling, self-healing, resilience, load balancing, rolling updates plus rollback, and horizontal scaling. Gartner estimates that by 2022, more than 75% of global organizations will be running containerized applications in production.</p><h3>Trunk-based development</h3><p>As more and more teams adopt trunk-based development, we wanted to unlock the potential of using trunk-based development on Kubernetes. We also wanted to reduce risk and increase productivity by making it easier for developers to test their feature branch changes before merging to trunk.</p><p>Trunk-based development is a branching model in which all branches extend from a single trunk or master branch and are merged back to the master after getting tested. The benefit of this development model is that it can help seasoned developers move quicker by doing smaller and frequent merges without having to deal with unnecessary bureaucracy. Since merges are applied to the master directly, the code is always production-ready. The flip side is, while this workflow provides a lot of autonomy, there is an inherent risk of introducing immature code or bug if proper code review and adequate testing are not performed. Hence it is imperative to quickly provision and provide every developer with a ‘shared-nothing’ isolated test environment to test each commit to their feature branch.</p><h3>Slalom Kubernetes Accelerator</h3><p>Many organizations adopting trunk-based development are faced with challenges like their developers not merging early and often. Getting environments stood up for demonstrating changes is also sometimes a long and arduous process. To solve these challenges, we came up with a simple solution. We provision and configure a Kubernetes cluster such that when a developer creates a new feature branch in the source code repository of an application, we automatically provision a new ephemeral and isolated test environment within the Kubernetes cluster. Then we deploy the feature branch to it to let the developer test out the changes made. When the feature branch eventually gets merged and deleted, we automatically clean up the test environment related to the branch and reclaim any resources allocated to it. We named this solution as the “Kubernetes Accelerator.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvuIynDAnCadZRv8y8nJ5w.png" /><figcaption>Focus area of the Kubernetes accelerator in the Software Development Life Cycle</figcaption></figure><h3>Developer experience</h3><p>The detailed developer workflow is described below:</p><p>1. A developer creates a new feature branch say <strong>feature-one</strong> in the source code repository</p><p>2. The developer makes code changes, commits and pushes the updated code to the new feature branch</p><p>3. A git repo webhook triggers an AWS CodeBuild job that builds a docker image from the feature branch and pushes the same to a private ECR docker registry</p><p>4. The “deploy” stage of the CI/CD process uses Helm to package and manage the deployment of the application to a new isolated <strong><em>namespace </em></strong>through a Kubernetes <strong><em>deployment </em></strong>using the freshly minted Docker image. Helm creates a new Kubernetes <strong><em>service</em></strong> to expose the application and an <strong><em>ingress</em></strong> object is provisioned within the namespace to allow incoming requests. Kubernetes <strong><em>network policies</em></strong> are created to enforce namespace boundaries.</p><p>5. The deployment takes 2–5 minutes after which the developer can access the application at <a href="https://www.example.com/feature-one">https://www.domain.com/feature-one</a></p><p>6. Any subsequent commits to the same branch will just update the underlying docker image of the deployment and not create a whole new environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLyaDwFxRwH1PjqCWdxhOQ.png" /><figcaption>CI/CD workflow of the Kubernetes Accelerator</figcaption></figure><h3>Under the hood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk3S-XseRB_tsOpfsf8oxw.png" /><figcaption>The accelerator is powered by Amazon EKS</figcaption></figure><p>Our Kubernetes cluster runs on Amazon EKS, which is AWS’s managed Kubernetes platform. Amazon EKS makes it easy to run Kubernetes on AWS without the need to provision or maintain our Kubernetes control plane. We use the tool <strong>eksctl</strong> in an AWS CodeBuild pipeline to provision the Kubernetes cluster with a few other goodies as detailed below:</p><p><strong>·</strong> <strong>NGINX Ingress Controller</strong> allows us to expose http and https routes from outside the cluster to applications within the cluster. The Ingress controller uses an external load balancer, and, in our case, we decided to use the Network Load Balancer (NLB). There are many benefits to using an NLB in contrast to an Application Load Balancer (ALB). One advantage is that a single NLB can be shared across feature branches, unlike that of an ALB, which needs to be provisioned separately for every feature branch and that can get pretty costly if you have a large number of feature branches. Refer to this link to read through all the other advantages of using an NLB over ALB — <a href="https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/">https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/</a></p><p>· <strong>ExternalDNS</strong> helps automatically synchronize our external DNS provider, which is Route53, with exposed Kubernetes services and ingress objects running within the EKS cluster.</p><p>· <strong>Calico Network Policy Engine</strong> helps us isolate traffic within and across namespaces through network policies to secure the test environments.</p><p>· <strong>EKS CloudWatch Container Insights</strong> collects, aggregates, and summarizes operational metrics and logs from the deployed applications</p><p>· <strong>IAM Roles for Service Accounts (IRSC)</strong> to enforce fine-grained IAM roles for Service Accounts running Pods, which is a security best practice.</p><h3>Trivia</h3><p>· We use a TLS certificate provisioned through the AWS Certificate manager on the listener of the NLB for our HTTPS traffic. We terminate HTTPS at the NLB instead of terminating it within the cluster to simplify things. An annotation <em>service.beta.kubernetes.io/aws-load-balancer-ssl-cert</em> configured with the ARN of the certificate on the NGINX ingress controller’s service allows it to configure the HTTPS listener on the NLB appropriately.</p><p>· We intentionally avoided creating new Route53 records for every new feature-branch because DNS propagation takes several minutes, so instead of using a subdomain per feature with URL such as <em>feature.domain.com</em>, we opted for a path-based URL instead, i.e., <em>domain.com/feature</em>. We set another annotation to rewrite the URL — <em>ingress.kubernetes.io.rewrite-target</em> to “/” in the Ingress objects to keep it transparent to the application.</p><h3>Clean-up</h3><p>After a developer merges a feature branch back to the master branch and deletes the feature branch, a nightly job triggered by an AWS CloudWatch rule fires another AWS CodeBuild job that deletes the feature branch’s namespace and any other Kubernetes artifacts related to it. This clean-up job also deletes any docker images of the feature branch from the ECR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Epj4H9ONbeLKSoKnznFg5w.png" /><figcaption>Nightly cleaner</figcaption></figure><h3>The beginning</h3><p>We have few other enhancements lined up like the introduction of a <strong>Cluster Autoscaler</strong> to add/ remove additional worker Nodes dynamically, log aggregation using <strong>Fluentd</strong>, <strong>Elasticsearch</strong> and <strong>Kibana</strong>, securing secrets with <strong>SealedSecrets</strong> and a service mesh like <strong>Istio</strong> or <strong>AWS App Mesh</strong>. Based on some recent Customer interests, there are also plans to port the accelerator solution to other flavors of Kubernetes!</p><p><strong>Written by:</strong> Dhiman Halder, with inputs from Jon Perkins, Matt Mousseau, Edgar Sanchez, RJ Jafarkhani, Todd Klitzner, and David Smith.</p><p><em>Found this article useful? Hit that clap button. Really like it? Hold the clap, give it two, or fifty! Follow Slalom Technology and read more articles on thought leadership in Technology.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a45069340ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I ran an inexpensive ‘sandbox’ multi-node Kubernetes cluster on AWS using EC2 Spot Instances…]]></title>
            <link>https://medium.com/@dhimanhalder/how-i-ran-an-inexpensive-sandbox-multi-node-kubernetes-cluster-on-aws-using-ec2-spot-instances-238c74f163bf?source=rss-9a2534f46e45------2</link>
            <guid isPermaLink="false">https://medium.com/p/238c74f163bf</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[spot-instances]]></category>
            <dc:creator><![CDATA[Dhiman Halder]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 05:43:52 GMT</pubDate>
            <atom:updated>2019-12-26T21:17:32.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I ran an inexpensive ‘sandbox’ multi-node Kubernetes cluster on AWS using EC2 Spot Instances for 1¢ per hour!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KNz7qqTseLqwzzEg" /><figcaption>Photo by <a href="https://unsplash.com/@jbrinkhorst?utm_source=medium&amp;utm_medium=referral">Jonathan Brinkhorst</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Overview</strong></h3><p>While preparing for my CKA &amp; CKAD certification exams, I wanted to build a solution to create ephemeral, ultra low-cost ‘sandbox’ Kubernetes clusters that could be spun-up and dismantled quickly. I did not want to use a solution like Minikube locally since that would only let me create single-node clusters. I required access to a true multi-node cluster environment to practice topics like Kubernetes cluster upgrades &amp; maintenance.</p><h3><strong>AWS Spot Instances</strong></h3><p>To keep costs down, I looked at AWS Spot Instances to build my ‘sandbox’ cluster. EC2 Spot Instances are unused EC2 instances which are sometimes available at up to 90% discount compared to On-Demand EC2 instances. The downside of Spot Instances is AWS can terminate Spot Instances with little to no warning. Since resiliency was not a primary driver, I was not very concerned if the Spot instances in my cluster got terminated suddenly; as long I had a way to spin up another one quickly without too much effort. Hence, I resorted to CloudFormation to create a re-usable script that I could run and provision an entire cluster within couple of minutes.</p><h3><strong>The CloudFormation script k8s-spot.yaml</strong></h3><p>The entire CloudFormation script is shared at <a href="https://github.com/dhiman-halder/k8s-aws-spot"><strong>https://github.com/dhiman-halder/k8s-aws-spot</strong></a></p><p><a href="https://raw.githubusercontent.com/dhiman-halder/k8s-aws-spot/master/k8s-spot.yaml">https://raw.githubusercontent.com/dhiman-halder/k8s-aws-spot/master/k8s-spot.yaml</a></p><p>The CloudFormation Script provisions the following AWS resources in <strong><em>us-east-1</em></strong>:</p><ol><li>A VPC with 1 public subnet, an Internet Gateway, a Public Route and a Security Group</li><li>1 <strong>t3a.small</strong> EC2 Spot Instance for master node (2 vCPU, 2 GiB memory) running Ubuntu 16.04. While the current <strong>On-Demand pricing</strong> is <strong>$0.0188</strong> per hour, the <strong>Spot</strong> <strong>price</strong> is just <strong>$0.0056</strong> at the moment- which is close to <strong>70% discount</strong> compared to On-Demand price!</li><li>1 <strong>t3a.micro</strong> EC2 Spot Instance for worker node (2 vCPU, 1 GiB memory) running Ubuntu 16.04. The current <strong>On-Demand price</strong> is <strong>$0.0094 </strong>per hour and the <strong>Spot price</strong> is <strong>$0.0028</strong>- again a <strong>70% discount</strong>!</li><li>Each EC2 Instance is paired with 1 8GB SSD EBS volume. The per hour cost for each volume is <strong>$0.0011</strong></li><li>IAM role for the Spot Fleet</li></ol><p>The Cluster is bootstrapped using <strong>Kubeadm</strong> through the UserData script as part of the EC2 provisioning process. The shell script does the following:</p><p><strong>On the Master node:</strong></p><ol><li>Set the hostname to master</li><li>Turn-off SWAP</li><li>Install and run Docker as the Container Runtime Engine</li><li>Install Kubeadm, Kubelet &amp; Kubectl tools</li><li>Start the Kubelet service</li><li>Use Kubeadm to initialize the cluster on the master</li><li>Setup KubeConfig on the master</li><li>Install Calico as the pod network add-on</li><li>Create a join.txt file on the user’s root with a Kubeadm command to let the worker node join the Kubernetes cluster</li></ol><p><strong>On the Worker node:</strong></p><ol><li>Set the hostname to node01</li><li>Turn-off SWAP</li><li>Install and run Docker as the Container Runtime Engine</li><li>Install Kubeadm, Kubelet &amp; Kubectl tools</li><li>Start the Kubelet service</li></ol><p>The UserData scripts follows the Kubernetes official guide as documented here: <br><a href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/">https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/</a></p><h3><strong>Run the CloudFormation Script</strong></h3><p>You can run the CloudFormation script either using the AWS CLI or the AWS Management console. You need to supply an EC2 KeyPair for SSH access into the EC2 Instances.</p><h4><strong>Manual Step</strong></h4><p>Once the EC2 instances are provisioned and running:</p><ol><li>SSH into the master node &amp; copy the Kubeadm join command from within the join.txt file on the user’s root</li><li>SSH into the worker node and execute the copied command to join the worker node to the cluster.</li></ol><h3><strong>Testing</strong></h3><ol><li>From the master node, run <strong><em>kubectl get nodes</em></strong> -this should list the 2 nodes and they should be in <strong>Ready</strong> state!</li><li>Run <strong><em>kubectl run nginx --image=nginx --restart=Never</em></strong> followed by <strong><em>kubectl get pods</em></strong> to list the newly created nginx pod</li></ol><h3><strong>Clean-up!</strong></h3><p>Delete the created CloudFormation stack to tear down the cluster!</p><h3><strong>Conclusion</strong></h3><p>Ignoring any data transfer cost, the current cost of running the 2 EC2 Spot Instances along with their EBS volumes is just <strong>$0.0056+$0.0028+$0.0011+$0.0011=$0.0106 </strong>which is ~<strong>1</strong>¢ per hour. Essentially, for <strong>$1</strong>, the environment could be run for <strong>~4 days!</strong> This is of-course assuming the average spot price during the period do not deviate substantially.</p><p><strong>Thanks for Reading!</strong></p><p>Found this article useful? Hit that clap button. Really like it? Hold the clap, give it two, or fifty!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238c74f163bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>