<?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 Utkarsh Singh on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Singh on Medium]]></description>
        <link>https://medium.com/@usvisen2000?source=rss-43e9c006e4a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UvbPXXrXK_tMxtr-</url>
            <title>Stories by Utkarsh Singh on Medium</title>
            <link>https://medium.com/@usvisen2000?source=rss-43e9c006e4a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:10:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usvisen2000/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[Automating AWS Resource Management with Custom Providers in Kubernetes]]></title>
            <link>https://medium.com/inspiredbrilliance/automating-aws-resource-management-with-custom-providers-in-kubernetes-56e771cea4e2?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e771cea4e2</guid>
            <category><![CDATA[crossplane]]></category>
            <category><![CDATA[custom-provider]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 11:16:13 GMT</pubDate>
            <atom:updated>2025-01-28T05:14:38.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nT-H1MmfsvzTIgrHmGlIQ.jpeg" /></figure><p>In the <a href="https://medium.com/@usvisen2000/understanding-custom-resource-definitions-crds-in-kubernetes-604f04b23c8c">previous blog</a>, we explored the concept of <strong>Custom Resource Definitions (CRDs)</strong> in Kubernetes. We saw how CRDs make it possible to deploy AWS resources like S3 buckets, Lambda functions, and Step Functions directly from Kubernetes. This makes managing cloud resources smooth and Kubernetes-centric.</p><p>But here’s a question:</p><ul><li><strong>What if the template for a specific resource or functionality you need is not available in Crossplane?</strong></li><li><strong>What if you want to integrate a feature that Crossplane does not support out of the box?</strong></li></ul><p>This blog will dive into how you can address these challenges by <strong>building a custom Crossplane provider</strong>. I will take you through the process of creating a provider that connects AWS S3 event driven capabilities with workflows.</p><h4>When Should You Create a Custom Provider?</h4><p>Here are two common scenarios:</p><ol><li><strong>Unsupported Resources</strong>: Crossplane does not support certain services or resources in a cloud provider.</li><li><strong>Custom Requirements</strong>: You need additional functionality, like custom APIs or logic, that is not available in standard providers.</li></ol><p>In these cases, creating a <strong>Custom Provider</strong> lets you fill the gaps and manage resources or workflows that Crossplane does not natively support.</p><h4>Recap: What Makes Crossplane Special?</h4><p>Crossplane turns Kubernetes into a <strong>universal control plane</strong>. With Crossplane, you can manage not just Kubernetes resources but also external cloud services (like AWS, GCP, Azure, etc.) using the same declarative approach.</p><p>Key Benefits of Crossplane:</p><ul><li><strong>Provisioning</strong>: Use CRDs to deploy and manage resources like S3 buckets, Lambda Functions, Step Functions, etc.</li><li><strong>Infrastructure as Code</strong>: Maintain consistency by defining your infrastructure in code.</li></ul><p>But while Crossplane is powerful, it does not support every resource or feature natively. That is where <strong>custom providers</strong> come in.</p><h3>Example Scenario: Automating Kubernetes Workflows with AWS S3 Events and Step Functions</h3><p>Let’s say you want to trigger a step function workflow in Kubernetes whenever a file is uploaded to an s3 bucket. To do this, you need to connect S3 event notifications with AWS Step Functions. We will create custom provider to trigger aws step function when a file is uploaded to s3 bucket.</p><h4>Why Not Use Crossplane’s Built-In Support?</h4><p>While Crossplane’s AWS provider allows you to provision and manage S3 buckets, it does not directly support event-driven workflows like triggering Step Functions based on S3 events.</p><p>For example:</p><ul><li>S3 event notifications can trigger AWS services such as Lambda, SNS, or SQS.</li><li>There is no native way to directly trigger workflows, such as Step Functions, from these events.</li></ul><p>If your infrastructure is Kubernetes-first, you will need a custom solution to fill this gap. Since Crossplane does not provide out of the box support for such integrations, we will create a custom provider that connects S3 events to Step Functions.</p><h3>Step 1: Define the Custom Resource</h3><p>Create a new CRD that represents the integration between S3 event notifications and step function workflows.</p><pre># s3stepfunctionbucket-crd.yaml<br>apiVersion: apiextensions.k8s.io/v1<br>kind: CustomResourceDefinition<br>metadata:<br>  name: s3stepfunctionbuckets.awsresources.io<br>spec:<br>  group: awsresources.io<br>  names:<br>    kind: S3StepFunctionBucket<br>    listKind: S3StepFunctionBucketList<br>    plural: s3stepfunctionbuckets<br>    singular: s3stepfunctionbucket<br>  scope: Namespaced<br>  versions:<br>  - name: v1<br>    served: true<br>    storage: true<br>    schema:<br>      openAPIV3Schema:<br>        type: object<br>        properties:<br>          spec:<br>            type: object<br>            properties:<br>              bucketName:<br>                type: string<br>              eventType:<br>                type: string<br>              stepFunctionArn:<br>                type: string</pre><p>This defines the structure of the custom resource (S3StepFunctionBucket) and allows Kubernetes to recognize it.. It creates a new custom resource called <strong><em>S3StepFunctionBucket</em></strong> that allows users to define:</p><ol><li><strong>bucketName</strong>: The S3 bucket to monitor.</li><li><strong>stepFunctionArn</strong>: The ARN of the Step Function to trigger.</li><li><strong>eventType</strong>: The S3 event (e.g., s3:ObjectCreated:* or s3:ObjectRemoved:*) that triggers the Step Function.</li></ol><p>Save the file and apply it to your Minikube cluster:</p><pre>kubectl apply -f s3stepfunctionbucket-crd.yaml</pre><h3>Step 2: Creating a Custom Resource</h3><p>Let’s create a sample instance of our custom resource:</p><pre># s3stepfunctionbucket.yaml<br>apiVersion: awsresources.io/v1<br>kind: S3StepFunctionBucket<br>metadata:<br>  name: example-s3-bucket<br>spec:<br>  bucketName: &quot;example-bucket&quot;<br>  eventType: &quot;s3:ObjectCreated:*&quot;<br>  stepFunctionArn: &quot;arn:aws:states:us-east-1:123456789012:stateMachine:example&quot;</pre><p>Apply the resource to your cluster:</p><pre>kubectl apply -f s3stepfunctionbucket.yaml</pre><h3>Step 3: Implement the Controller Logic</h3><p>The core of your custom provider is the controller that manages the lifecycle of the resource.</p><p>This controller will:</p><ol><li>Create an s3 bucket using the AWS SDK.</li><li>Configure event notifications to link the S3 bucket to the specified Step Function.</li></ol><h4>Step 3.1: Setting Up the Kubernetes Client</h4><p>The first step is to connect to the Kubernetes cluster. We configure the client to work both locally (using <em>~/.kube/config</em>) and inside the cluster (using the in-cluster configuration):</p><pre>// main.go<br>var kubeconfig string<br>if home := homedir.HomeDir(); home != &quot;&quot; {<br> kubeconfig = filepath.Join(home, &quot;.kube&quot;, &quot;config&quot;)<br>}<br><br>config, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)<br>if err != nil {<br> fmt.Println(&quot;Falling back to in-cluster config&quot;)<br> config, err = rest.InClusterConfig()<br> if err != nil {<br>  panic(err.Error())<br> }<br>}</pre><h4>Step 3.2: Defining the Custom Resource</h4><p>To manage the <strong><em>S3StepFunctionBucket</em></strong> custom resource, we define its <strong>GroupVersionResource (GVR)</strong>:</p><pre>s3StepFunctionBucket := schema.GroupVersionResource{<br> Group:    &quot;awsresources.io&quot;,<br> Version:  &quot;v1&quot;,<br> Resource: &quot;s3stepfunctionbuckets&quot;, // Plural form of the CRD<br>}</pre><p>This tells the Kubernetes client how to locate our custom resource.</p><h4>Step 3.3: Creating an Informer</h4><p>An <strong>Informer</strong> is used to watch for changes to Kubernetes resources (Add, Update, Delete events). We create an informer for <strong><em>S3StepFunctionBucket</em></strong>:</p><pre>informer := cache.NewSharedIndexInformer(<br> &amp;cache.ListWatch{<br>  ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {<br>   return dynClient.Resource(s3StepFunctionBucket).Namespace(&quot;&quot;).List(context.TODO(), options)<br>  },<br>  WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {<br>   return dynClient.Resource(s3StepFunctionBucket).Namespace(&quot;&quot;).Watch(context.TODO(), options)<br>  },<br> },<br> &amp;unstructured.Unstructured{},<br> 0,                            <br> cache.Indexers{},<br>)</pre><p>Here’s what happens:</p><ul><li><strong>ListFunc:</strong> Lists the current state of the resource.</li><li><strong>WatchFunc:</strong> Watches for future changes to the resource.</li><li>We use <em>unstructured.Unstructured</em> because the custom resource’s schema is unknown to the Go client.</li></ul><h4>Step 3.4: Adding Event Handlers</h4><p>We attach handlers to the informer to handle <strong>Add</strong>, <strong>Update</strong>, and <strong>Delete</strong> events. Each handler logs the spec field of the resource</p><pre>informer.AddEventHandler(cache.ResourceEventHandlerFuncs{<br> AddFunc: func(obj interface{}) {<br>  fmt.Println(&quot;Add event detected:&quot;)<br>  printCustomResourceSpec(obj)<br> },<br> UpdateFunc: func(oldObj, newObj interface{}) {<br>  fmt.Println(&quot;Update event detected:&quot;)<br>  printCustomResourceSpec(newObj)<br> },<br> DeleteFunc: func(obj interface{}) {<br>  fmt.Println(&quot;Delete event detected:&quot;)<br>  printCustomResourceSpec(obj)<br> },<br>})</pre><p>The printCustomResourceSpec function extracts and logs the spec field:</p><pre>func printCustomResourceSpec(obj interface{}) {<br> unstructuredObj := obj.(*unstructured.Unstructured)<br> spec := unstructuredObj.Object[&quot;spec&quot;]<br> fmt.Printf(&quot;Custom Resource spec: %v\n&quot;, spec)<br>}</pre><blockquote>For simplicity, in this example, I have just used <strong>basic log statements</strong> in each event handler (Create, Update, Delete) to demonstrate how the controller interacts with Kubernetes Custom Resources (CRs).</blockquote><blockquote>In a real-world scenario, you would replace these logs with actual logic, such as using the <strong>AWS SDK to create an S3 bucket, configure event notifications to trigger a Step Function,</strong> or clean up resources when they are deleted.</blockquote><blockquote>The core purpose of this example is to show how to handle events in a controller, while in practice, you need to implement resource management and error handling using the relevant APIs.</blockquote><h4>Step 3.5: Running the Informer</h4><p>Finally, we start the informer and wait for it to sync:</p><pre>stop := make(chan struct{})<br>defer close(stop)<br><br>go informer.Run(stop)<br><br>if !cache.WaitForCacheSync(stop, informer.HasSynced) {<br> panic(&quot;Timeout waiting for cache sync&quot;)<br>}<br><br>fmt.Println(&quot;Custom Resource Controller started successfully&quot;)<br>&lt;-stop</pre><p>You can find the complete file here.</p><h3>Step 4: Running the Controller</h3><ul><li><strong>Initialize the Go module and download dependencies:</strong></li></ul><pre>go mod tidy<br>go get k8s.io/client-go@v0.27.1<br>go get k8s.io/apimachinery@v0.27.1</pre><ul><li><strong>Build and run the controller locally:</strong></li></ul><pre>go run main.go</pre><h3>Step 4: Test the Controller</h3><h4><strong>Add Event</strong></h4><p>When the <strong><em>example-bucket</em></strong> resource is created, you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TH0oX7qK0EUt2Q7muQG7w.png" /></figure><h4><strong>Update Event</strong></h4><p>Update the custom resource, update any field in the <strong><em>spec</em></strong>:</p><pre>kubectl edit s3stepfunctionbucket example-bucket</pre><pre>apiVersion: awsresources.io/v1<br>kind: S3StepFunctionBucket<br>metadata:<br>  name: example-bucket<br>spec:<br>  bucketName: &quot;my-s3-bucket&quot;<br>  eventType: &quot;s3:ObjectRemoved:*&quot; # Changed to ObjectRemoved from ObjectCreated<br>  stateMachineName: &quot;my-step-function&quot;</pre><p>Apply the changes:</p><pre>kubectl apply -f s3stepfunctionbucket.yaml</pre><p>You should see an “Update event detected” log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpwWoFYYF9_Z-97yMCqu-w.png" /></figure><h4>Delete Event</h4><p>Delete the custom resource:</p><pre>kubectl delete s3stepfunctionbucket example-bucket</pre><p>You should see a “Delete event detected” log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4o2UNTb7oX3UnPOtH0xOhg.png" /></figure><h3>Conclusion</h3><p>Wrapping up our dive into Kubernetes custom controllers, it’s clear that this journey has only scratched the surface of what is achievable. We have explored building a basic Kubernetes custom controller to handle create, update, and delete events for a custom resource. Using the client-go library, we set up event listeners and simple logging for resource changes. While the example was kept simple, in real-world applications, this logic would integrate with services like AWS SDK to automate tasks like creating resources or triggering events..</p><p>Happy Learning! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e771cea4e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/automating-aws-resource-management-with-custom-providers-in-kubernetes-56e771cea4e2">Automating AWS Resource Management with Custom Providers in Kubernetes</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Custom Resource Definitions (CRDs) in Kubernetes]]></title>
            <link>https://medium.com/inspiredbrilliance/understanding-custom-resource-definitions-crds-in-kubernetes-604f04b23c8c?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/604f04b23c8c</guid>
            <category><![CDATA[crossplane]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-crds]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 10:29:35 GMT</pubDate>
            <atom:updated>2025-01-28T05:14:32.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xE-s-oCPTL-DW28egzbj-A.jpeg" /></figure><p>Kubernetes is a powerful platform for orchestrating and managing containers, offering a comprehensive set of resources like Pods, Deployments, and Services to handle common use cases. But as your applications grow in complexity, what if<strong> </strong>the default resources aren’t enough to meet your needs? For example:</p><ul><li><strong>What if you want to manage cloud services like AWS Lambda functions, SQS queues, or SNS topics right from Kubernetes?</strong></li><li><strong>Or what if you want to automate workflows using AWS Step Functions but prefer to stay within the Kubernetes environment?</strong></li></ul><p>Sounds tricky, right? Well, that’s where <strong>Custom Resource Definitions</strong>, or CRDs, comes to the rescue.</p><h3>What Are Custom Resource Definitions (CRDs)?</h3><p>CRDs allow you to extend Kubernetes by defining your own resource types. These custom resources work just like Kubernetes native resources, such as pods or services, but are specifically designed to meet your unique needs.</p><h4>Why Are CRDs Useful?</h4><ul><li>You can use them to extend Kubernetes to do things it normally can’t, like managing external cloud services or handling unique workflows.</li><li>They behave just like regular Kubernetes resources, so you can create, update, or delete them using the Kubernetes API.</li></ul><h4>Example Time!</h4><p>Let’s say your app uses AWS Lambda functions, and you want to manage those functions right from Kubernetes environment to keep everything consistent. With a CRD for AWS Lambda, you can deploy and manage those functions alongside your Kubernetes workloads.</p><p>But here’s the big question:<br>How can you manage cloud resources like AWS Lambda, SQS, or SNS directly in Kubernetes <em>without</em> needing tools like Terraform or Pulumi?</p><p>This is where Crossplane comes in!</p><h3>How Does Crossplane Help?</h3><p>Crossplane brings cloud resource management directly into Kubernetes. This means you can manage things like Lambda Functions, SQS, Step Functions, etc in the same way you manage Kubernetes applications, making it easier to handle resources across multiple clouds.</p><ul><li><strong>Crossplane and AWS Provider</strong>: Crossplane communicates with AWS through the AWS provider. This provider acts as a bridge, allowing your Kubernetes cluster to interact with AWS resources. It introduces <strong>Custom Resource Definitions (CRDs)</strong> for various AWS services like S3 buckets, Lambda functions, and RDS instances.</li><li><strong>Reconciliation</strong>: Crossplane continuously monitors the <strong>desired state</strong> defined in your Kubernetes manifests and reconciles it with the <strong>actual state</strong> in AWS. If any changes occur in AWS (like manual deletion of resources), Crossplane ensures that the system corrects the changes to match the desired state you defined.</li></ul><h4>How Crossplane Works with the AWS Provider</h4><p>Let’s break down how Crossplane works step by step:</p><p><strong>1. Install the Cloud Provider</strong></p><ul><li>Use the following command to install the AWS provider:</li></ul><pre>kubectl crossplane install provider crossplane/provider-aws:v0.23.0</pre><ul><li>Verify that the provider is installed:</li></ul><pre>kubectl get providers</pre><p>When you install the AWS provider in your Kubernetes cluster, Crossplane registers CRDs like <strong><em>S3Bucket</em></strong>, <strong><em>Lambda</em></strong>, SQS, and various other AWS services. These CRDs act as templates for declaring and managing AWS resources directly within Kubernetes.</p><p><strong>2. Configure the Provider</strong> After installing the provider, configure its credentials to allow Crossplane to authenticate with the cloud API. For AWS, this involves creating a <strong><em>ProviderConfig</em></strong>.</p><ul><li>Example configuration file:</li></ul><pre>apiVersion: aws.crossplane.io/v1alpha1<br>kind: ProviderConfig<br>metadata:<br>  name: aws-provider-config<br>spec:<br>  credentials:<br>    source: Secret<br>    secretRef:<br>      namespace: crossplane-system<br>      name: aws-creds<br>      key: creds</pre><ul><li>Apply the configuration:</li></ul><pre>kubectl apply -f providerconfig.yaml</pre><p><strong>3. Define Resources</strong> Using CRDs, you need to create Kubernetes manifests to define your AWS resources declaratively. For example, the <strong><em>S3Bucket</em></strong> manifest defines the desired state of an S3 bucket, including its name, region, and configurations such as CORS:</p><ul><li>Define the resource in a YAML manifest:</li></ul><pre>apiVersion: aws.crossplane.io/v1alpha1<br>kind: S3Bucket<br>metadata:<br>  name: my-s3-bucket<br>spec:<br>  forProvider:<br>    region: us-west-2<br>    bucketName: my-unique-bucket-name<br>  providerConfigRef:<br>    name: aws-provider-config</pre><ul><li>Apply the manifest:</li></ul><pre>kubectl apply -f s3bucket.yaml</pre><p><strong>4. Manage via API Calls</strong> Crossplane does not directly deploy resources within the Kubernetes cluster. Instead, it leverages AWS APIs to create, update, and delete resources in AWS based on your YAML definitions. The credentials provided in the <strong><em>ProviderConfig</em></strong> are used to authenticate Crossplane with AWS and interact with AWS services securely. Once resources are defined, you can manage them using Kubernetes commands.</p><ul><li>Check the status of your resource:</li></ul><pre>kubectl get s3bucket</pre><ul><li>Update or delete resources as needed:</li></ul><pre>kubectl edit s3bucket my-s3-bucket <br>kubectl delete s3bucket my-s3-bucket</pre><p><strong>5. State Comparison and Reconciliation</strong>: Crossplane continuously compares the <strong>desired state</strong> in your Kubernetes manifests with the <strong>actual state</strong> in AWS. If there is any discrepancy, such as a resource being manually deleted or changed, Crossplane triggers the reconciliation process to ensure the actual state matches the desired state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*362OAtTjvknqotT7pGFosg.png" /></figure><h4>How Crossplane Helps with Multi-Cloud Resource Management</h4><p>Crossplane also shines when you need to manage resources across multiple cloud providers. Whether you’re working with <strong>AWS</strong>, <strong>GCP</strong>, or <strong>Azure</strong>, you can use Crossplane to define and manage resources in a unified, declarative manner.</p><p>Each cloud provider has its own set of controllers and CRDs that manage its respective resources. For example:</p><ul><li>The <strong>AWS provider</strong> enables you to manage resources like S3, Lambda, RDS, and more.</li><li>The <strong>GCP provider</strong> helps you manage GCP-specific resources like Compute Engine, Cloud Storage, and Cloud SQL.</li><li>The <strong>Azure provider</strong> allows you to manage Azure resources like Virtual Machines, Azure Storage, and Azure Databases.</li></ul><p>By using Crossplane, you can manage these resources from within a Kubernetes cluster, making it easier to handle your multi-cloud infrastructure in one place.</p><h4>Where to Find Templates for Crossplane</h4><p>1. <a href="https://marketplace.upbound.io/">Upbound Marketplace</a></p><p>2. <a href="https://github.com/crossplane/crossplane">Crossplane GitHub Repository</a></p><p>3. <a href="https://github.com/upbound">Upbound GitHub Repository</a></p><h3>Handling Limitations: When Crossplane Doesn’t Meet Your Needs</h3><p>What if you need to create a resource or feature that is not available in Crossplane’s built-in templates? For example, what if you want s3 bucket or Lambda resource to trigger an AWS Step Function, but Crossplane does not currently support this integration? How can you extend Crossplane to meet these specific needs? This is where custom providers come in, which I will be discussing in my <a href="https://medium.com/@usvisen2000/automating-aws-resource-management-with-custom-providers-in-kubernetes-56e771cea4e2">next blog.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=604f04b23c8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/understanding-custom-resource-definitions-crds-in-kubernetes-604f04b23c8c">Understanding Custom Resource Definitions (CRDs) in Kubernetes</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Kubernetes: A Beginner’s Roadmap to Understanding Key Concepts]]></title>
            <link>https://medium.com/inspiredbrilliance/navigating-kubernetes-a-beginners-roadmap-to-understanding-key-concepts-8362558c10b6?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8362558c10b6</guid>
            <category><![CDATA[kubernetes-crds]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[pods]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 10:58:56 GMT</pubDate>
            <atom:updated>2025-01-28T05:14:20.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xE-s-oCPTL-DW28egzbj-A.jpeg" /></figure><p>In my journey of diving into the world of Kubernetes, I vividly remember the initial excitement quickly turning into confusion. The promise of simplifying container orchestration sounded amazing, but as I started exploring, I found myself grappling with concepts that didn’t make sense at first glance.</p><p>One of the trickiest parts for me and for many beginners was understanding Pods and some Kubernetes terms. From figuring out how they work, to why my YAML files weren’t behaving as expected, there were moments when I felt completely lost.</p><p>If you’ve ever asked yourself questions like:</p><ul><li><em>What exactly is the relationship between Pods and containers?</em></li><li><em>What is a service?</em></li><li><em>What’s an API controller?</em></li><li><em>What are Ingress and Ingress Controllers?</em></li></ul><p>…then you’re not alone! I’ve been there, and this blog is here to help you avoid those same headaches. Let’s break down <strong>10 Kubernetes concepts</strong> that often confuse beginners and demystify them with clear explanations.</p><h3>1. Pods vs. Containers</h3><p><strong>The Confusion</strong>: Many people new to Kubernetes often assume that a Pod is the same as a container. This is understandable because containers are the basic building blocks of applications in Kubernetes. However, this assumption can lead to confusion when you start working with Pods.</p><p><strong>The Reality</strong>:<br>A <a href="https://kubernetes.io/docs/concepts/workloads/pods/"><strong>Pod</strong></a> is a higher-level abstraction in Kubernetes that can contain one or more containers. In Kubernetes, a <strong>container</strong> is a runtime environment where an application runs, while a Pod is the smallest deployable unit in Kubernetes that encapsulates one or more containers. All the containers inside a Pod are guaranteed to share certain resources like network and storage, and they can communicate with each other over <strong><em>localhost</em></strong>.</p><p>To make this clearer, think of a <strong>Pod</strong> as a <strong>“wrapper”</strong> around one or more tightly coupled containers that need to work closely together. You can think of it as a “box” that holds containers, and this box is useful when you have related tasks that must run together in the same environment.</p><h3>2. Single vs. Multi-Container Pods</h3><p><strong>The Confusion</strong>:<br>A common question that arises when working with Kubernetes Pods is: <em>Why would you ever need multiple containers in a single Pod?</em> At first glance, it might seem redundant or unnecessary, especially if you are used to thinking of containers as self-contained applications that can run independently. The use of multiple containers within a single Pod is actually a powerful and efficient pattern in Kubernetes.</p><p><strong>The Reality</strong>:<br><strong>Multi-container Pods</strong> are designed to support patterns where multiple containers need to work together and share certain resources. The most common use case for this is the <a href="https://www.geeksforgeeks.org/sidecar-design-pattern-for-microservices/"><strong>sidecar pattern</strong></a>, where one container (the main container) does the primary job, and a second container (the sidecar) supports it in a complementary way. Both containers share the same network, storage, and other resources within the Pod, which makes them well suited for tasks that need close coordination.</p><p>Think of a <strong>Single-Container Pod</strong> as a lone worker, performing a task by itself. On the other hand, a <strong>Multi-Container Pod</strong> is like a team of workers where one person does the main job, while another helps with tasks like maintaining equipment or managing resources. Together they complete the job efficiently.</p><p><strong>Example</strong>:<br>Let’s say you have a web server container running in a Pod, serving a web application. Alongside this container, you might want to include a <strong>logging sidecar container</strong>. This sidecar could be responsible for gathering logs from the web server container and forwarding them to a centralized logging service.</p><ul><li><strong>Web server container</strong>: Main container running the application.</li><li><strong>Logging sidecar container</strong>: Collects and forwards logs to a logging system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*iOEt6zgB23bBv5-2VvXRWg.jpeg" /></figure><p>In this setup, both containers are tightly coupled within the same Pod, sharing the same network namespace (they can communicate via <strong><em>localhost</em></strong>) and storage resources (like log files stored in a shared volume).</p><h3>3. Kubernetes API Server and API Controllers</h3><h4>The Confusion:</h4><p>A common challenge for beginners when working with Kubernetes is understanding the difference between the <strong>API Server</strong> and <strong>API Controllers</strong>. At first glance, they might appear to serve overlapping roles in managing the cluster, leading to confusion about their specific responsibilities and how they collaborate to maintain the cluster’s desired state.</p><h4>The Reality:</h4><p><a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/"><strong>Kubernetes API Server</strong></a>: The API server is the entry point for all REST requests in the Kubernetes cluster. It validates and processes requests to create, update, delete, or retrieve cluster resources such as Pods, Services, Deployments, etc. The API server acts as a gatekeeper and mediator between the internal cluster and the external world, including users, clients, and other systems.</p><ul><li><strong>Example</strong>: When a user sends a POST request to create a new Pod, this request goes through the Kubernetes API Server.</li><li>The API Server receives this request and initiates the creation of a Pod.</li></ul><p><a href="https://kubernetes.io/docs/concepts/architecture/controller/"><strong>API Controllers</strong></a>: API Controllers are components within Kubernetes that monitor resources and ensure the cluster’s state matches the desired state defined by users. Each controller is responsible for a specific type of resource (e.g., Pods, Deployments, ReplicaSets). When the current state differs from the desired state, the controller takes corrective action.</p><p><strong>Reconciliation</strong>: It is the process where controllers continuously monitor the actual state of resources and compare it with the desired state. If discrepancies are found, they act to “reconcile” the two by either creating, updating, or deleting resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4YL_fmNQhjHC-kpKn-WcQ.png" /></figure><p><strong>Example</strong>: Suppose you define a <strong>Deployment</strong> with 3 replicas for a <strong><em>nginx </em></strong>application. If only 2 replicas are running (for example, one Pod crashes), the <strong>Deployment Controller</strong> will detect this mismatch and create a new Pod to ensure that the desired state (3 replicas) is met.</p><h3>3. Kubernetes Services</h3><p><strong>The Confusion</strong>:<br>When you first encounter Kubernetes, you might hear the term “Service” thrown around often. But a question that arises is: <strong>What exactly does a Kubernetes Service do?</strong> It can be confusing to understand the connection between Pods, Services, and how they communicate.</p><p><strong>The Reality</strong>:<br>A <a href="https://kubernetes.io/docs/concepts/services-networking/service/"><strong>Kubernetes Service</strong></a> is a fundamental concept that plays a key role in how applications run and interact within a Kubernetes cluster. At its core, a Service in Kubernetes is a <strong>stable endpoint</strong> that acts as an abstraction layer to access a group of Pods.</p><p>Why is this needed?</p><p>In Kubernetes, <strong>Pods</strong> are ephemeral and can change over time. They can be <strong>created, destroyed, and re-scheduled</strong> across nodes in the cluster. This makes direct communication with Pods difficult since their IP addresses <strong>are dynamic and constantly changing</strong>. Services help address this by providing a <strong>static IP address or DNS name</strong> that clients or other Pods can use to communicate with a set of Pods, regardless of their changing IPs.</p><p>Think of a Service as a <strong>middleman</strong> that abstracts the complexity of Pods in a Kubernetes cluster. Instead of connecting directly to a Pod’s IP address, clients connect to the Service.</p><p>For example, if you have a web application running in several Pods, you can create a Service to provide a stable access point for all traffic to reach those Pods.</p><p><strong>Types of Services:</strong></p><p><strong>ClusterIP</strong>: The default type of Service, <strong>ClusterIP</strong> exposes the Service only within the cluster, making it accessible only from other Pods inside the same cluster. It provides a stable IP address for the Service, but only for internal use.</p><ul><li><strong>Use Case</strong>: This is ideal for communication between services that need to interact within the cluster, such as a backend service talking to a database, but not exposed outside the cluster.</li></ul><p><strong>NodePort</strong>: It exposes the Service on each node in the cluster at a static port, making it accessible outside the cluster through the node’s IP address. A specific port range (usually between 30000–32767) is used for NodePort Services, and traffic sent to the node’s IP on that port is forwarded to the appropriate Pod.</p><ul><li><strong>Use Case</strong>: If you want to expose an application to external users or clients and don’t want to set up a full load balancer, you can use a NodePort Service. For example, a front-end web application can be accessed through a NodePort.</li></ul><p><strong>LoadBalancer: </strong>It creates an external load balancer in a cloud environment (like AWS or GCP) to distribute traffic across multiple Pods. It assigns a fixed external IP address and routes traffic to the correct Pods behind the Service.</p><ul><li><strong>Use Case</strong>: LoadBalancer Services are often used when you need to expose an application to the internet and want to have load balancing automatically managed by the cloud provider. For instance, exposing a production website with high availability and scalability.</li></ul><h3>4. Ingress and Ingress Controllers</h3><p><strong>The Confusion</strong>:<br>A common question when working with Kubernetes networking is: Why do we need an Ingress and an Ingress Controller? At first glance, it might seem simpler to expose services directly, leading to confusion about the purpose of an Ingress and the role the Ingress Controller plays in managing external access to the cluster.</p><p><strong>The Reality</strong>:<br>In Kubernetes, <strong>Ingress</strong> and <strong>Ingress Controllers</strong> work together to manage how external HTTP(S) traffic is routed to your services inside the cluster.</p><h4>What is Ingress?</h4><p>An <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/"><strong>Ingress</strong></a> is a Kubernetes API object that defines the rules for external HTTP(S) access to services inside your Kubernetes cluster. It is used to expose HTTP and HTTPS routes from outside the cluster to services within the cluster. Essentially, Ingress acts as a <strong>gatekeeper</strong> for external traffic.</p><p>Ingress allows for:</p><ul><li><strong>Routing Traffic</strong>: Directing traffic based on the hostname or URL path to the appropriate service.</li><li><strong>SSL Termination</strong>: Handling SSL encryption and decryption to provide secure connections (HTTPS).</li><li><strong>Load Balancing</strong>: Distributing incoming traffic across multiple instances of a service to ensure high availability and reliability.</li><li><strong>Name-based Virtual Hosting</strong>: You can route traffic based on domain names or URL paths (e.g., <a href="https://www.example.com/">www.example.com</a> for one service and <a href="https://api.example.com/">api.example.com</a> for another).</li></ul><p><strong>Example</strong>:<br>If you have multiple applications running in your Kubernetes cluster, such as a frontend and a backend, you could use an Ingress to route traffic from <a href="https://www.example.com/">www.example.com</a> to the frontend and <a href="https://api.example.com/">api.example.com</a> to the backend, even though both applications reside within the same Kubernetes cluster.</p><h4>What is an Ingress Controller?</h4><p>An <a href="https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/"><strong>Ingress Controller</strong></a> is a piece of software responsible for fulfilling the Ingress rules defined in your Kubernetes cluster. While an Ingress defines the routing rules, the Ingress Controller actually carries them out.</p><p>The Ingress Controller is typically a <strong>reverse proxy</strong> (like NGINX, HAProxy, or Traefik) that listens for changes to the Ingress resource and then takes action based on the defined rules. It routes incoming HTTP(S) traffic to the appropriate services, handles SSL termination, and balances the traffic across the available pods.</p><p>The <strong>Ingress Controller</strong> works behind the scenes and is essential for Ingress to function. Without an Ingress Controller, Ingress objects have no effect because there’s nothing to implement those routing rules.</p><h3>5. Pod Lifecycle Phases</h3><p><strong>The Confusion</strong>:<br>One of the most common points of confusion is understanding the different <strong>Pod lifecycle phases, </strong>specifically the difference between <strong><em>Pending</em></strong>, <strong><em>Running</em></strong>, <strong><em>Succeeded</em></strong>, and <strong><em>Failed</em></strong>. At first, these terms may seem ambiguous, and it can be hard to know what’s happening with your Pod at any given moment.</p><p><strong>The Reality</strong>:<br>Kubernetes provides several phases to describe the state of a Pod as it progresses through its lifecycle. These phases help you track the status of a Pod and troubleshoot any issues that may arise during its execution. Let’s break down each of the key Pod lifecycle phases:</p><p><strong>Pending</strong>:<br>This phase indicates that the Pod has been <strong>created</strong> and is <strong>waiting to be scheduled</strong> onto a node. The Pod is essentially in a “waiting” state. The containers within the Pod have not started yet.</p><ul><li><strong>Example</strong>: If a Pod is waiting for CPU and memory resources to be available, it will remain in the Pending phase.</li></ul><p><strong>Running</strong>:<br>Once the scheduler assigns the Pod to a node and the containers are started, the Pod enters the “Running” phase.</p><ul><li><strong>What Happens Here</strong>: The Pod is active and running, and its containers are fully started and executing their tasks. The Pod will remain in this state as long as at least one container in the Pod is still running.</li><li><strong>Example</strong>: If the Pod contains a web server container, it would be running and serving requests at this point.</li></ul><p><strong>Succeeded</strong>:<br>After all containers in a Pod finish successfully (i.e., they complete their task without errors), the Pod enters the “Succeeded” phase. This is typically the end state for <strong>Batch jobs</strong> or <strong>one-time tasks</strong>.</p><ul><li><strong>Example</strong>: If the Pod is running a batch job to process some data, once the job finishes without issues, the Pod enters the “Succeeded” state.</li></ul><p><strong>Failed</strong>:<br>A Pod enters the “Failed” phase when <strong>all containers</strong> inside it terminate with an error. This could happen due to various reasons, such as incorrect configurations, crashes, or issues within the application itself.</p><ul><li><strong>Example</strong>: If the container running a web server crashes due to a misconfiguration, the Pod would enter the “Failed” state.</li></ul><h3>6. Init Containers</h3><p><strong>The Confusion</strong>:<br>When first diving into Kubernetes, you might come across the term <strong>Init Containers</strong> and wonder: <em>What exactly are Init Containers, and how do they differ from regular containers?</em> This is a common point of confusion, as both Init Containers and regular containers run within a Pod, but they serve different purposes.</p><p><strong>The Reality</strong>:<br><strong>Init Containers</strong> are a special type of container that run before the main application containers inside a Pod. They perform setup tasks or initialization steps before the primary containers in the Pod start running. Init Containers allow you to prepare the environment for your main application, ensuring that everything is set up and ready to go.</p><p>Init Containers run <strong>sequentially</strong> (one after the other) before the main containers in the Pod can start. If one Init Container fails, the Pod won’t proceed to the next one or start the main containers. Only when all Init Containers complete successfully will the regular containers start.</p><h3>7. Volumes and Persistent Storage</h3><p><strong>The Confusion</strong>:<br>Many beginners find it difficult to understand the differences between types of storage like emptyDir, hostPath, and <strong>Persistent Volumes (PVs)</strong> in Kubernetes. What does each one do, and when should you use them?</p><p><strong>The Reality</strong>:<br>Kubernetes offers different types of storage for different needs:</p><ul><li><strong>emptyDir</strong>: This is temporary storage that exists only as long as the Pod is running. Once the Pod is deleted, the data is lost. It is typically used for <strong>temporary tasks</strong> like caching or processing that does not require persistence.</li><li><strong>hostPath</strong>: This volume type links a Pod to the <strong>local filesystem of the node</strong> it is running on. While useful for certain tasks, it’s typically <strong>not recommended for production</strong> because if the Pod moves to another node, it won’t have access to the same data.</li><li><strong>Persistent Volumes (PVs)</strong>: These are <strong>long-term storage resources</strong> that exist independently of Pods. PVs provide <strong>persistent storage</strong> that remains even if the Pod is deleted or rescheduled. You would use PVs when you need to store important data like databases, files, or logs that must survive beyond the Pod lifecycle.</li></ul><h3>8. Pod Health Checks</h3><p><strong>The Confusion</strong>:<br>Beginners often get confused between <strong>readiness probes</strong> and <strong>liveness probes</strong>. What exactly do each of these health checks do, and why are both needed?</p><p><strong>The Reality</strong>:<br>Kubernetes uses two types of probes to monitor the health of a Pod:</p><p><strong>Readiness Probes</strong>: These check if a Pod is <strong>ready</strong> to start receiving traffic. For example, when your app is still loading dependencies or doing some setup, Kubernetes will use a readiness probe to check if it’s ready to serve requests.</p><p>For example: A web server container might need to complete initialization before it can start serving traffic. The readiness probe checks if the server is fully ready to handle incoming requests.</p><p><strong>Liveness Probes</strong>: These check if a Pod is still <strong>healthy</strong> while running. If the probe fails, Kubernetes will assume the Pod is no longer working properly and will <strong>restart</strong> it. This is useful if your application crashes or hangs during runtime.</p><p>For example: A server that suddenly becomes unresponsive might need a restart. The liveness probe checks the server’s health, and if it fails, Kubernetes restarts the container to restore service.</p><h3>9. Pod Annotations vs. Labels</h3><p><strong>The Confusion</strong>:<br>Many beginners struggle to understand the difference between <strong>annotations</strong> and <strong>labels</strong> in Kubernetes. What are they used for, and when should you use one over the other?</p><p><strong>The Reality</strong>:<br>Both annotations and labels are ways to attach metadata to Pods, but they serve different purposes:</p><p><strong>Labels</strong>: Labels are used to <strong>identify and organize Pods</strong> based on certain criteria. They help you select and filter Pods, usually for grouping Pods with a common characteristic. For example, labels are used to associate Pods with Services, so that traffic can be directed to the right Pods. Labels are used in <strong>selectors</strong> to match resources in Kubernetes.</p><p>For example: A label like app: web-server helps group Pods together. Kubernetes services or deployments can select this label to direct traffic to all Pods with the app: web-server label.</p><p><strong>Annotations</strong>: Annotations are used to store <strong>non-identifying metadata</strong>. This metadata isn’t used for filtering or selecting Pods like labels, but it provides additional information that can be used by external tools, for debugging, or for tracking. Annotations are generally <strong>larger</strong> and can store more data than labels.</p><p>For example: an annotation like maintainer: team@example.com stores extra information that might be useful for developers or system administrators but doesn’t directly affect the behavior of the Pods or Services.</p><h3>10. Custom Resource Definitions (CRDs) and Operators in Kubernetes</h3><h4>The Confusion:</h4><p>When diving into Kubernetes, many beginners struggle with understanding the purpose and functionality of <strong>Custom Resource Definitions (CRDs)</strong> and <strong>Operators</strong>. They might wonder: “Why do we need to create custom resources? Isn’t Kubernetes enough with the built-in resources?” The concept of extending Kubernetes with custom resources and automating management through Operators can be a bit overwhelming at first.</p><h4>The Reality:</h4><p>A <strong>Custom Resource Definition (CRD)</strong> is a way to extend Kubernetes’ built-in resources with your own custom-defined resources. It allows you to create new types of objects (resources) that behave similarly to native Kubernetes objects (like Pods, Deployments, etc.), but with properties that are unique to your application or use case.</p><ul><li><strong>Creating Custom Resources</strong>: With CRDs, you can define any custom resource, such as a database configuration or application-specific state, that behaves like a standard Kubernetes resource.</li><li><strong>Example</strong>: If you’re managing a database service in Kubernetes, you might create a <strong><em>Database </em></strong>custom resource with specifications like the database type, connection settings, and size, allowing Kubernetes to track and manage it.</li></ul><p>You can learn more about CRDs in my <a href="https://medium.com/@usvisen2000/understanding-custom-resource-definitions-crds-in-kubernetes-604f04b23c8c">next blog</a>, where I will dive deeper into scenarios, including when to use CRDs, practical examples, and how they can enhance your Kubernetes experience.</p><h4>Conclusion</h4><p>In conclusion, Kubernetes may initially feel like an intricate maze of concepts and abstractions, but with persistence and the right resources, the path becomes clearer. From understanding the relationship between Pods and containers to demystifying Services, Ingress, and API controllers, each piece of knowledge brings you closer to harnessing the full power of Kubernetes.</p><h4>References:</h4><p><strong>Tutorials and Quick Starts:</strong></p><ul><li><a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/">Kubernetes Basics</a></li><li><a href="https://kubernetes.io/docs/tutorials/hello-minikube/">Hello Minikube</a></li></ul><p><strong>Hands-On Platforms</strong></p><ul><li><a href="https://labs.play-with-k8s.com/">Play with Kubernetes</a>:</li><li><a href="https://minikube.sigs.k8s.io/docs/start/">Minikube — Local Cluster Setup</a></li></ul><p><strong>Online Tutorials and Guides</strong></p><ol><li><a href="https://kube.academy/">Kubernetes Academy by VMware</a></li><li><a href="https://www.katacoda.com/courses/kubernetes/">Katacoda Kubernetes Scenarios:</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8362558c10b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/navigating-kubernetes-a-beginners-roadmap-to-understanding-key-concepts-8362558c10b6">Navigating Kubernetes: A Beginner’s Roadmap to Understanding Key Concepts</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Docker Deployments on AWS EC2 Instances: A GitHub Actions and AWS SSM Approach]]></title>
            <link>https://medium.com/@usvisen2000/simplifying-docker-deployments-on-aws-ec2-instances-a-github-actions-and-aws-ssm-approach-45014bf3869a?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/45014bf3869a</guid>
            <category><![CDATA[continous-deployment]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws-ssm]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 11:13:51 GMT</pubDate>
            <atom:updated>2024-02-19T18:30:14.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z-6UikjauWSHlCmr.jpg" /></figure><p>In my <a href="https://medium.com/@usvisen2000/overcoming-deployment-challenges-deploying-docker-containers-on-aws-ec2-instances-add7ee6e835a">previous blog</a>, we delved into the intricacies of updating Docker containers via CloudFormation helper scripts, namely cfn-init and cfn-hup. However, amidst the discussion of streamlined deployments, one critical aspect remained unaddressed: the <strong>absence of a robust rollback strategy.</strong></p><p>Consider this scenario: what happens if, during deployment, the Docker run or pull command encounters a failure? Or worse, if the Docker rm command fails unexpectedly? In such instances, the absence of a rollback strategy leaves our deployment pipeline vulnerable and prone to disruptions.</p><h3>Streamlining Docker Deployments with GitHub Actions and AWS SSM</h3><p>AWS Systems Manager (SSM) commands enable remote execution of tasks on EC2 instances, while GitHub Actions automate deployment workflows triggered by events. By integrating SSM commands within GitHub Actions, we can execute deployment tasks and handle failures effectively, ensuring smoother deployments and enhanced system reliability in AWS environments.</p><h3>What is AWS SSM?</h3><p><a href="https://docs.aws.amazon.com/cli/latest/reference/ssm/">AWS Systems Manager (SSM)</a> commands serve as a powerful tool for managing and executing tasks on EC2 instances without requiring direct access. With SSM, users can remotely run scripts, install software, and perform system updates across fleets of instances, all from a centralized management console. This eliminates the need for manual intervention and simplifies operational tasks, enhancing efficiency and security in cloud environments. SSM also offers features like Parameter Store for securely storing configuration data and Session Manager for interactive shell access to instances without exposing SSH/RDP ports. Overall, SSM commands streamline infrastructure management and enable robust automation capabilities in AWS environments.</p><h4>1. Sending a Command:</h4><p>To send a command to EC2 instances, we use the <a href="https://docs.aws.amazon.com/cli/latest/reference/ssm/send-command.html">aws ssm send-command</a> CLI command. Let’s say you want to list all running Docker containers on an EC2 instance. You can simply send the docker ps command using the aws ssm send-command CLI command. This command tells SSM to execute docker ps on the specified instance:</p><pre>aws ssm send-command \<br>    --instance-ids ${YOUR_INSTANCE_ID} \<br>    --document-name &quot;AWS-RunShellScript&quot; \<br>    --comment &quot;List Docker containers&quot; \<br>    --parameters commands=[&quot;docker ps&quot;] \<br>    --output text</pre><h4>2. Waiting for Command Execution:</h4><p>We can wait for the command execution to complete using the aws ssm wait command-executed command:</p><pre>aws ssm wait command-executed \<br>    --command-id ${COMMAND_ID} \<br>    --instance-id ${YOUR_INSTANCE_ID}</pre><h4>3. Retrieving Command Output:</h4><p>To retrieve the output of the command, we use the <a href="https://docs.aws.amazon.com/cli/latest/reference/ssm/get-command-invocation.html">aws ssm get-command-invocation</a> command:</p><pre>aws ssm get-command-invocation \<br>    --command-id ${COMMAND_ID} \<br>    --instance-id ${YOUR_INSTANCE_ID}</pre><h3>Implementation Steps:</h3><h4>1. Utilizing Docker Image Tagged with GITHUB_NUMBER</h4><pre>jobs:<br>  deploy:<br>    name: Deploy<br>    runs-on: ubuntu-latest<br><br>    env:<br>      ECR_IMAGE_TO_DEPLOY: &quot;&quot;<br>      YOUR_ECR_REPOSITORY_NAME: &quot;test-application&quot;<br><br>    steps:<br>      - name: Setting and updating Base Environment Variables<br>        env:<br>          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}<br>        run: |<br>          echo &quot;Create ECR image with GitHub run number as tag&quot;<br>          echo &quot;ECR_IMAGE_TO_DEPLOY=$ECR_REGISTRY/$YOUR_ECR_REPOSITORY_NAME:$GITHUB_RUN_NUMBER&quot; &gt;&gt; $GITHUB_ENV<br><br>      - name: Build and Push to ECR<br>        run: |<br>          echo &quot;Building ECR image...&quot;<br>          docker build -t $ECR_IMAGE_TO_DEPLOY .<br>          echo &quot;Tagging Docker image with GitHub run number...&quot;<br>          docker tag $ECR_IMAGE_TO_DEPLOY $ECR_IMAGE_TO_DEPLOY:latest<br>          echo &quot;Pushing Docker image to ECR...&quot;<br>          docker push $ECR_IMAGE_TO_DEPLOY</pre><p>Explanation:</p><ul><li><strong>Setting and updating Base Environment Variables: </strong>This step sets up the base environment variables required for the deployment process. It retrieves the ECR registry URL and concatenates it with the GitHub run number to create a unique ECR image tag. <strong>This ensures that each deployment gets a distinct version identifier based on the GitHub run number.</strong></li><li><strong>Build and Push to ECR</strong>: Here, the Docker image is locally built using the repository’s Dockerfile. It’s then tagged with a unique ECR image tag from earlier steps and pushed to Amazon ECR. This process deploys the latest application version to ECR with a GitHub run number-based tag.</li></ul><blockquote>Using the GitHub run number to version the builds allows for easy rollback to previous versions when needed. Each deployment generates a unique version identifier, making it simple to track and revert to specific versions in case of issues or changes. This versioning strategy enhances the reliability and maintainability of the deployment process.</blockquote><h4>2. Execute Docker Commands on AWS Instance:</h4><p>In this step, we orchestrate the execution of Docker commands on EC2 instance to deploy the application using GitHub Actions and AWS Systems Manager (SSM) commands.</p><pre>name: Execute Docker Commands on AWS Instance to deploy the application<br>        run: |<br>          command_id=$(aws ssm send-command \<br>            --instance-ids ${{ env.INSTANCE_ID }} \<br>            --document-name &quot;AWS-RunShellScript&quot; \<br>            --comment &quot;Executing Docker operations&quot; \<br>            --parameters commands=&#39;[<br>              &quot;set -e&quot;,<br>              &quot;trap &#39;\&#39;&#39;echo DOCKER_STOP_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; if docker ps --format &#39;\&#39;&#39;{{.Names}}&#39;\&#39;&#39; | grep -q ${{ env.CONTIANER_NAME }}; then docker stop ${{ env.CONTIANER_NAME }}; fi&quot;,<br>              &quot;trap &#39;\&#39;&#39;echo DOCKER_RENAME_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; if docker ps -a --format &#39;\&#39;&#39;{{.Names}}&#39;\&#39;&#39; | grep -q ${{ env.CONTIANER_NAME }}; then docker rename ${{ env.CONTIANER_NAME }} ${{ env.CONTIANER_NAME }}-${GITHUB_RUN_NUMBER}; fi&quot;,<br>              &quot;trap &#39;\&#39;&#39;echo DOCKER_LOGIN_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; aws ecr get-login-password --region eu-west-1 | docker login --username AWS --password-stdin ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;,<br>              &quot;trap &#39;\&#39;&#39;echo DOCKER_PULL_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker pull ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;,<br>              &quot;trap &#39;\&#39;&#39;echo DOCKER_RUN_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker run -d -p 80:80 --name ${{ env.CONTIANER_NAME }} ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;<br>            ]&#39; --query &#39;Command.CommandId&#39; --output text)<br><br>          echo &quot;command_id=$command_id&quot; &gt;&gt; $GITHUB_ENV</pre><p>Explanation:</p><ul><li><strong>DOCKER_STOP_FAILURE trap</strong>: This trap is set to catch errors in case the docker stop command fails. It ensures that any running containers with the specified name (${{ env.CONTIANER_NAME }}) are stopped gracefully before proceeding with the deployment process.</li><li><strong>DOCKER_RENAME_FAILURE trap: </strong>In the event of a failure during the Docker operations, such as pull or run, the container is renamed to ${{ env.CONTIANER_NAME }}-${GITHUB_RUN_NUMBER}. This renaming serves as a backup mechanism, preserving the existing container state and configuration.<em> </em><strong><em>If any subsequent operations fail, the renamed container can be reverted to its original state for recovery purposes.</em></strong></li><li><strong>DOCKER_LOGIN_FAILURE, DOCKER_PULL_FAILURE, DOCKER_RUN_FAILURE traps: </strong>These traps handle errors related to Docker login, image pull, and container run operations, respectively. They ensure that any failures during these critical steps are detected and appropriately handled to maintain the integrity of the deployment process.</li></ul><h4><strong>3. Retrieve and Store SSM Command Results:</strong></h4><p>After sending the SSM command, the workflow waits for the command to be executed on the EC2 instance. The aws ssm wait command-executed command is used to monitor the execution status of the SSM command. Once the command execution is complete, the output and status of the command invocation are retrieved using the aws ssm get-command-invocation command.</p><pre>- name: Retrieve and Store SSM Command Results<br>        run: |<br>          aws ssm wait command-executed \<br>            --command-id ${{ env.command_id }} \<br>            --instance-id ${{ env.INSTANCE_ID }} || true<br>          ssm_command_output=$(aws ssm get-command-invocation \<br>                --command-id ${{ env.command_id }} \<br>                --instance-id ${{ env.INSTANCE_ID }})<br><br>          standard_error_content=$(echo &quot;$ssm_command_output&quot; | jq -r &#39;.StandardErrorContent&#39;)<br>          standard_error_content=${standard_error_content//$&#39;\n&#39;/&#39; &#39;}<br>          status=$(echo &quot;$ssm_command_output&quot; | jq -r &#39;.Status&#39;)<br><br>          echo &quot;status=$status&quot; &gt;&gt; $GITHUB_ENV<br>          echo &quot;standard_error_content=$standard_error_content&quot; &gt;&gt; $GITHUB_ENV</pre><p>This step ensures that the workflow proceeds only after the Docker operations on the EC2 instance have been successfully executed or handled with appropriate error recovery mechanisms.</p><h4><strong>4. Check Docker Command Success and Remove Old Container:</strong></h4><p>In this step, we handle the aftermath of Docker command execution, ensuring the smooth progression of our deployment pipeline. Let’s delve into the details:</p><pre> - name: Check Docker Command Success and Remove Old Container<br>        id: handle_docker_results<br>        run: |<br>          if [[ &quot;${{ env.status }}&quot; == &quot;Success&quot; ]]; then<br>            echo &quot;Commands completed successfully.&quot;<br>            echo &quot;Deleting renamed old container&quot;<br>            removeOldContainerCommandId=$(aws ssm send-command \<br>              --instance-ids ${{ env.INSTANCE_ID }} \<br>              --document-name &quot;AWS-RunShellScript&quot; \<br>              --comment &quot;Deploy test-application&quot; \<br>              --parameters commands=&#39;[<br>                &quot;set -e&quot;,<br>                &quot;trap &#39;\&#39;&#39;echo DOCKER_RM_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker rm ${{ env.CONTAINER_NAME }}-${GITHUB_RUN_NUMBER}&quot;<br>              ]&#39; --query &#39;Command.CommandId&#39; --output text)<br>            echo &quot;Waiting for removal of renamed old container to complete...&quot;<br>            removeContainerInvocation = aws ssm wait command-executed \<br>              --command-id &quot;$removeOldContainerCommandId&quot; \<br>              --instance-id ${{ env.INSTANCE_ID }} || true<br><br>            removeContainerInvocationStatus=$(echo $removeContainerInvocation | jq -r &#39;.Status&#39;)<br><br>            if [[ $removeContainerInvocationStatus == &quot;Success&quot; ]]; then<br>              echo &quot;Removal of renamed old container completed successfully.&quot;<br>            else <br>              error_content=$(echo $removeContainerInvocation | jq -r &#39;.StandardErrorContent&#39;)<br>              echo &quot;Container removal failed with error: ${error_content}&quot;<br>            fi<br>          fi</pre><ul><li><strong>Evaluation of Command Success: </strong>We kick off by checking the outcome of the Docker commands executed in the preceding steps. Leveraging environment variables provided by GitHub Actions, we check if the Docker commands concluded successfully.</li><li><strong>Removal of Renamed Old Container: </strong>Upon confirming the success of the Docker commands, our next course of action involves the removal of the previously renamed old container. <strong><em>This container was renamed during deployment as a safety measure. Now, it’s not needed anymore, so we will remove it to keep the system clean.</em></strong></li><li><strong>Execution of Removal Command via SSM: </strong>With SSM send command, we dispatch a directive to the target EC2 instance, commanding the removal of the designated old container. The SSM command execution is monitored to ensure completion and validate the removal of the container.</li><li><strong>Verification of Removal Status: </strong>After we send the SSM command, we wait to see if the removal is done properly. If everything goes well and the removal is successful, we consider it a win.</li><li><strong>Handling Removal failure: </strong>If there’s an unexpected issue while we’re removing the container, the workflow will let us know by printing out the error details. This helps us understand why the container removal failed, so we can take the right steps to fix it.</li></ul><h4>5. Check Docker Command Failures and rollback if needed:</h4><p>In this phase of our deployment workflow, we address potential setbacks encountered during Docker command execution and swiftly respond with robust recovery mechanisms. Let’s break down this step-by-step process:</p><pre>- name: Check Docker Command Failures and rollback if needed<br>        if: env.status == &#39;Failed&#39;<br>        run: |<br>          echo &quot;error_content: ${{ env.standard_error_content }}&quot;<br>          if echo &quot;${{ env.standard_error_content }}&quot; | grep -Eq &quot;DOCKER_RUN_FAILURE|DOCKER_PULL_FAILURE&quot;; then<br>            echo &quot;Docker run command failed&quot;<br>            echo &quot;Handling Docker run failure...&quot;<br>              echo &quot;Rollback initiated...&quot;<br>              rollbackId=$(aws ssm send-command \<br>                --instance-ids ${{ env.INSTANCE_ID }} \<br>                --document-name &quot;AWS-RunShellScript&quot; \<br>                --comment &quot;Rollback to previous container version&quot; \<br>                --parameters commands=&#39;[<br>                  &quot;set -e&quot;,<br>                  &quot;trap &#39;\&#39;&#39;echo DOCKER_RENAME_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker rename ${{ env.CONTIANER_NAME }}-${GITHUB_RUN_NUMBER} ${{ env.CONTIANER_NAME }}&quot;,<br>                  &quot;trap &#39;\&#39;&#39;echo DOCKER_RESTART_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker restart ${{ env.CONTIANER_NAME }}&quot;,<br>                ]&#39; --query &#39;Command.CommandId&#39; --output text)<br><br>              echo &quot;Waiting for rollback to get completed...&quot;<br>              aws ssm wait command-executed \<br>                --command-id &quot;$rollbackId&quot; \<br>                --instance-id ${{ env.INSTANCE_ID }} || true<br><br>              echo &quot;Fetching rollback invocation details...&quot;<br>              rollbackInvocation=$(aws ssm get-command-invocation \<br>                --command-id &quot;$rollbackId&quot; \<br>                --instance-id ${{ env.INSTANCE_ID }})<br><br>              rollbackstatus=$(echo $rollbackInvocation | jq -r &#39;.Status&#39;)<br><br>              if [[ $rollbackstatus == &quot;Success&quot; ]]; then<br>                echo &quot;Rollback completed: $rollbackstatus&quot;<br>              else <br>                error_content=$(echo $rollbackInvocation | jq -r &#39;.StandardErrorContent&#39;)<br>                echo &quot;Rollback failed with error: ${error_content}&quot;<br>              fi<br>              exit 1<br>          <br>          elif echo &quot;${{ env.standard_error_content }}&quot; | grep -Eq &quot;DOCKER_STOP_FAILURE|DOCKER_RENAME_FAILURE&quot;; then<br>            echo &quot;Docker stop/rename command failed&quot;<br>            echo &quot;Handling Docker stop/rename failure...&quot;<br>              echo &quot;Deploying application to new evironment&quot;<br>              rollbackId=$(aws ssm send-command \<br>                --instance-ids ${{ env.INSTANCE_ID }} \<br>                --document-name &quot;AWS-RunShellScript&quot; \<br>                --comment &quot;Deploy application to new evironment&quot; \<br>                --parameters commands=&#39;[<br>                  &quot;set -e&quot;,<br>                  &quot;trap &#39;\&#39;&#39;echo DOCKER_LOGIN_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; aws ecr get-login-password --region eu-west-1 | docker login --username AWS --password-stdin ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;,<br>                  &quot;trap &#39;\&#39;&#39;echo DOCKER_PULL_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker pull ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;,<br>                  &quot;trap &#39;\&#39;&#39;echo DOCKER_RUN_FAILURE 1&gt;&amp;2&#39;\&#39;&#39; ERR; docker run -d -p 80:80 --name ${{ env.CONTIANER_NAME }} ${{ env.ECR_IMAGE_TO_DEPLOY }}&quot;<br>                ]&#39; --query &#39;Command.CommandId&#39; --output text)<br><br>              echo &quot;Waiting for application to be deployed to new environment...&quot;<br>              aws ssm wait command-executed \<br>                --command-id &quot;$rollbackId&quot; \<br>                --instance-id ${{ env.INSTANCE_ID }} || true<br><br>              echo &quot;Fetching new environment deployment details...&quot;<br>              newEnvironmentInvocation=$(aws ssm get-command-invocation \<br>                --command-id &quot;$rollbackId&quot; \<br>                --instance-id ${{ env.INSTANCE_ID }})<br><br>              newEnvironmentDeploymentStatus=$(echo $newEnvironmentInvocation | jq -r &#39;.Status&#39;)<br><br>              if [[ $newEnvironmentDeploymentStatus == &quot;Success&quot; ]]; then<br>                echo &quot;New environment deployment completed: $newEnvironmentDeploymentStatus&quot;<br>              else <br>                error_content=$(echo $newEnvironmentInvocation | jq -r &#39;.StandardErrorContent&#39;)<br>                echo &quot;New environment deployment failed with error: ${error_content}&quot;<br>              fi<br><br>          else <br>            echo &quot;Command did not complete successfully.&quot;<br>            echo &quot;Error details: ${{ env.standard_error_content }}&quot;<br>            exit 1<br>          fi</pre><ol><li><strong>Handling Docker Run or Pull Failures:</strong></li></ol><ul><li><strong>Identifying Docker Run or Pull Failures:</strong> If errors related to Docker run or pull commands are found, the workflow recognizes that the deployment process may have encountered issues.</li><li><strong>Initiating Rollback Procedure:</strong> To rectify deployment problems, the workflow triggers a rollback process using AWS Systems Manager (SSM) commands.</li><li><strong>Rollback Steps: </strong>The rollback process involves renaming the current container to its previous version and restarting it to address deployment glitches.</li><li><strong>Waiting for Rollback Completion:</strong> After initiating the rollback, the workflow waits for the rollback command to execute and complete its task.</li><li><strong>Verifying Rollback Status:</strong> Once the rollback command finishes execution, the workflow verifies its status to ensure that the rollback procedure was successful.</li><li><strong>Handling Rollback Failure: </strong>If the rollback encounters errors or fails to execute successfully, the workflow logs the error details and acknowledges the rollback failure.</li><li><strong>Ensuring Deployment Stability:</strong> To maintain system stability and prevent further complications, the workflow exits with an error status until the rollback issues are resolved, ensuring a smooth and stable deployment process.</li></ul><p><strong>2. Handling Docker Stop or Rename Failures:</strong></p><ul><li><strong>Handling Docker Stop/Rename Failure:</strong> Upon detecting failures in Docker stop or rename commands, the workflow initiates steps to address the issue.</li><li><strong>Deployment to New Environment:</strong> If Docker stop or rename commands fail, it suggests that there is no existing container running, <strong>indicating a need for a new environment deployment</strong>. This approach ensures that the application is deployed to a fresh environment.</li><li><strong>Execution of Deployment Commands:</strong> The workflow utilizes SSM to send deployment commands to the instance. These commands include logging into the AWS Elastic Container Registry (ECR), pulling the required Docker image, and running the container with specified configurations.</li><li><strong>Monitoring Deployment Process: </strong>After sending the deployment commands, the workflow waits for the deployment process to complete by using the aws ssm wait command-executed function, ensuring that the new environment deployment progresses smoothly.</li><li><strong>Verification of Deployment Status: </strong>Once the deployment process concludes, the workflow retrieves the status of the deployment invocation to check whether the new environment deployment was successful.</li><li><strong>Handling Deployment Outcome:</strong> If the deployment to the new environment succeeds, the workflow logs the completion status and acknowledges the successful deployment. However, if the deployment encounters errors, the workflow logs the error details and acknowledges the deployment failure, ensuring transparency and accountability in the deployment process.</li></ul><p><strong>3. Fallback for unexpected errors:</strong></p><ul><li>The last part of the script (else part) functions as a catch-all mechanism for handling unexpected errors.</li><li>If none of the previously mentioned failure scenarios occur and the script encounters an unexpected error, it prints a message indicating that the command did not complete successfully.</li><li>Additionally, it logs details of the error content, allowing developers to review and troubleshoot the issue directly from the workflow logs.</li><li>This ensures that any unforeseen errors are properly documented and visible within the workflow environment, facilitating effective debugging and resolution processes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45014bf3869a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overcoming Deployment Challenges: Deploying Docker Containers on AWS EC2 Instances]]></title>
            <link>https://medium.com/@usvisen2000/overcoming-deployment-challenges-deploying-docker-containers-on-aws-ec2-instances-add7ee6e835a?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/add7ee6e835a</guid>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[cloudformation-template]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 13:51:19 GMT</pubDate>
            <atom:updated>2024-02-13T13:02:28.922Z</atom:updated>
            <content:encoded><![CDATA[<p>In my exploration of cloud infrastructure, I’ve found AWS EC2 instances to be the backbone for deploying a myriad of applications, providing the flexibility, scalability, and reliability that businesses crave. Yet, the process of deploying Docker containers on EC2 instances comes with its set of hurdles, especially when it comes to automation and updating container images. This blog post is my dive into these challenges, as I offer a structured approach to deploying Docker containers on EC2 instances using AWS CloudFormation. Throughout, I’ll also address the limitations that come with UserData initialization, paving the way for smoother deployments in the future.</p><h3>Problem Statement</h3><p>When deploying Docker containers on EC2 instances, relying solely on UserData for script execution presents several limitations. UserData scripts execute only during instance initialization, making subsequent updates or changes challenging. This limitation becomes particularly problematic when needing to update the Docker image running inside the EC2 instance. Even though UserData contains the necessary scripts for updating the Docker image, they won’t execute again after the initial instance launch, rendering the update process manual and error-prone.</p><h3>Solution Overview</h3><p>To tackle these issues, I use AWS CloudFormation, along with, <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html"><strong>cfn-init</strong></a>, and <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-hup.html"><strong>cfn-hup</strong></a> to automate deploying and updating Docker containers on EC2 instances. CloudFormation is great for managing AWS resources using code, while cfn-init and cfn-hup help automate and manage configurations on EC2 instances.</p><h4>What is cfn-init and cfn-hup?</h4><p><strong>cfn-init: </strong>AWS CloudFormation Init (cfn-init) is a tool designed to help bootstrap and configure instances that are launched as part of an AWS CloudFormation stack. It allows you to define configuration sets, which contain instructions for installing packages, creating files, and executing scripts on EC2 instances. These instructions are specified in the CloudFormation template metadata and are executed during the instance initialization process.</p><p><strong>cfn-hup</strong>: AWS CloudFormation Helper Scripts (cfn-hup) is another essential component that works in conjunction with cfn-init. Its primary purpose is to detect changes in the CloudFormation stack and trigger updates on EC2 instances accordingly. cfn-hup runs as a daemon on the EC2 instance, periodically checking for updates in the CloudFormation stack metadata. When changes are detected, cfn-hup can execute specified actions, such as running scripts or updating configurations, ensuring that the instance remains in sync with the desired state defined in the CloudFormation template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2utoavWGSa3HNmkZ60i8bA.png" /></figure><h4>How do cfn-init and cfn-hup work together?</h4><p>During the initialization of an EC2 instance launched via CloudFormation, cfn-init reads the metadata specified in the CloudFormation template and executes the defined configuration sets. These sets encompass various instructions crucial for system configuration, such as installing dependencies, configuring services, and executing setup tasks required for the instance.</p><p>In our diagram, cfn-init is depicted as the component responsible for configuring the system based on the instructions provided in the CloudFormation template. This includes setting up system configurations, installing packages, configuring files, and other necessary tasks outlined in the CloudFormation template.</p><p>Once the instance is initialized, cfn-hup continues to monitor the CloudFormation stack metadata for any changes. If changes are detected, cfn-hup triggers the execution of specified actions, ensuring that the instance remains up-to-date with the latest configuration defined in the CloudFormation template.</p><p>By leveraging the capabilities of cfn-init and cfn-hup within AWS CloudFormation, we can automate the deployment and configuration of EC2 instances, including the provisioning and updating of Docker containers, thereby streamlining our deployment workflows and enhancing the reliability and scalability of our infrastructure.</p><h4>Implementation Steps</h4><p><strong>Step 1: Defining the EC2 Instance and Metadata:</strong></p><pre>EC2Service:<br>  Type: AWS::EC2::Instance<br>  Metadata:<br>    AWS::CloudFormation::Init:<br>      configSets:<br>        default:<br>          - install_docker<br>      install_docker:<br>        files:<br>          &quot;/tmp/install.sh&quot;:<br>            content: !Sub<br>              - |<br>                #!/bin/bash<br>                # Install Docker <br>                sudo yum update -y<br>                sudo amazon-linux-extras install docker<br>                sudo service docker start<br>                sudo usermod -a -G docker ec2-user<br><br>                # Pulling and deploying new Docker image<br>                sudo docker pull ${ImageName}<br>                # Restarting Docker container with the new image<br>                sudo docker stop ${ContainerName} &amp;&amp; sudo docker rm ${ContainerName}<br>                sudo docker run -d --name ${ContainerName} -p 8000:9000 ${ImageName}<br>            mode: &quot;000755&quot;<br>            owner: root<br>            group: root</pre><p><strong>Explanation:</strong></p><ul><li>We define an EC2 instance named “EC2Service” using AWS::EC2::Instance.</li><li>In the Metadata section, we utilize AWS::CloudFormation::Init to specify configuration sets.</li><li>The “install_docker” configSet includes instructions for installing Docker and deploying a new Docker image.</li><li>We define a script (install.sh) in the &quot;files&quot; section. This script installs Docker, pulls the specified Docker image (${ImageName}), stops and removes the existing Docker container (${ContainerName}), and runs a new container with the pulled image, mapping port 8000 on the host to port 9000 inside the container.</li></ul><blockquote><strong><em>Note: </em>ImageName</strong><em> and </em><strong>ContainerName</strong><em> are placeholders for the actual image name and container name. They should be defined in the parameters section of the CloudFormation template.</em></blockquote><p><strong>Step 2: Configuring cfn-hup:<br></strong>In this step, we are configuring cfn-hup, which is a part of the AWS CloudFormation helper scripts designed to detect changes in the CloudFormation stack and trigger updates on EC2 instances accordingly. Let’s break down the configuration:</p><pre>        /etc/cfn/cfn-hup.conf:<br>          content: !Join<br>            - &quot;&quot;<br>            - - |<br>                [main]<br>              - stack=<br>              - !Ref &quot;AWS::StackId&quot;<br>              - |+<br>              - region=<br>              - !Ref &quot;AWS::Region&quot;<br>              - |+<br>              - interval=<br>              - 3<br>              - |+<br>          mode: &quot;000400&quot;<br>          owner: root<br>          group: root<br>        /etc/cfn/hooks.d/cfn-auto-reloader.conf:<br>          content: !Join<br>            - &quot;&quot;<br>            - - |<br>                [cfn-auto-reloader-hook]<br>              - |<br>                triggers=post.update<br>              - &gt;<br>                path=Resources.EC2Service.Metadata.AWS::CloudFormation::Init<br>              - &quot;action=/opt/aws/bin/cfn-init -s &quot;<br>              - !Ref &quot;AWS::StackId&quot;<br>              - &quot; -r EC2Service &quot;<br>              - &quot; --region     &quot;<br>              - !Ref &quot;AWS::Region&quot;<br>              - |+<br>              - |<br>                runas=root<br>          mode: &quot;000644&quot;<br>          owner: apache<br>          group: apache</pre><p><strong>cfn-hup Configuration (</strong><strong>/etc/cfn/cfn-hup.conf):</strong></p><ul><li>This file specifies the configuration settings for cfn-hup, which is responsible for detecting changes in the CloudFormation stack and triggering updates on the EC2 instance.</li><li>The content attribute defines the content of the cfn-hup.conf file.</li><li>Within the content, we have sections like [main] that define various parameters:</li><li>stack=: Typically contains the name of the CloudFormation stack, but here it&#39;s left empty.</li><li>region=: Normally contains the AWS region where the stack is deployed, also left empty here.</li><li>interval=: Specifies the frequency (in minutes) at which cfn-hup checks for updates. In this case, it&#39;s set to 3 minutes.</li><li>The mode, owner, and group attributes define the file permissions, owner, and group for the cfn-hup.conf file, respectively.</li></ul><p><strong>cfn-auto-reloader Configuration (</strong><strong>/etc/cfn/hooks.d/cfn-auto-reloader.conf):</strong></p><ul><li>This file configures a hook called cfn-auto-reloader, which triggers actions after CloudFormation stack updates.</li><li>The content attribute defines the content of the cfn-auto-reloader.conf file.</li><li>Within the content, we have sections like [cfn-auto-reloader-hook] that define the hook configuration:</li><li>triggers=post.update: Specifies that this hook should be triggered after a CloudFormation stack update.</li><li>path=Resources.EC2Service.Metadata.AWS::CloudFormation::Init: Specifies the path where CloudFormation init metadata is located.</li><li>action=/opt/aws/bin/cfn-init -s &lt;StackId&gt; -r EC2Service --region &lt;Region&gt;: Defines the action to perform when the hook is triggered. It typically involves running cfn-init to apply new configurations. Here, &lt;StackId&gt; and &lt;Region&gt; are placeholders for the actual CloudFormation stack ID and AWS region.</li><li>runas=root: Indicates that the action should be executed with root privileges.</li><li>The mode, owner, and group attributes define the file permissions, owner, and group for the cfn-auto-reloader.conf file, respectively.</li></ul><p><strong>Step 3: Configuring UserData:</strong></p><pre>    UserData:<br>      &quot;Fn::Base64&quot;: !Sub |<br>        #!/bin/bash<br>        yum install -y aws-cfn-bootstrap<br>        /opt/aws/bin/cfn-init -v --stack ${AWS::StackId} --resource EC2Service --region ${AWS::Region} --configsets default<br>        /opt/aws/bin/cfn-hup || error_exit &#39;Failed to start cfn-hup&#39;<br>        /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackId} --region ${AWS::Region} --resource EC2Service</pre><p><strong>Explanation:</strong></p><ol><li><strong>Installation of AWS CloudFormation Bootstrap Tools:</strong> The script begins by installing the AWS CloudFormation bootstrap tools (aws-cfn-bootstrap) on the EC2 instance. These tools are essential for executing further CloudFormation-initiated actions on the instance.</li><li><strong>Initialization of CloudFormation Metadata: </strong>The script uses cfn-init to initialize CloudFormation metadata on the EC2 instance. This metadata includes configurations defined in the CloudFormation template, which are applied to the instance.</li><li><strong>Starting CloudFormation Helper Script (cfn-hup):</strong> The script starts the CloudFormation helper script (cfn-hup). This script continuously checks for changes in the CloudFormation metadata and applies them to the instance, ensuring that its configuration stays up-to-date.</li><li><strong>Signaling CloudFormation: </strong>Finally, the script sends a signal back to CloudFormation, indicating whether the UserData execution was successful or encountered errors. This signal allows CloudFormation to proceed with subsequent stack operations based on the outcome of the initialization process.</li></ol><h3>Conclusion</h3><p>In conclusion, the UserData script within the AWS CloudFormation template executes only during the initial launch of an EC2 instance, setting up essential configurations such as installing necessary tools and initializing CloudFormation metadata. The CloudFormation helper daemon (cfn-hup) is started to continuously monitor changes in the CloudFormation metadata, facilitating automatic updates to the EC2 instance&#39;s configuration.</p><p>cfn-hup detects changes in the CloudFormation metadata, including updates to Docker image specifications. Therefore, modifications to the Docker image referenced in the CloudFormation template will trigger cfn-hup to update the EC2 instance, ensuring that the latest Docker image is pulled and utilized by the container running on the instance.</p><p>Overall, this orchestrated mechanism streamlines the management of EC2 instances, facilitating automatic updates and maintaining synchronization with the CloudFormation template, thereby enhancing operational efficiency and ensuring consistency in deployment configurations.</p><p>Here is the complete cloudformation yaml code:</p><pre>EC2Service:<br>  Type: AWS::EC2::Instance<br>  Metadata:<br>    AWS::CloudFormation::Init:<br>      configSets:<br>        default:<br>          - install_docker<br>      install_docker:<br>        files:<br>          &quot;/tmp/install.sh&quot;:<br>            content: !Sub<br>              - |<br>                #!/bin/bash<br>                # Install Docker <br>                sudo yum update -y<br>                sudo amazon-linux-extras install docker<br>                sudo service docker start<br>                sudo usermod -a -G docker ec2-user<br><br>                # Pulling and deploying new Docker image<br>                sudo docker pull ${ImageName}<br>                # Restarting Docker container with the new image<br>                sudo docker stop ${ContainerName} &amp;&amp; sudo docker rm ${ContainerName}<br>                sudo docker run -d --name ${ContainerName} -p 8000:9000 ${ImageName}<br>              mode: &quot;000755&quot;<br>              owner: root<br>              group: root<br><br>          &quot;/etc/cfn/cfn-hup.conf&quot;:<br>            content: !Join<br>              - &quot;&quot;<br>              - - |<br>                  [main]<br>                - stack=<br>                - !Ref &quot;AWS::StackId&quot;<br>                - |+<br>                - region=<br>                - !Ref &quot;AWS::Region&quot;<br>                - |+<br>                - interval=<br>                - 3<br>                - |+<br>            mode: &quot;000400&quot;<br>            owner: root<br>            group: root<br><br>          &quot;/etc/cfn/hooks.d/cfn-auto-reloader.conf&quot;:<br>            content: !Join<br>              - &quot;&quot;<br>              - - |<br>                  [cfn-auto-reloader-hook]<br>                - |<br>                  triggers=post.update<br>                - &gt;<br>                  path=Resources.EC2Service.Metadata.AWS::CloudFormation::Init<br>                - &quot;action=/opt/aws/bin/cfn-init -s &quot;<br>                - !Ref &quot;AWS::StackId&quot;<br>                - &quot; -r EC2Service &quot;<br>                - &quot; --region     &quot;<br>                - !Ref &quot;AWS::Region&quot;<br>                - |+<br>                - |<br>                  runas=root<br>            mode: &quot;000644&quot;<br>            owner: apache<br>            group: apache<br><br>        services:<br>          sysvinit:<br>            cfn-hup:<br>              enabled: &quot;true&quot;<br>              ensureRunning: &quot;true&quot;<br>              files:<br>                - /etc/cfn/cfn-hup.conf<br>                - /etc/cfn/hooks.d/cfn-auto-reloader.conf<br><br>        commands:<br>          00_run_install:<br>            command: &quot;bash /tmp/install.sh&quot;<br><br>    Properties:<br>      InstanceType: !Ref InstanceType<br>      ImageId: !Ref ImageId<br>      KeyName: !Ref YourEC2KeyPair<br>      IamInstanceProfile: !Ref EC2InstanceProfile<br>      UserData:<br>        &quot;Fn::Base64&quot;: !Sub |<br>          #!/bin/bash<br>          yum install -y aws-cfn-bootstrap<br>          /opt/aws/bin/cfn-init -v --stack ${AWS::StackId} --resource EC2Service --region ${AWS::Region} --configsets default<br>          /opt/aws/bin/cfn-hup || error_exit &#39;Failed to start cfn-hup&#39;<br>          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackId} --region ${AWS::Region} --resource EC2Service</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=add7ee6e835a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Silent SNS Alarm Issue in SQS Workflow: An Interactive Dive into a Step Function…]]></title>
            <link>https://medium.com/@usvisen2000/solving-the-silent-sns-alarm-issue-in-sqs-workflow-an-interactive-dive-into-a-step-function-341c55413086?source=rss-43e9c006e4a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/341c55413086</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[sqs-lambda]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Utkarsh Singh]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 08:52:34 GMT</pubDate>
            <atom:updated>2024-02-09T17:05:21.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving the Silent SNS Alarm Issue in SQS Workflow: An Interactive Dive into a Step Function Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrfgJTUCj9IcH9pKz-JMxg.jpeg" /></figure><h3>The Problem: Silence in the Face of Workflow Anomalies</h3><p>In the realm of SQS workflow management, I encountered a perplexing issue with SNS alarms. Previously, I relied on SNS alarms to notify me when messages populated in my SQS queues, especially when they found their way into the Dead Letter Queue (DLQ). However, the alarms seemed to stay silent when my workflow triggered multiple times, causing messages to accumulate in the DLQ.</p><p>Upon closer inspection, the root cause surfaced: the SNS alarm remained in an ALARM state, because the DLQ was not cleared. This persistent state became problematic because, if my workflow executed multiple times a day and developers chose to ignore or not manually clear the DLQ, the alarm would never transition back to an OK state. Consequently, vital email notifications weren’t triggered, leaving unnoticed issues lingering in the workflow.</p><h3>The Exploration: Unveiling Potential Solutions</h3><p>To address this challenge, I explored different ways to solve the problem. My goal was to find a robust method that didn’t involve manual intervention or introduce unnecessary complexities. Here’s a glimpse into the options I considered:</p><ol><li><strong>Lambda Function for Email Notifications: </strong>The conventional approach involves using a Lambda function to check the SQS queues and send email notifications. However, this approach seemed resource-intensive and introduced additional complexities.</li><li><strong>Scheduled Lambda Invocations: </strong>Automate the Lambda function to run at scheduled intervals. While this solves the problem, it adds the overhead of scheduling and managing Lambda executions.</li><li><strong>Enhanced SNS Alarm Configuration:</strong> Modify the SNS alarm configurations to handle cases where the DLQ is emptied. Unfortunately, this approach proved challenging due to the inherent limitations of SNS alarm settings.</li></ol><h3>Solution Architecture</h3><p>After careful consideration, I crafted a solution using AWS Step Functions — a versatile orchestration service. This Step Function workflow tracks messages in the SQS queues after each run of the main workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*rc8TggVdeWY_ye9bgd0E3w.png" /></figure><p>Alright, let’s dive into the code step by step, starting with the first part, which is the DLQMessageReceiver step.</p><h4>Step 1: DLQMessageReceiver</h4><p>So, the DLQMessageReceiver is the starting point of our state machine. It&#39;s like the entry gate where everything begins. Here&#39;s what it does:</p><pre>&quot;DLQMessageReceiver&quot;: {<br>  &quot;Type&quot;: &quot;Parallel&quot;,<br>  &quot;Branches&quot;: [<br>    {<br>      &quot;StartAt&quot;: &quot;ProcessDLQ&quot;,<br>      &quot;States&quot;: {<br>        &quot;ProcessDLQ&quot;: {<br>          ...<br>        }<br>      }<br>    }<br>  ],<br>  &quot;Parameters&quot;: {<br>    &quot;DLQs&quot;: [<br>      {<br>        &quot;QueueUrl&quot;: &quot;first_dlq_queue_url&quot;<br>      },<br>      {<br>        &quot;QueueUrl&quot;: &quot;second_dlq_queue_url&quot;<br>      }<br>    ]<br>  },<br>  &quot;End&quot;: true<br>}</pre><p>This part sets up the overall structure of our state machine. It’s a Parallel state, meaning it can handle multiple things at once, but in our case, we’re just dealing with one branch. Here’s what we’re doing:</p><ul><li>We have some DLQs that we want to check for unprocessed messages.</li><li>We start by specifying the DLQs we want to monitor. For example, “first_dlq_queue_url” and “second_dlq_queue_url”.</li><li>Once we’ve defined our DLQs, we move on to the next step, which is processing each DLQ to see if there are any unprocessed messages.</li></ul><p><strong>Note: This solution is designed to be scalable, allowing monitoring of multiple Dead Letter Queues (DLQs) for unprocessed messages.</strong></p><p>This scalable approach ensures that the solution can accommodate an increasing number of queues without significant modifications, providing flexibility and adaptability to evolving workflow demands.</p><h4>Step 2: ProcessDLQ</h4><p>Now, let’s write the code for processing each DLQ. This is where the real action happens:</p><pre>&quot;ProcessDLQ&quot;: {<br>  &quot;Type&quot;: &quot;Map&quot;,<br>  &quot;ItemsPath&quot;: &quot;$.DLQs&quot;,<br>  &quot;MaxConcurrency&quot;: 1,<br>  &quot;Iterator&quot;: {<br>    &quot;StartAt&quot;: &quot;ReceiveMessages&quot;,<br>    &quot;States&quot;: {<br>      &quot;ReceiveMessages&quot;: {<br>        ...<br>      }<br>    }<br>  },<br>  &quot;End&quot;: true<br>}</pre><p>In this step, we’re using a Map state, which allows us to iterate over each DLQ in the list. Here’s what each part does:</p><ul><li>&quot;Type&quot;: &quot;Map&quot;: This indicates that we&#39;re using a Map state, which iterates over a list of items (in our case, DLQs).</li><li>&quot;ItemsPath&quot;: &quot;$.DLQs&quot;: This specifies the path to the array of DLQs that we defined earlier in the DLQMessageReceiver step.</li><li>&quot;MaxConcurrency&quot;: 1: This ensures that only one DLQ is processed at a time to avoid overwhelming our system.</li><li>&quot;Iterator&quot;: This is where we define what happens during each iteration, starting with the ReceiveMessages state.</li></ul><h4>Step 3: ReceiveMessages</h4><p>Let’s move forward and write the code for the ReceiveMessages state. This state is responsible for retrieving messages from the SQS queue associated with each DLQ.</p><p>Here’s the structure of the ReceiveMessages state within the Iterator of the ProcessDLQ step:</p><pre>&quot;ReceiveMessages&quot;: {<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:sqs:receiveMessage&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;QueueUrl.$&quot;: &quot;$.QueueUrl&quot;<br>  },<br>  &quot;Next&quot;: &quot;CheckMessages&quot;,<br>  &quot;ResultPath&quot;: &quot;$.receivedMessage&quot;<br>}</pre><p>Now, let’s break down what each part does:</p><ul><li>&quot;Type&quot;: &quot;Task&quot;: This indicates that we&#39;re using a Task state, which performs a specific action.</li><li>&quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:sqs:receiveMessage&quot;: This specifies the ARN (Amazon Resource Name) for the receiveMessage action in SQS. It tells AWS Step Functions where to find the code or service to execute.</li><li>&quot;Parameters&quot;: {&quot;QueueUrl.$&quot;: &quot;$.QueueUrl&quot;}: Here, we&#39;re passing the QueueUrl parameter to the receiveMessage action. The $.QueueUrl references the QueueUrl of the current DLQ being processed.</li><li>&quot;Next&quot;: &quot;CheckMessages&quot;: This specifies the next state to transition to after the task (receiving messages) is completed.</li><li>&quot;ResultPath&quot;: &quot;$.receivedMessage&quot;: This specifies where the output of the task (received messages) should be stored in the state&#39;s output.</li></ul><p>Now, we’re ready to move on to the next step, which is checking if messages were received from the SQS queue.</p><h4>Step 4: CheckMessages</h4><p>Let’s proceed by writing the code for the CheckMessages state. This state is responsible for determining whether messages were received from the SQS queue associated with each DLQ.</p><p>Here’s the structure of the CheckMessages state within the Iterator of the ProcessDLQ step:</p><pre>&quot;CheckMessages&quot;: {<br>  &quot;Type&quot;: &quot;Choice&quot;,<br>  &quot;Choices&quot;: [<br>    {<br>      &quot;Variable&quot;: &quot;$.receivedMessage.Messages&quot;,<br>      &quot;IsPresent&quot;: true,<br>      &quot;Next&quot;: &quot;PublishAlert&quot;<br>    }<br>  ],<br>  &quot;Default&quot;: &quot;EndStateMachine&quot;<br>}</pre><p>Now, let’s break down what each part does:</p><ul><li>&quot;Type&quot;: &quot;Choice&quot;: This indicates that we&#39;re using a Choice state, which allows us to make decisions based on the output of the previous state.</li><li>&quot;Choices&quot;: This is an array of conditions to evaluate. In our case, we&#39;re checking if the &quot;Messages&quot; array is present in the output of the ReceiveMessages state.</li><li>&quot;Variable&quot;: &quot;$.receivedMessage.Messages&quot;: This specifies the variable to evaluate, which is the &quot;Messages&quot; array from the output of the ReceiveMessages state.</li><li>&quot;IsPresent&quot;: true: This condition checks if the &quot;Messages&quot; array is present.</li><li>&quot;Next&quot;: &quot;PublishAlert&quot;: If the &quot;Messages&quot; array is present, we transition to the PublishAlert state to send an alert about unprocessed messages.</li><li>&quot;Default&quot;: &quot;EndStateMachine&quot;: If the &quot;Messages&quot; array is not present, we transition to the end of the state machine, indicating that no unprocessed messages were found.</li></ul><p>Now that we have defined the CheckMessages state, we&#39;re ready to move on to the final step, which is publishing an alert if unprocessed messages are found</p><h4>Step 5: PublishAlert</h4><p>Let’s proceed by writing the code for the final step, which is the PublishAlert state. This state is responsible for publishing an alert to an SNS topic if unprocessed messages are found in the SQS queue.</p><p>Here’s the structure of the PublishAlert state:</p><pre>&quot;PublishAlert&quot;: {<br>  &quot;Type&quot;: &quot;Task&quot;,<br>  &quot;Resource&quot;: &quot;arn:aws:states:::sns:publish&quot;,<br>  &quot;Parameters&quot;: {<br>    &quot;TopicArn&quot;: &quot;${AlertSNSTopicArn}&quot;,<br>    &quot;Message.$&quot;: &quot;States.Format(&#39;ALERT: Unprocessed messages found in: {}&#39;, $.QueueUrl)&quot;<br>  },<br>  &quot;End&quot;: true<br>}</pre><h3>Let’s take a closer look at the execution of the devised Step Function solution:</h3><ol><li><strong>Email Sent:</strong> In the first iteration, specifically concerning the first queue, the Step Function successfully executed. The workflow identified unprocessed messages in the specified Dead Letter Queue (DLQ), retrieved them, and sent an alert email through the configured SNS topic.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*rc8TggVdeWY_ye9bgd0E3w.png" /></figure><p>2. <strong>Email Not Sent:</strong> Now, let’s explore the second iteration, focusing on the second queue. In this case, the Step Function executed successfully, but no email notification was sent as there were no messages found in the second DLQ during this particular execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*VswWw4zrg_JEaIhh2Qlkew.png" /></figure><h3>The Benefits</h3><ol><li><strong>Automated Oversight:</strong> The Step Function solution automates the workflow oversight process, eliminating the need for manual intervention.</li><li><strong>Developer Relief:</strong> Developers are freed from the task of manually clearing queues, reducing their workload and allowing them to focus on more critical aspects of development.</li><li><strong>Timely Notifications:</strong> Email notifications are now sent promptly whenever unprocessed messages are detected, ensuring quick awareness of potential issues.</li><li><strong>Scalability: </strong>The solution is designed to handle any number of queues efficiently. It executes in loops, making it easily scalable to accommodate growing workflow demands.</li></ol><p>Here is the complete code for the Step Function setup:</p><pre>{<br>  &quot;Comment&quot;: &quot;This state machine checks for unprocessed messages in specified Dead Letter Queues (DLQs) and sends an alert if any are found.&quot;,<br>  &quot;StartAt&quot;: &quot;DLQMessageReceiver&quot;,<br>  &quot;States&quot;: {<br>    &quot;DLQMessageReceiver&quot;: {<br>      &quot;Type&quot;: &quot;Parallel&quot;,<br>      &quot;Branches&quot;: [<br>        {<br>          &quot;StartAt&quot;: &quot;ProcessDLQ&quot;,<br>          &quot;States&quot;: {<br>            &quot;ProcessDLQ&quot;: {<br>              &quot;Type&quot;: &quot;Map&quot;,<br>              &quot;ItemsPath&quot;: &quot;$.DLQs&quot;,<br>              &quot;MaxConcurrency&quot;: 1,<br>              &quot;Iterator&quot;: {<br>                &quot;StartAt&quot;: &quot;ReceiveMessages&quot;,<br>                &quot;States&quot;: {<br>                  &quot;ReceiveMessages&quot;: {<br>                    &quot;Type&quot;: &quot;Task&quot;,<br>                    &quot;Resource&quot;: &quot;arn:aws:states:::aws-sdk:sqs:receiveMessage&quot;,<br>                    &quot;Parameters&quot;: {<br>                      &quot;QueueUrl.$&quot;: &quot;$.QueueUrl&quot;<br>                    },<br>                    &quot;Next&quot;: &quot;CheckMessages&quot;,<br>                    &quot;ResultPath&quot;: &quot;$.receivedMessage&quot;<br>                  },<br>                  &quot;CheckMessages&quot;: {<br>                    &quot;Type&quot;: &quot;Choice&quot;,<br>                    &quot;Choices&quot;: [<br>                      {<br>                        &quot;Variable&quot;: &quot;$.receivedMessage.Messages&quot;,<br>                        &quot;IsPresent&quot;: true,<br>                        &quot;Next&quot;: &quot;PublishAlert&quot;<br>                      }<br>                    ],<br>                    &quot;Default&quot;: &quot;EndStateMachine&quot;<br>                  },<br>                  &quot;PublishAlert&quot;: {<br>                    &quot;Type&quot;: &quot;Task&quot;,<br>                    &quot;Resource&quot;: &quot;arn:aws:states:::sns:publish&quot;,<br>                    &quot;Parameters&quot;: {<br>                      &quot;TopicArn&quot;: &quot;${AlertSNSTopicArn}&quot;,<br>                      &quot;Message.$&quot;: &quot;States.Format(&#39;ALERT: Unprocessed messages found in: {}&#39;, $.QueueUrl)&quot;<br>                    },<br>                    &quot;End&quot;: true<br>                  },<br>                  &quot;EndStateMachine&quot;: {<br>                    &quot;Type&quot;: &quot;Succeed&quot;<br>                  }<br>                }<br>              },<br>              &quot;End&quot;: true<br>            }<br>          }<br>        }<br>      ],<br>      &quot;Parameters&quot;: {<br>        &quot;DLQs&quot;: [<br>          {<br>            &quot;QueueUrl&quot;: &quot;first_dlq_queue_url&quot;<br>          },<br>          {<br>            &quot;QueueUrl&quot;: &quot;second_dlq_queue_url&quot;<br>          }<br>        ]<br>      },<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341c55413086" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>