<?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 Dulanjana Lakmal on Medium]]></title>
        <description><![CDATA[Stories by Dulanjana Lakmal on Medium]]></description>
        <link>https://medium.com/@dulanjanalakmal?source=rss-54cbcac0d4c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NPB6muXKFB8XkSA4bTSvjw.jpeg</url>
            <title>Stories by Dulanjana Lakmal on Medium</title>
            <link>https://medium.com/@dulanjanalakmal?source=rss-54cbcac0d4c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:56:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dulanjanalakmal/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[Building a Zero-Downtime EKS Upgrade Pipeline with GitHub Actions (and the Bugs That Broke It…]]></title>
            <link>https://medium.com/@dulanjanalakmal/building-a-zero-downtime-eks-upgrade-pipeline-with-github-actions-and-the-bugs-that-broke-it-14842c3a8c98?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/14842c3a8c98</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[ek]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 09:22:41 GMT</pubDate>
            <atom:updated>2026-07-04T09:22:41.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Zero-Downtime EKS Upgrade Pipeline with GitHub Actions (and the Bugs That Broke It First)</h3><p>Upgrading an EKS cluster safely is an important part of running production workloads on Kubernetes. AWS requires you to keep your cluster version reasonably current, and doing that manually every time is slow and easy to get wrong. This article explains how I built a GitHub Actions pipeline that upgrades an EKS cluster’s control plane, add-ons, and node groups automatically, with no downtime to running workloads, and walks through the bugs I ran into while building it.</p><p>Full source code: <a href="http://github.com/lakmal-ya/eks-upshift">github.com/lakmal-ya/eks-upshift</a></p><p>The Problem</p><p>EKS clusters need to be upgraded one minor Kubernetes version at a time, and each version has a limited support window. If you fall behind, you either pay AWS for extended support or upgrade multiple versions at once, which is riskier. Most teams handle this manually: someone schedules a maintenance window, cordons and drains nodes by hand, and hopes nothing goes wrong. This works, but it does not scale well and depends heavily on whoever is doing it that day.</p><p>The Solution</p><p>I built a pipeline that only needs one person to trigger it and approve a single gate before the control plane upgrade starts. Everything else, add-on upgrades and node group upgrades, runs automatically afterward. Every step checks the current state of the cluster before doing anything, so the pipeline can be re-run safely at any point if something fails partway through.</p><p>First Approach: Blue-Green Node Group Swap</p><p>My first idea for upgrading node groups was to do a manual blue-green swap:</p><ol><li>Create a temporary node group on the new Kubernetes version.</li><li>Cordon and drain the original node group so pods move to the temporary nodes.</li><li>Delete the original node group and recreate it with the same name on the new version.</li><li>Cordon and drain the temporary node group so pods move back.</li><li>Delete the temporary node group.</li></ol><p>This works, but it needs about 150 lines of bash, and it requires kubectl access to the cluster to run the cordon and drain commands. If the cluster’s API endpoint is private, this becomes a bigger problem, because a normal GitHub-hosted runner cannot reach it. Getting around that meant setting up a self-hosted runner inside the VPC and giving it Kubernetes RBAC access, which added a lot of extra infrastructure just to upgrade a node group.</p><p>Better Approach: Native Rolling Update</p><p>AWS already provides a command that does the same job: update-nodegroup-version. It brings up new nodes on the target version, drains the old nodes while respecting PodDisruptionBudgets, and removes them, all on AWS’s side. This means the pipeline does not need kubectl access or any Kubernetes RBAC setup at all, since AWS handles the draining itself.</p><p>The node group upgrade script became much simpler:</p><p>current_version=$(aws eks describe-nodegroup — cluster-name “$CLUSTER” — nodegroup-name “$NG” — query ‘nodegroup.version’ — output text)</p><p>if [[ “$current_version” == “$TARGET” ]]; then echo “Nodegroup $NG already at k8s $TARGET, skipping” exit 0 fi</p><p>UPDATE_ID=$(aws eks update-nodegroup-version — cluster-name “$CLUSTER” — nodegroup-name “$NG” — kubernetes-version “$TARGET” — query ‘update.id’ — output text)</p><p>wait_for_cluster_update “$CLUSTER” “$UPDATE_ID” — nodegroup-name “$NG”</p><p>Pipeline Overview</p><p>The final pipeline runs four jobs in order:</p><ol><li>Preflight — checks that the target version is exactly one minor version ahead of the current version, and that compatible add-on versions exist.</li><li>Upgrade control plane — behind a manual approval gate, upgrades the control plane and waits for it to finish.</li><li>Upgrade add-ons — upgrades the CNI, DNS, and kube-proxy add-ons to versions compatible with the new control plane.</li><li>Migrate node groups — loops through each node group and runs the native rolling update on it.</li></ol><p>Each job checks whether its work is already done before doing anything, so re-running the pipeline after a failure is always safe.</p><p>Bugs Found During Development</p><p>All of these bugs produced the same symptom: a plain, unhelpful exit code with no useful error message in the CI logs.</p><ol><li>The update status check needs to know what type of update it is checking.</li></ol><p>Checking an update’s status works with just a cluster name and update ID for control plane upgrades. For add-on or node group upgrades, the same command fails with a “resource not found” error unless you also pass the add-on name or node group name. The error message makes it look like the update ID itself is wrong, which is misleading.</p><ol><li>Update IDs are not immediately queryable.</li></ol><p>Even after fixing the first issue, a freshly created update can return “not found” for a few seconds before AWS finishes indexing it. I added a short retry loop that tolerates this specific error for the first 10–20 seconds. I confirmed this by checking the update directly in the AWS console, where it had actually completed successfully every time, even though my script reported it as failed.</p><ol><li>A flag name collided with a global CLI flag.</li></ol><p>The node group upgrade command needs a flag for the target Kubernetes version. I had named it the same as the AWS CLI’s own global version flag, which prints the CLI version and exits without calling any API. Because of this, the upgrade command never actually ran, but it still returned a successful exit code, with the CLI’s version string captured as if it were a real update ID. I only found this by checking the node group’s update history directly in AWS and seeing that no upgrade attempt had ever been recorded.</p><ol><li>A reserved bash variable name broke the whole script silently.</li></ol><p>The workflow used a variable named GROUPS to hold the list of node group names:</p><p>IFS=’,’ read -ra GROUPS &lt;&lt;&lt; “$NODE_GROUPS_INPUT” for ng in “${GROUPS[@]}”; do bash migrate-nodegroup.sh “$ng” “$TARGET_VERSION” done</p><p>This failed instantly every time, with no output at all. It turns out GROUPS is a reserved variable in bash that normally holds the current user’s group IDs. Writing to it silently fails and returns a non-zero exit code, without actually changing the variable. Because this was the first line of the script and the script uses set -e, the entire step exited immediately, before the loop or any of my own log statements ever ran. Renaming the variable fixed it right away.</p><p>I also ran into a process issue worth mentioning: GitHub Actions’ “Re-run failed jobs” option reuses the exact commit from the original run. If you push a fix and use “re-run” instead of starting a new workflow run, it will silently run the old code again. I lost time to this more than once before I made it a habit to always trigger a fresh run after pushing any fix.</p><p>Conclusion</p><p>Every one of these bugs looked identical from the CI logs, a bare exit code with no explanation, and every one of them had a different root cause. The one approach that consistently worked was checking the actual state in AWS directly instead of trusting the pipeline’s own output. This process resulted in a pipeline that upgrades an EKS cluster’s control plane, add-ons, and node groups safely, with no manual steps beyond one approval.</p><p>Follow My Journey</p><p>If you found this useful and want to follow more of what I’m building, feel free to connect with me on GitHub. I’ll keep sharing more DevOps and cloud automation projects as I work on them.</p><p><a href="http://github.com/lakmal-ya/eks-upshift">github.com/lakmal-ya</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14842c3a8c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Modular Capability Plugins (MCP) with Amazon Q on Arch Linux]]></title>
            <link>https://blog.stackademic.com/setting-up-modular-capability-plugins-mcp-with-amazon-q-on-arch-linux-1933d11fc491?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1933d11fc491</guid>
            <category><![CDATA[amazon-q]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Wed, 14 May 2025 22:24:46 GMT</pubDate>
            <atom:updated>2025-05-15T14:56:25.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xu5xx0945E_AfZ9GOmW1Wg.png" /></figure><p>Hello everyone!</p><p>Today I’m writing about one of the most viral topics in the developer world right now: Modular Capability Plugins (MCP).</p><h3>What are MCPs?</h3><p>MCPs (Modular Capability Plugins) are specialized extensions that enhance AI assistants like Amazon Q with specific capabilities. Think of MCPs as “super-powered tool belts” for AI assistants — they give these assistants specialized knowledge and abilities to perform specific tasks far better than they could with general training alone.</p><p>To use a simple metaphor: if Amazon Q is like a smartphone out of the box, MCPs are like specialized apps you install to transform it from a general-purpose device into a professional-grade tool for specific tasks. Just as you might install Photoshop for image editing or Final Cut Pro for video production, MCPs add specialized capabilities to your AI assistant.</p><h3>My Experience with Amazon Q MCPs</h3><p>For the past month, I’ve been using Amazon Q Chat service for my day-to-day DevOps and CloudOps tasks. It’s been an incredibly helpful tool that streamlines my workflow. Since I’m running Arch Linux on my personal laptop, I decided to set up several specialized MCPs to enhance my productivity.</p><h3>The Challenge</h3><p>As a cloud engineer, I frequently encounter several time-consuming tasks:</p><ul><li><strong>AWS architecture diagrams</strong> have always been a critical but manual and time-consuming task for developers and cloud architects</li><li><strong>Searching through AWS documentation</strong> efficiently can be challenging</li><li><strong>Following Terraform best practices</strong> and security-first development workflows requires constant reference checking</li></ul><h3>The Solution: Custom MCPs</h3><p>To address these challenges, I’ve set up the following MCPs:</p><ol><li><strong>awslabs.aws-diagram-mcp-server</strong> — For generating AWS architecture diagrams automatically</li><li><strong>awslabs.aws-documentation-mcp-server</strong> — For searching AWS documentation using the official AWS search API, getting content recommendations, and converting documentation to markdown format</li><li><strong>awslabs.terraform-mcp-server</strong> — For AWS Terraform best practices, security-first development workflows, Checkov integration, AWS provider documentation, AWS-IA GenAI modules, and Terraform workflow execution</li></ol><h3>Setup Guide for Arch Linux</h3><h3>Prerequisites</h3><p>Before beginning, make sure you have:</p><ul><li>Python 3.10</li><li>python-uv (Python packaging tool)</li><li>AWS CLI configured locally with an AWS Builder ID for accessing Amazon Q</li><li>GraphViz installed (<a href="https://www.graphviz.org/">https://www.graphviz.org/</a>)</li></ul><h3>Installation Steps</h3><ol><li><strong>Install Amazon Q on Arch Linux</strong>:</li></ol><pre>curl --proto &#39;=https&#39; --tlsv1.2 -sSf &quot;https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip&quot; -o &quot;q.zip&quot;<br>unzip q.zip<br>./q/install.sh</pre><ol><li>After installation, you should see an “amazonq” folder under your .aws folder.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*sbNOf8qVS5U5ve-pfLDEXw.png" /></figure><ol><li><strong>Create an MCP configuration file</strong>:</li></ol><pre>vim ~/.aws/amazonq/mcp.json</pre><ol><li><strong>Add the following content</strong> to configure all three MCP servers:</li></ol><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;awslabs.terraform-mcp-server&quot;: {<br>      &quot;command&quot;: &quot;uvx&quot;,<br>      &quot;args&quot;: [&quot;awslabs.terraform-mcp-server@latest&quot;],<br>      &quot;env&quot;: {<br>        &quot;FASTMCP_LOG_LEVEL&quot;: &quot;ERROR&quot;<br>      },<br>      &quot;disabled&quot;: false,<br>      &quot;autoApprove&quot;: []<br>    },<br>   &quot;awslabs.aws-documentation-mcp-server&quot;: {<br>        &quot;command&quot;: &quot;uvx&quot;,<br>        &quot;args&quot;: [&quot;awslabs.aws-documentation-mcp-server@latest&quot;],<br>        &quot;env&quot;: {<br>          &quot;FASTMCP_LOG_LEVEL&quot;: &quot;ERROR&quot;<br>        },<br>        &quot;disabled&quot;: false,<br>        &quot;autoApprove&quot;: []<br>    },<br>   &quot;awslabs.aws-diagram-mcp-server&quot;: {<br>      &quot;command&quot;: &quot;uvx&quot;,<br>      &quot;args&quot;: [&quot;awslabs.aws-diagram-mcp-server&quot;],<br>      &quot;env&quot;: {<br>        &quot;FASTMCP_LOG_LEVEL&quot;: &quot;ERROR&quot;<br>      },<br>      &quot;autoApprove&quot;: [],<br>      &quot;disabled&quot;: false<br>    }<br>  }<br>}</pre><p><strong>Note</strong>: If you don’t need all three MCPs, you can remove the ones you don’t want from your mcp.json file.</p><h3>Using Your MCPs</h3><ol><li>Open Amazon Q — you should see it initializing the MCP servers</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3m48WI17-058EmDnLM8y4g.png" /></figure><ol><li>Enter /tools in the chat to check what tools you have access to via Amazon Q MCPs</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojA1lrjJ27i7KMsy5nYKMw.png" /></figure><ol><li>If you encounter any issues, double-check your Python version, the uv package installation, and that GraphViz is properly installed</li></ol><h3>Testing Your Setup</h3><p>To verify everything is working correctly, try a sample prompt like:</p><pre>generate an aws architecture diagram for sample s3 bucket with cloudfront for hosting static website</pre><p>Voilà! Your setup is complete — it’s time to celebrate!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pfogtxNC6Do20duu" /><figcaption>Photo by <a href="https://unsplash.com/@smallcamerabigpictures?utm_source=medium&amp;utm_medium=referral">Joost Crop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee.</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1933d11fc491" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/setting-up-modular-capability-plugins-mcp-with-amazon-q-on-arch-linux-1933d11fc491">Setting Up Modular Capability Plugins (MCP) with Amazon Q on Arch Linux</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Script to Manage Azure Alerts]]></title>
            <link>https://medium.com/@dulanjanalakmal/python-script-to-manage-azure-alerts-63f4c578930f?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f4c578930f</guid>
            <category><![CDATA[azure-monitor]]></category>
            <category><![CDATA[azure-alerts]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 16:59:53 GMT</pubDate>
            <atom:updated>2025-02-11T16:59:53.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever found yourself frantically toggling Azure alerts during a maintenance window, clicking through countless menus while your team waits? I’ve been there. After one particularly chaotic deployment night, I decided enough was enough. Today, I’m sharing a practical solution that transformed how we manage Azure alerts using Python.</p><h3>The Problem with Manual Alert Management</h3><p>Picture this: It’s 2 AM, you’re about to start a critical system upgrade, and you need to disable dozens of Azure alerts to avoid false positives. You could click through the Azure portal manually, but let’s be honest — that’s neither efficient nor foolproof. What if you miss one? What if you forget to re-enable them afterward?</p><h3>Enter Python Automation</h3><p>The solution? A simple yet powerful Python script that can toggle multiple Azure alerts with a single command. But before we dive into the code, let’s set up our environment properly.</p><h3>Setting Up Your Development Environment</h3><p>First things first, we need to install the right Azure packages. Create a requirements.txt file with these essential dependencies:</p><pre>azure-identity<br>azure-mgmt-monitor<br>azure-mgmt-loganalytics</pre><p>A quick pip install -r requirements.txt, and you&#39;re ready to roll. These packages provide everything we need to interact with Azure&#39;s monitoring services programmatically.</p><h3>The Magic Script: Breaking It Down</h3><p>Let’s look at the core functionality that makes this work. Our script handles both metric and log search alerts — two different beasts in the Azure ecosystem. Here’s the interesting part: we don’t need separate workflows for each type. The script intelligently detects the alert type and handles it appropriately.</p><p>The heart of our solution lies in this elegant piece of logic:</p><pre>for alert_name in alert_names_to_modify:<br>    try:<br>        # Try handling it as a metric alert first<br>        metric_alert = monitor_client.metric_alerts.get(resource_group_name, alert_name)<br>        metric_alert.enabled = (action == &#39;enable&#39;)<br>        monitor_client.metric_alerts.create_or_update(resource_group_name, alert_name, metric_alert)<br>    except Exception:<br>        # If that fails, try as a log search alert<br>        subprocess.run([<br>            &quot;az&quot;, &quot;monitor&quot;, &quot;scheduled-query&quot;, &quot;update&quot;,<br>            &quot;-g&quot;, resource_group_name,<br>            &quot;-n&quot;, alert_name,<br>            &quot;--disabled&quot;, str(action == &#39;disable&#39;).lower()<br>        ], check=True)</pre><h3>Real-World Application</h3><p>Here’s where this script really shines. Let’s say you’re managing a microservices architecture with dozens of services, each with its own set of alerts. During deployments or maintenance windows, you can:</p><ol><li>Disable all alerts with a single command</li><li>Perform your maintenance work without false alarms</li><li>Re-enable everything just as easily when you’re done</li></ol><p>The best part? The script provides clear feedback about what it’s doing, so you’re never left wondering about the state of your alerts.</p><h3>Pro Tips from the Trenches</h3><p>After using this script in production, here are some valuable lessons learned:</p><ol><li><strong>Keep a List of Critical Alerts</strong>: Maintain a separate list of alerts that should never be disabled. You can add a simple check in the script to prevent accidental modifications.</li><li><strong>Add Logging</strong>: Consider adding detailed logging to track when alerts are modified and by whom. This is invaluable for audit trails.</li><li><strong>Use Environment Variables</strong>: Instead of hardcoding the subscription ID and resource group, use environment variables for better security and flexibility.</li></ol><h3>Looking Ahead</h3><p>This script is just the beginning. You could extend it to:</p><ul><li>Schedule alert modifications for planned maintenance windows</li><li>Integrate it with your CI/CD pipeline</li><li>Add support for batch operations across multiple resource groups</li><li>Include alert configuration backup and restore functionality</li></ul><h3>Conclusion</h3><p>Automation doesn’t always mean building complex systems. Sometimes, it’s about taking those repetitive, error-prone tasks and turning them into simple, reliable operations. This Python script is a perfect example — it takes a common operational headache and transforms it into a one-liner.</p><p>Remember, the goal isn’t just to automate tasks; it’s to free up your time and mental energy for more important challenges. Start with this script, adapt it to your needs, and keep building tools that make your life easier.</p><p><em>Want to take this further? The complete code is available in our </em><a href="https://github.com/lakmal-ya/azure-alerts-manager.git"><em>GitHub repository</em></a><em>. Feel free to fork it, improve it, and share your enhancements with the community!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KgntAjOsHYF5WcuA" /><figcaption>Photo by <a href="https://unsplash.com/@haleytruong?utm_source=medium&amp;utm_medium=referral">Haley Truong</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f4c578930f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Linux Filesystems: Best Practices for DevOps Security]]></title>
            <link>https://medium.com/@dulanjanalakmal/securing-linux-filesystems-best-practices-for-devops-security-9f57117fe30b?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f57117fe30b</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 14:28:49 GMT</pubDate>
            <atom:updated>2024-09-03T14:28:49.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeKTf4d6VpkI96nWTTtHoQ.png" /></figure><p>In the ever-evolving landscape of DevOps and cloud computing, securing Linux filesystems remains a critical aspect of maintaining robust system integrity. This article explores best practices for DevOps professionals to enhance the security of Linux filesystems, ensuring data protection and system reliability.</p><p>1. Introduction to Linux Filesystem Security</p><p>Linux filesystems form the backbone of data storage and management in most DevOps environments. Securing these filesystems is crucial to protect sensitive information, maintain system stability, and prevent unauthorized access. A comprehensive security strategy involves multiple layers of protection, from basic file permissions to advanced encryption techniques.</p><p>2. Implementing Proper File Permissions and Ownership</p><p>The foundation of Linux filesystem security lies in its permission model:</p><p>- Use the principle of least privilege: Grant only the minimum necessary permissions.<br>- Regularly audit and update file permissions using commands like chmod and chown.<br>- Implement umask settings to control default permissions for new files and directories.</p><p>Example:<br># Set restrictive permissions on a sensitive file<br>chmod 600 /path/to/sensitive_file</p><p># Change ownership to a specific user and group<br>chown user:group /path/to/directory</p><p>3. Using Access Control Lists (ACLs) for Fine-Grained Control</p><p>When standard permissions are not enough, ACLs provide more granular control:</p><p>- Use setfacl and getfacl to manage ACLs.<br>- ACLs allow you to set permissions for specific users or groups without changing the base permissions.</p><p>Example:<br># Grant read access to a specific user<br>setfacl -m u:username:r /path/to/file</p><p># View ACLs on a file<br>getfacl /path/to/file</p><p>4. Securing Mount Points and Partitions</p><p>Properly configuring mount points and partitions enhances security:</p><p>- Use the noexec, nosuid, and nodev mount options where appropriate.<br>- Separate sensitive directories into different partitions.<br>- Implement disk quotas to prevent resource exhaustion attacks.</p><p>Example in /etc/fstab:<br>/dev/sda2 /tmp ext4 defaults,noexec,nosuid,nodev 0 0</p><p>5. Encrypting Sensitive Data and Filesystems</p><p>Encryption adds a crucial layer of protection:</p><p>- Use LUKS (Linux Unified Key Setup) for full-disk encryption.<br>- Implement eCryptfs or EncFS for directory-level encryption.<br>- Consider using dm-crypt for block device encryption.</p><p>Example:<br># Create an encrypted container<br>cryptsetup luksFormat /dev/sdb1</p><p># Open the encrypted container<br>cryptsetup luksOpen /dev/sdb1 secret_data</p><p>6. Regular Security Audits and Monitoring</p><p>Continuous monitoring is essential for maintaining security:</p><p>- Use tools like Auditd to monitor filesystem changes.<br>- Implement intrusion detection systems (IDS) like AIDE or Tripwire.<br>- Regularly scan for vulnerabilities using tools like Lynis.</p><p>Example:<br># Set up a basic audit rule<br>auditctl -w /etc/passwd -p wa -k passwd_changes</p><p>7. Backup and Recovery Strategies</p><p>A robust backup strategy is crucial for data protection and disaster recovery:</p><p>- Implement regular, automated backups using tools like rsync or Bacula.<br>- Store backups in secure, off-site locations.<br>- Regularly test recovery procedures to ensure data integrity.</p><p>Example rsync backup:<br>rsync -avz — delete /source/directory/ user@remote:/backup/directory/</p><p>8. DevOps-Specific Considerations for Filesystem Security</p><p>In a DevOps context, additional considerations include:</p><p>- Implement Infrastructure as Code (IaC) to manage and version control filesystem configurations.<br>- Use containerization technologies like Docker to isolate applications and their filesystems.<br>- Employ secrets management tools to handle sensitive data securely.</p><p>9. Automated Security Checks in CI/CD Pipelines</p><p>Integrate security checks into your CI/CD pipelines:</p><p>- Use tools like CIS-CAT or OpenSCAP to automate compliance checks.<br>- Implement pre-commit hooks to catch security issues before they enter the codebase.<br>- Regularly scan Docker images and containers for vulnerabilities.</p><p>Example GitLab CI/CD job:<br>security_scan:<br> stage: test<br> script:<br> — lynis audit system<br> — docker scan my-image:latest</p><p>10. Conclusion and Best Practices Summary</p><p>Securing Linux filesystems in a DevOps environment requires a multi-faceted approach:</p><p>1. Implement and regularly review file permissions and ACLs.<br>2. Use encryption for sensitive data and filesystems.<br>3. Secure mount points and partitions with appropriate options.<br>4. Conduct regular security audits and monitoring.<br>5. Maintain robust backup and recovery strategies.<br>6. Integrate security checks into CI/CD pipelines.<br>7. Stay informed about the latest security threats and best practices.</p><p>By following these best practices, DevOps teams can significantly enhance the security of their Linux filesystems, protecting valuable data and maintaining system integrity in an increasingly complex and threat-prone digital landscape.</p><p>If you found this guide helpful, give it a clap! 👏</p><p>Don&#39;t forget to follow me for more insightful content on AWS best practices, cloud security, and technology updates! 🚀</p><p>If you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f57117fe30b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Dynamic Routing in Amazon CloudFront with Lambda@Edge for a Next.js Application]]></title>
            <link>https://blog.stackademic.com/handling-dynamic-routing-in-amazon-cloudfront-with-lambda-edge-for-a-next-js-application-a946887f4422?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a946887f4422</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nextjsrouting]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 07:12:21 GMT</pubDate>
            <atom:updated>2024-07-29T00:22:02.763Z</atom:updated>
            <content:encoded><![CDATA[<p>When deploying a Next.js application on AWS, managing dynamic and static routes can become complex, especially when using Amazon CloudFront as a CDN. This article will guide you through handling dynamic routing in CloudFront using Lambda@Edge, ensuring that your Next.js application serves the correct HTML files for specific routes.</p><p>In a Next.js application, certain routes like /features/, /privacy/, and /terms/ need to serve specific HTML files. Additionally, the application must handle dynamic routes and static assets properly. CloudFront might incorrectly serve the index.html file for all routes without proper configuration.</p><p>We can use a Lambda@Edge function to address this to intercept and rewrite requests based on predefined rules. This function will:</p><ol><li>Serve specific HTML files for predefined routes.</li><li>Handle dynamic routes.</li><li>Append .html to suffix-less URIs.</li><li>Append index.html to directory paths.</li><li>Optionally remove trailing slashes.</li></ol><h3>1. Set Up the Lambda Function</h3><p>Create a new Lambda function in AWS and use the following Python script:</p><pre>import re</pre><pre># Configuration settings<br>config = {<br> &#39;suffix&#39;: &#39;.html&#39;,<br> &#39;appendToDirs&#39;: &#39;index.html&#39;,<br> &#39;removeTrailingSlash&#39;: False,<br>}</pre><pre># Regular expressions<br>regex_suffixless = re.compile(r&#39;/[^/.]+$&#39;) # e.g. &quot;/some/page&quot; but not &quot;/&quot;, &quot;/some/&quot; or &quot;/some.jpg&quot;<br>regex_trailing_slash = re.compile(r&#39;.+/&#39;) # e.g. &quot;/some/&quot; or &quot;/some/page/&quot; but not root &quot;/&quot;<br>dynamic_route_regex = re.compile(r&#39;/subpath/\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b&#39;) # e.g /subpath/uuid</pre><pre># Specific routes<br>specific_routes = {<br> &#39;/features&#39;: &#39;/features.html&#39;,<br> &#39;/privacy&#39;: &#39;/privacy.html&#39;,<br> &#39;/terms&#39;: &#39;/terms.html&#39;<br>}</pre><pre>def lambda_handler(event, context):<br> request = event[&#39;Records&#39;][0][&#39;cf&#39;][&#39;request&#39;]<br> uri = request[&#39;uri&#39;]<br> <br> # Logging for debugging<br> print(f&quot;Incoming request URI: {uri}&quot;)</pre><pre> # Check for specific routes<br> if uri in specific_routes:<br> request[&#39;uri&#39;] = specific_routes[uri]<br> print(f&quot;Specific route matched. New request URI: {request[&#39;uri&#39;]}&quot;)<br> return request<br> <br> # Check for dynamic route and retrieve the proper [id].html file<br> if dynamic_route_regex.search(uri):<br> request[&#39;uri&#39;] = &quot;/subpath/[id].html&quot;<br> print(f&quot;Dynamic route matched. New request URI: {request[&#39;uri&#39;]}&quot;)<br> return request<br> <br> # Append &quot;.html&quot; to origin request<br> if config[&#39;suffix&#39;] and regex_suffixless.search(uri):<br> request[&#39;uri&#39;] = uri + config[&#39;suffix&#39;]<br> print(f&quot;Suffixless route matched. New request URI: {request[&#39;uri&#39;]}&quot;)<br> return request<br> <br> # Append &quot;index.html&quot; to origin request<br> if config[&#39;appendToDirs&#39;] and regex_trailing_slash.search(uri):<br> request[&#39;uri&#39;] = uri + config[&#39;appendToDirs&#39;]<br> print(f&quot;Directory route matched. New request URI: {request[&#39;uri&#39;]}&quot;)<br> return request</pre><pre> # Redirect (301) non-root requests ending in &quot;/&quot; to URI without trailing slash<br> if config[&#39;removeTrailingSlash&#39;] and uri != &#39;/&#39; and uri.endswith(&#39;/&#39;):<br> response = {<br> &#39;status&#39;: &#39;301&#39;,<br> &#39;statusDescription&#39;: &#39;Moved Permanently&#39;,<br> &#39;headers&#39;: {<br> &#39;location&#39;: [{<br> &#39;key&#39;: &#39;Location&#39;,<br> &#39;value&#39;: uri[:-1]<br> }]<br> }<br> }<br> print(f&quot;Trailing slash route matched. Redirect to: {uri[:-1]}&quot;)<br> return response</pre><pre> # If nothing matches, return request unchanged<br> print(f&quot;No route matched. Returning original URI: {request[&#39;uri&#39;]}&quot;)<br> return request</pre><h3>2. Deploy the Lambda Function</h3><ol><li><strong>Deploy</strong> this function to AWS Lambda.</li><li><strong>Publish a new version</strong> of the Lambda function.</li></ol><h3>3. Update CloudFront Distribution</h3><ol><li>Go to the CloudFront console and select your distribution.</li><li>Update the behavior that uses the Lambda function for Origin Request events to use the new version of the Lambda function.</li></ol><h3>4. Invalidate CloudFront Cache</h3><p>Invalidate the CloudFront cache to ensure the new configuration is applied.</p><h3>5. Test the Routes</h3><p>Test the predefined routes (/features, /privacy, /terms) to ensure they are correctly rewritten. Additionally, test other random routes to ensure they fallback to index.html or another appropriate page if necessary.</p><p>By using a Lambda@Edge function, we can effectively manage dynamic and static routing in a Next.js application deployed on AWS CloudFront. This approach ensures that specific routes serve the correct HTML files, dynamic routes are handled appropriately, and static assets are served without issues.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a946887f4422" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/handling-dynamic-routing-in-amazon-cloudfront-with-lambda-edge-for-a-next-js-application-a946887f4422">Handling Dynamic Routing in Amazon CloudFront with Lambda@Edge for a Next.js Application</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a New Ubuntu Server User and Converting SSH Key Format from OpenSSH to RSA]]></title>
            <link>https://blog.stackademic.com/creating-a-new-ubuntu-server-user-and-converting-ssh-key-format-from-openssh-to-rsa-1a23e7f4bc1a?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a23e7f4bc1a</guid>
            <category><![CDATA[openssh]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[rsa-algorithm]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 07:04:04 GMT</pubDate>
            <atom:updated>2024-07-29T00:22:18.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7ouMvIRw6ytg3AI" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating users with secure SSH access is crucial when managing a server. This guide will walk you through creating a new user on an Ubuntu server, generating an SSH key pair for them, and converting the SSH key from the default OpenSSH format to the traditional RSA format.</p><h3>Step 1: Create a New User</h3><ol><li><strong>Connect to your server:</strong> Open your terminal and connect to your Ubuntu server via SSH:</li></ol><pre>ssh your-username@your-server-ip</pre><p><strong>2. Create the new user:</strong> Use the following command to create a new user named “User_1”:</p><pre>sudo adduser User_1</pre><p>You will be prompted to set a password and provide some additional information for the new user. Fill out the information or press Enter to skip any field.</p><h3>Step 2: Generate an SSH Key Pair for the User</h3><ol><li><strong>Switch to the new user:</strong></li></ol><pre>sudo su - User_1</pre><p>2. <strong>Create the </strong><strong>.ssh directory:</strong></p><pre>mkdir -p ~/.ssh<br>chmod 700 ~/.ssh</pre><p>3. Generate an SSH key pair (in OpenSSH format by default):</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;User_1 key&quot;</pre><p>Follow the prompts to save the key (press Enter to accept the default file location and optionally set a passphrase).</p><h3>Step 3: Convert the SSH Key from OpenSSH to RSA Format</h3><ol><li><strong>Convert the private key to RSA format:</strong></li></ol><pre>ssh-keygen -p -m PEM -f ~/.ssh/id_rsa</pre><ol><li>When prompted, press Enter to keep the same passphrase (if any).</li><li><strong>Ensure the public key is added to the </strong><strong>authorized_keys file:</strong></li></ol><pre>cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys</pre><h3>Step 4: Verify the Conversion</h3><ol><li><strong>Check the private key format:</strong></li></ol><pre>cat ~/.ssh/id_rsa</pre><p>The output should start with -----BEGIN RSA PRIVATE KEY----- and end with -----END RSA PRIVATE KEY-----.</p><h3>Full Process</h3><p>Here is the full process consolidated:</p><pre># Create the new user<br>sudo adduser User_1</pre><pre># Switch to the new user<br>sudo su - User_1</pre><pre># Create the .ssh directory<br>mkdir -p ~/.ssh<br>chmod 700 ~/.ssh</pre><pre># Generate an SSH key pair (OpenSSH format)<br>ssh-keygen -t rsa -b 4096 -C &quot;User_1 key&quot;</pre><pre># Convert the private key to RSA format<br>ssh-keygen -p -m PEM -f ~/.ssh/id_rsa</pre><pre># Ensure the public key is added to the authorized_keys file<br>cat ~/.ssh/id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys<br>chmod 600 ~/.ssh/authorized_keys</pre><pre># Verify the private key format<br>cat ~/.ssh/id_rsa</pre><p>This process ensures that the user “User_1” is created with an SSH key pair, and the private key is in the traditional RSA format for compatibility with systems that require it.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a23e7f4bc1a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/creating-a-new-ubuntu-server-user-and-converting-ssh-key-format-from-openssh-to-rsa-1a23e7f4bc1a">Creating a New Ubuntu Server User and Converting SSH Key Format from OpenSSH to RSA</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</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 Log Management with Dozzle]]></title>
            <link>https://medium.com/@dulanjanalakmal/simplifying-docker-log-management-with-dozzle-3f88932e84c7?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f88932e84c7</guid>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Tue, 28 May 2024 07:36:42 GMT</pubDate>
            <atom:updated>2024-05-28T10:30:46.798Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to Dozzle</h4><p>In the realm of containerization, monitoring and debugging are critical tasks. To streamline these processes, Dozzle, an open-source project sponsored by Docker OSS, offers a robust solution. Dozzle is a lightweight, web-based log viewer specifically designed to enhance the visibility and manageability of logs from Docker containers. By providing real-time log streaming, filtering, and searching capabilities, Dozzle makes debugging and troubleshooting in a Docker environment significantly more efficient.</p><h4>Key Features of Dozzle</h4><ul><li>Real-Time Log Streaming: Dozzle streams logs in real-time, ensuring that users can monitor their containerized applications as they run. This feature is particularly valuable for catching and resolving issues promptly.</li><li>Filtering and Searching: The ability to filter and search through logs allows users to pinpoint specific entries, which is essential for debugging complex applications.</li><li>Intuitive User Interface: With a user-friendly web interface, Dozzle simplifies the process of accessing and analyzing logs. This interface supports JSON logs with intelligent color coding, enhancing readability and making it easier to identify critical information.</li></ul><h4>Installation and Configuration</h4><p>Dozzle’s ease of installation and configuration makes it an attractive tool for both developers and system administrators. It can be installed and configured with minimal effort, which is crucial for maintaining efficient workflows.</p><p><strong>Using Docker CLI</strong></p><p>The simplest method to set up Dozzle is via the Docker CLI. By mounting the docker.sock file, which is typically found at /var/run/docker.sock, and exposing the port on which Dozzle will listen, users can quickly get Dozzle up and running. The following command demonstrates this setup:</p><pre>docker run --detach --volume=/var/run/docker.sock:/var/run/docker.sock -p 8080:8080 amir20/dozzle</pre><p>This command runs Dozzle in detached mode, mounts the necessary docker.sock file, and maps port 8080 on the host to port 8080 in the container. Users can change the external port using the -p flag if needed.</p><p><strong>Using Docker Compose</strong></p><p>For those managing multiple services, Docker Compose offers a more streamlined configuration process. By incorporating Dozzle into an existing Docker Compose file, users can maintain a clean and organized setup. Here’s an example of a Docker Compose configuration for Dozzle:</p><pre>version: &quot;3&quot;<br>services:<br>  dozzle:<br>    container_name: dozzle<br>    image: amir20/dozzle:latest<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>    ports:<br>      - 9999:8080</pre><p>In this configuration, the Dozzle service is defined with the necessary volume and port mappings, making it easy to integrate into an existing Docker ecosystem.</p><h4>Advanced Usage</h4><p>Dozzle also supports connecting to remote hosts via tcp:// and tls, offering flexibility for monitoring containers across different environments. This feature is particularly useful for administrators managing multiple Docker hosts.</p><h4>Licensing and Maintenance</h4><p>Dozzle is released under the MIT license, ensuring that it remains free and open-source. It is actively maintained by its developer, Amir Raminfar, with regular updates and community contributions enhancing its functionality and reliability.</p><h4>Conclusion</h4><p>In conclusion, Dozzle stands out as an essential tool for anyone working within a Docker environment. Its real-time log streaming, intuitive interface, and ease of installation make it an invaluable resource for monitoring and debugging containerized applications. Whether you’re a developer looking to streamline your workflow or a system administrator managing a complex Docker setup, Dozzle provides the functionality and flexibility needed to efficiently handle log management tasks.</p><h3>Grow the Network. Earn BTRST.</h3><p>Spread the word to potential clients and talent, and if they join and use Braintrust, you’ll get rewarded in BTRST, giving you ownership in the network. All you have to do is share the link!</p><p><a href="https://app.usebraintrust.com/r/dulanjana3/">Refer Clients</a></p><p>Send your link to employers looking for Talent, and you’ll earn 2% of their billings in BTRST for anyone they hire on Braintrust.</p><p>Max $100k in BTRST per client. <a href="https://app.usebraintrust.com/r/dulanjana3/">Learn more about BTRST</a>.</p><p><a href="https://app.usebraintrust.com/r/dulanjana3/">Refer Talent</a></p><p>Invite Talent to sign up using your link, and you’ll earn 1% of their earnings in BTRST for any job they land on Braintrust.</p><p>Max $100k in BTRST per client and $10k in BTRST per talent. Must sign up using your referral link. <a href="https://app.usebraintrust.com/r/dulanjana3/">Learn more about BTRST</a>.</p><h3>Happy Automating!</h3><p>If you found this guide helpful, give it a clap! 👏</p><p>For more insightful content on AWS best practices, cloud security, and technology updates, don’t forget to follow me! 🚀</p><p>And if you enjoyed this information and feel like supporting my virtual endeavors, consider buying me a ☕️ coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f88932e84c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Redis Cluster Deployment with Docker Compose]]></title>
            <link>https://medium.com/@dulanjanalakmal/simplifying-redis-cluster-deployment-with-docker-compose-d6f9abebd31b?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f9abebd31b</guid>
            <category><![CDATA[redis-cluster]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 21:22:16 GMT</pubDate>
            <atom:updated>2024-04-29T21:24:24.217Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s dynamic tech landscape, orchestrating containerized applications has become a standard practice, leveraging tools like Docker Compose to streamline deployment processes. Redis, renowned for its blazing fast in-memory data storage and retrieval, stands as a quintessential component in modern microservices architectures. However, configuring Redis clusters manually can be daunting. Enter Docker Compose, a powerful tool for defining and running multi-container Docker applications. In this article, we’ll explore how Docker Compose simplifies the deployment of Redis clusters, utilizing the declarative syntax of YAML files to orchestrate multiple Redis instances seamlessly.</p><p>Prerequisites</p><p>Before diving into the deployment process of a Redis cluster using Docker Compose, ensure that you have the necessary prerequisites set up on your system. Follow these steps to prepare your environment:</p><p>1. Installing Docker CE</p><p>Amazon Linux 2 introduces changes to the Docker installation process. Ensure Docker CE is installed on your system by following these steps:b</p><pre>sudo amazon-linux-extras install docker<br>sudo service docker start<br>sudo usermod -a -G docker ec2-user</pre><p>To configure Docker to start automatically upon system boot, execute:</p><pre>sudo chkconfig docker on</pre><p>After installing Docker Finally, to ensure all changes take effect, reboot your system:</p><pre>sudo reboot</pre><p>2. Installing Docker Compose</p><p>Docker Compose simplifies the management of multi-container Docker applications. Follow these steps to install Docker Compose on your system:</p><pre># Copy the appropriate docker-compose binary from GitHub<br>sudo curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose<br># Fix permissions after download<br>sudo chmod +x /usr/local/bin/docker-compose<br># Verify the installation<br>docker-compose version</pre><p>With these prerequisites in place, you’re now ready to proceed with deploying the Redis cluster using Docker Compose.</p><p>Setting the Stage with YAML</p><p>YAML, a human-readable data serialization format, serves as the foundation for Docker Compose configuration files. With its intuitive structure, YAML allows developers to specify service definitions, volumes, networks, and more, all within a single file. Let’s delve into a YAML configuration snippet illustrating the deployment of a Redis cluster comprising three nodes:</p><pre>version: &#39;3&#39;<br><br>services:<br>  redis-1:<br>    image: &quot;redis:latest&quot;<br>    container_name: redis-1<br>    ports:<br>      - &quot;6390:6380&quot;  # Map external port for Redis commands<br>      - &quot;16380:16380&quot;  # Map external port for Redis cluster bus<br>    volumes:<br>      - ./redis.conf:/etc/redis/redis.conf<br>    command: redis-server /etc/redis/redis.conf --maxmemory 1gb --maxmemory-policy allkeys-lru --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes --appendfilename appendonly-1.aof --cluster-announce-ip &lt;replace_with_your_server_external_ip&gt; --cluster-announce-port 6390 --cluster-announce-bus-port 16380<br><br>  redis-2:<br>    image: &quot;redis:latest&quot;<br>    container_name: redis-2<br>    ports:<br>      - &quot;6380:6380&quot;  # Map external port for Redis commands<br>      - &quot;16381:16380&quot;  # Map external port for Redis cluster bus<br>    volumes:<br>      - ./redis.conf:/etc/redis/redis.conf<br>    command: redis-server /etc/redis/redis.conf --maxmemory 1gb --maxmemory-policy allkeys-lru --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes --appendfilename appendonly-2.aof --cluster-announce-ip &lt;replace_with_your_server_external_ip&gt; --cluster-announce-port 6380 --cluster-announce-bus-port 16381<br><br>  redis-3:<br>    image: &quot;redis:latest&quot;<br>    container_name: redis-3<br>    ports:<br>      - &quot;6381:6380&quot;  # Map external port for Redis commands<br>      - &quot;16382:16380&quot;  # Map external port for Redis cluster bus<br>    volumes:<br>      - ./redis.conf:/etc/redis/redis.conf<br>    command: redis-server /etc/redis/redis.conf --maxmemory 1gb --maxmemory-policy allkeys-lru --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes --appendfilename appendonly-3.aof --cluster-announce-ip &lt;replace_with_your_server_external_ip&gt; --cluster-announce-port 6381 --cluster-announce-bus-port 16382<br><br>  redisinsight:<br>    image: &quot;redis/redisinsight:latest&quot;<br>    container_name: redisinsight<br>    ports:<br>      - &quot;5540:5540&quot;<br>    volumes:<br>      - redisinsight-data:/db<br><br>volumes:<br>  redisinsight-data:<br><br>networks:<br>  default:<br>    driver: bridge</pre><p>In the above snippet, we define four services: redis-1, redis-2, redis-3, and redisinsight. Each redis service represents a Redis instance within the cluster, configured with specific ports, volumes, and command options. Additionally, the redisinsight service deploys RedisInsight, a graphical user interface for managing Redis data, facilitating monitoring and administration tasks.</p><p>To initialize the Redis cluster, run the following command:</p><pre>docker exec -it redis-1 redis-cli --cluster create \<br>  $(docker inspect -f &#39;{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39; redis-1):6380 \<br>  $(docker inspect -f &#39;{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39; redis-2):6380 \<br>  $(docker inspect -f &#39;{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39; redis-3):6380 \<br>  --cluster-replicas 0</pre><p>This command orchestrates the creation of the Redis cluster, utilizing the IP addresses of the Redis instances (redis-1, redis-2, and redis-3) along with their respective ports. The --cluster-replicas 0 flag specifies that there will be no replica nodes in the cluster.</p><p><strong>Understanding Service Definitions</strong></p><p>The redis services utilize the official Redis Docker image, ensuring consistency and reliability. By specifying container names, ports, volumes, and command options, we tailor each Redis instance to meet cluster requirements. Notably, the command directive enables us to pass runtime arguments to the Redis server, enabling features like clustering, persistence, and memory management.</p><p><strong>Visualizing Data with RedisInsight</strong></p><p>While Redis offers a robust command-line interface, visualizing data and monitoring cluster health can be challenging. Enter RedisInsight, a web-based management tool that simplifies Redis administration. By exposing port 5540 and mounting a volume for persistent storage, the redisinsight service grants developers seamless access to real-time performance metrics, key-value visualization, and cluster management capabilities. You have access to this resource via the following URL: http://&lt;Ip_address&gt;:5540/</p><p><strong>Conclusion</strong></p><p>In conclusion, Docker Compose empowers developers to deploy Redis clusters effortlessly, abstracting away the complexities of manual configuration. By leveraging YAML configuration files, we define service specifications, volumes, and networks, orchestrating containerized applications with ease. With the inclusion of RedisInsight, monitoring and managing Redis clusters becomes a streamlined experience, enhancing developer productivity and facilitating seamless application deployment in modern cloud-native environments.</p><p><strong>If you found this guide helpful, give it a clap!</strong> 👏</p><p>For more insightful content on AWS best practices, cloud security, and technology updates, don’t forget to <strong>**follow me! 🚀**</strong></p><p>And if you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a ☕️ coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f9abebd31b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating EC2 Instance Management: Starting Instances and Allowing IP Access through Postman]]></title>
            <link>https://awstip.com/automating-ec2-instance-management-starting-instances-and-allowing-ip-access-through-postman-60bd9f8a01e7?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bd9f8a01e7</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 07:20:23 GMT</pubDate>
            <atom:updated>2024-03-22T17:59:50.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2J3iP8X98w3xkhhRscJW7Q.png" /></figure><p>To elevate your development skills in Python and AWS, we’ve composed two scripts to perform the functionalities of starting an EC2 instance and allowing a specific IP address to that instance. Using these scripts, you can also integrate with Postman to execute these functionalities straight from your favorite REST client interface.</p><h3>Script 1: Python Code for Starting an EC2 Instance</h3><p>The first script begins by importing the boto3 and json modules. Using a Python function that serves as an AWS Lambda handler (lambda_handler), it leverages the boto3 module to communicate with AWS EC2.</p><p>After defining your instance ID, you can now start an instance. A successful start response will return a status code of 200 along with the message ‘Instance started.’ If the process encounters errors, it will return a status code of 500 and will include the error details in the response.</p><pre># Instnace script<br>import boto3<br>import json<br><br>def lambda_handler(event, context):<br>    ec2_resource = boto3.resource(&#39;ec2&#39;)<br><br>    instance_id = &#39;&lt;your_instance_id&gt;&#39;<br>    instance = ec2_resource.Instance(instance_id)<br><br>    try:<br>        instance.start()<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps(&#39;Instance started&#39;)<br>        }<br>    except Exception as e:<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps(f&#39;Error occurred: {str(e)}&#39;)<br>        }</pre><h3>Script 2: Python Code for Allowing an IP address</h3><p>The second script imports the json, logging, and boto3 modules, and it sets up logging configuration. This script follows a more complex logic to handle IP allowance. First, it extracts the IP address and description by checking if these values are in the HTTP POST request body or the query parameters sent to the API Gateway.</p><p>With the IP permissions in the security group of interest, if the description is aligned with the existing one, the security group ingress with the same description is revoked, and the incoming IP range is authorized. If the IP and description do not match any existing records, a new permission is created for the IP address.</p><p>In both cases, a successful execution will return a 200 status with a success message.</p><pre>import json<br>import logging<br>import boto3<br><br># Initialize logger<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>def lambda_handler(event, context):<br>    # Extract the ip_address and description from the event payload or query parameters<br>    try:<br>        if &#39;body&#39; in event:<br>            payload = json.loads(event[&#39;body&#39;])<br>            ip_address = payload[&#39;ip_address&#39;]<br>            description = payload.get(&#39;description&#39;, &#39;&#39;)<br>        elif &#39;queryStringParameters&#39; in event:<br>            ip_address = event[&#39;queryStringParameters&#39;][&#39;ip_address&#39;]<br>            description = event[&#39;queryStringParameters&#39;].get(&#39;description&#39;, &#39;&#39;)<br>        else:<br>            return {<br>                &#39;isBase64Encoded&#39;: False,<br>                &#39;statusCode&#39;: 400,<br>                &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                &#39;body&#39;: json.dumps({&#39;error&#39;: &#39;Missing ip_address in request&#39;})<br>            }<br><br>        # Log the IP address and description<br>        logger.info(f&#39;IP address: {ip_address}&#39;)<br>        logger.info(f&#39;Description: {description if description else &quot;None provided&quot;}&#39;)<br><br>        ec2 = boto3.client(&#39;ec2&#39;)<br>        security_group_id = &#39;&lt;your_security_group_id&gt;&#39;<br><br>        response = ec2.describe_security_groups(GroupIds=[security_group_id])<br>        existing_permissions = response[&#39;SecurityGroups&#39;][0][&#39;IpPermissions&#39;]<br>        for permission in existing_permissions:<br>            for range in permission[&#39;IpRanges&#39;]:<br>                if (&#39;Description&#39; in range) and (range[&#39;Description&#39;] == description):<br>                    try:<br>                        remove_permission = [{<br>                            &#39;IpProtocol&#39;: permission[&#39;IpProtocol&#39;],<br>                            &#39;FromPort&#39;: permission[&#39;FromPort&#39;],<br>                            &#39;ToPort&#39;: permission[&#39;ToPort&#39;],<br>                            &#39;IpRanges&#39;: [{&#39;CidrIp&#39;: range[&#39;CidrIp&#39;], &#39;Description&#39;: description}]<br>                        }]<br>                        ec2.revoke_security_group_ingress(GroupId=security_group_id, IpPermissions=remove_permission)<br>                    except Exception as e:<br>                        logger.error(f&quot;Error occurred while revoking security group ingress: {str(e)}&quot;)<br>                        return {<br>                            &#39;isBase64Encoded&#39;: False,<br>                            &#39;statusCode&#39;: 500,<br>                            &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>                        }<br>                    try:<br>                        add_permission = [{<br>                            &#39;IpProtocol&#39;: permission[&#39;IpProtocol&#39;],<br>                            &#39;FromPort&#39;: permission[&#39;FromPort&#39;],<br>                            &#39;ToPort&#39;: permission[&#39;ToPort&#39;],<br>                            &#39;IpRanges&#39;: [{&#39;CidrIp&#39;: f&quot;{ip_address}/32&quot;, &#39;Description&#39;: description}]<br>                        }]<br>                        ec2.authorize_security_group_ingress(GroupId=security_group_id, IpPermissions=add_permission)<br>                    except Exception as e:<br>                        logger.error(f&quot;Error occurred while authorizing security group ingress: {str(e)}&quot;)<br>                        return {<br>                            &#39;isBase64Encoded&#39;: False,<br>                            &#39;statusCode&#39;: 500,<br>                            &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>                        }<br>                    return {<br>                        &#39;isBase64Encoded&#39;: False,<br>                        &#39;statusCode&#39;: 200,<br>                        &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                        &#39;body&#39;: json.dumps({&#39;message&#39;: f&#39;IP address {ip_address} allowed in existing record with description: {description}&#39;})<br>                    }<br>    except Exception as e:<br>        logger.error(f&quot;Error occurred: {str(e)}&quot;)<br>        return {<br>            &#39;isBase64Encoded&#39;: False,<br>            &#39;statusCode&#39;: 500,<br>            &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>        }<br>    new_permission = {<br>        &#39;IpProtocol&#39;: &#39;tcp&#39;,<br>        &#39;FromPort&#39;: 80,<br>        &#39;ToPort&#39;: 80,<br>        &#39;IpRanges&#39;: [{<br>            &#39;CidrIp&#39;: f&#39;{ip_address}/32&#39;,<br>            &#39;Description&#39;: description<br>        }],<br>    }<br>    try:<br>        response = ec2.authorize_security_group_ingress(<br>            GroupId=security_group_id,<br>            IpPermissions=[new_permission]<br>        )<br>    except Exception as e:<br>        logger.error(f&quot;Error occurred while authorizing security group ingress: {str(e)}&quot;)<br>        return {<br>            &#39;isBase64Encoded&#39;: False,<br>            &#39;statusCode&#39;: 500,<br>            &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>        }<br>    return {<br>        &#39;isBase64Encoded&#39;: False,<br>        &#39;statusCode&#39;: 200,<br>        &#39;headers&#39;: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        &#39;body&#39;: json.dumps({&#39;message&#39;: f&#39;IP address {ip_address} allowed in new record with description: {description}&#39;})<br>    }</pre><h3>How to Use an API Gateway with Python</h3><p>By taking advantage of Amazon’s API Gateway, you can expose these functionalities and connect them to your app, website, or even third-party integrations.</p><p>After deploying your code to AWS Lambda, you can set up an API Gateway that uses a POST method, where scripts 1 and 2 are associated with their respective routes: instance_start and instance_ipallow.</p><p>With the established routes in your API, you can make a POST call to either https://[api-gateway-url]/instance_start or <a href="https://[api-gateway-url]/instance_ipallow?ip_address=1.1.11.14&amp;description=lahiru_ip">https://[api-gateway-url]/instance_ipallow?ip_address=&lt;YOUR_IP_ADDRESS&gt;&amp;description=&lt;</a>DESCRIPTION_OF_IP&gt; with the necessary parameters in the request body or the query parameters.</p><p>Finally, in Postman, enter the specific URL for starting the instance or allowing IP access.</p><p>Remember to replace the placeholders in the code with your specific entries, and you’re ready to see your Python scripts in action. With these capabilities, your EC2 instances can become more interactive and programmatically manageable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pe7sTnmFy_BRs6XDqC_Gwg.png" /></figure><p>You can download the script from the following GitHub repository: <a href="https://github.com/lakmal-ya/sample_python_script.git">[click_here]</a></p><p><strong>Happy automating!</strong></p><p><strong>If you found this guide helpful, give it a clap!</strong> 👏</p><p>For more insightful content on AWS best practices, cloud security, and technology updates, don’t forget to <strong>**follow me! 🚀**</strong></p><p>And if you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a ☕️ coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bd9f8a01e7" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/automating-ec2-instance-management-starting-instances-and-allowing-ip-access-through-postman-60bd9f8a01e7">Automating EC2 Instance Management: Starting Instances and Allowing IP Access through Postman</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Website Deployment to AWS EC2 Using GitHub Actions]]></title>
            <link>https://medium.com/@dulanjanalakmal/automating-website-deployment-to-aws-ec2-using-github-actions-76997c52747a?source=rss-54cbcac0d4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/76997c52747a</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Dulanjana Lakmal]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 04:05:24 GMT</pubDate>
            <atom:updated>2024-02-27T20:15:59.268Z</atom:updated>
            <content:encoded><![CDATA[<p>GitHub Actions is a powerful automation tool that allows you to build, test, and deploy your projects directly from your GitHub repository. In this article, we’ll explore how to set up a GitHub Actions workflow to automate the deployment of a website to an AWS EC2 instance.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have the following:</p><ol><li>A GitHub repository containing your web application code.</li><li>An AWS EC2 instance with the necessary configurations.</li></ol><p>Absolutely, let me adjust the article accordingly:</p><h3>Automating Website Deployment to AWS EC2 Using GitHub Actions</h3><p>GitHub Actions is a powerful automation tool that allows you to build, test, and deploy your projects directly from your GitHub repository. In this article, we’ll explore how to set up a GitHub Actions workflow to automate the deployment of a website to an AWS EC2 instance.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have the following:</p><ol><li>A GitHub repository containing your web application code.</li><li>An AWS EC2 instance with the necessary configurations.</li></ol><h3>GitHub Actions Workflow</h3><h3>1. Trigger on Push</h3><pre>on:<br>  push:<br>    branches:<br>      - main</pre><p>This workflow is triggered on every push to the main branch.</p><h3>2. Set Up Deployment Environment</h3><pre>jobs:<br>  build:<br>    name: 🎉 Deploy<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: 🚚 Get latest code<br>        uses: actions/checkout@v2<br><br>      - name: 📂 Set working directory<br>        run: cd &lt;your_code_directory&gt;</pre><p>The workflow starts by checking out the latest code and setting the working directory to your project folder.</p><h3>3. Install Dependencies and Build</h3><pre>      - name: 🛠 Install dependencies<br>        run: npm install<br>        working-directory: &lt;your_code_directory&gt;<br><br>      - name: 🛠 Install Vite globally<br>        run: npm install -g vite<br>        working-directory: &lt;your_code_directory&gt;<br><br>      - name: 🛠 Build<br>        run: npm run build<br>        working-directory: &lt;your_code_directory&gt;</pre><p>nstall project dependencies, globally install Vite, and build the project using npm.</p><h3>4. Deploy to AWS EC2</h3><pre>      - name: 📂 rsync deployments<br>        uses: burnett01/rsync-deployments@5.1<br>        with:<br>          switches: -avzr --delete<br>          path: ./*<br>          remote_path: /var/www/html/&lt;your_project_directory&gt;/<br>          remote_host: &lt;your_ec2_ip_address&gt;<br>          remote_user: ec2-user<br>          remote_key: &quot;${{ secrets.SSH_PRIVATE_KEY }}&quot;</pre><p>The workflow uses rsync to deploy the built files to the AWS EC2 instance.</p><h3>5. Set Ownership and Permissions on Remote Server</h3><pre>      - name: 📂 Set ownership on remote server<br>        run: |<br>          echo &quot;${{ secrets.SSH_PRIVATE_KEY }}&quot; &gt; private_key.pem<br>          chmod 600 private_key.pem<br><br>          # Create known_hosts file if it doesn&#39;t exist<br>          mkdir -p /home/runner/.ssh<br>          touch /home/runner/.ssh/known_hosts<br>          <br>          # Clear old key from known_hosts<br>          ssh-keygen -R &lt;your_ec2_ip_address&gt; &gt;&gt; /home/runner/.ssh/known_hosts<br><br>          # Run the SSH command<br>          ssh -i private_key.pem -o StrictHostKeyChecking=no ec2-user@&lt;your_ec2_ip_address&gt; \<br>          &quot;sudo chown -R ec2-user:apache /var/www/html/&lt;your_project_directory&gt;/ &amp;&amp; chmod 777 -R /var/www/html/&lt;your_project_directory&gt;/&lt;your_code_directory&gt;/storage &amp;&amp; chmod -R 777 /var/www/html/&lt;your_project_directory&gt;/&lt;your_code_directory&gt;/bootstrap/cache/ &amp;&amp; cd /var/www/html/&lt;your_project_directory&gt;/&lt;your_code_directory&gt;/ &amp;&amp; sudo npm install -g vite  &amp;&amp; npm install &amp;&amp; sudo chown -R ec2-user:apache /var/www/html/&lt;your_project_directory&gt;/ &amp;&amp; chmod +x /var/www/html/&lt;your_project_directory&gt;/&lt;your_code_directory&gt;/dev_run.sh&quot;          <br>        env:<br>          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}</pre><p>This step sets ownership and permissions on the remote server, ensuring proper access to directories and files.</p><h3>6. Run Deployment Script on Remote Server</h3><pre>      - name: 🎉 Deploy to Remote Server<br>        uses: appleboy/ssh-action@master<br>        with:<br>          host: &lt;your_ec2_ip_address&gt;<br>          username: ec2-user<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          script: |<br>            cd /var/www/html/&lt;your_project_directory&gt;/&lt;your_code_directory&gt;<br>            ./dev_run.sh</pre><p>The final step runs a deployment script (dev_run.sh) on the AWS EC2 instance, initiating any additional tasks required for your application.</p><h3>7. Dev Run Script (dev_run.sh)</h3><p>Create a dev_run.sh file in your project directory with the following content:</p><pre>#!/bin/bash<br>npm run dev &amp;</pre><p>This script runs npm run dev in the background.</p><h3>Conclusion</h3><p>By setting up this GitHub Actions workflow, you’ve automated the deployment process of your web application to an AWS EC2 instance. Any push to the main branch will trigger this workflow, ensuring your application is always up to date.</p><p><strong>Happy automating!</strong></p><p><strong>If you found this guide helpful, give it a clap!</strong> 👏</p><p>For more insightful content on AWS best practices, cloud security, and technology updates, don’t forget to <strong>**follow me! 🚀**</strong></p><p>And if you enjoyed this information and feel like supporting my virtual endeavours, consider buying me a ☕️ coffee! Your support keeps the bytes flowing. Cheers! ☕️😊 <a href="https://www.buymeacoffee.com/lakmalya">Buy Me a Coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76997c52747a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>