<?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 Rob Satnarain on Medium]]></title>
        <description><![CDATA[Stories by Rob Satnarain on Medium]]></description>
        <link>https://medium.com/@pails-topper.3j?source=rss-132100fc896b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K2mwbmCZRl-qXMqC_7-aFg@2x.jpeg</url>
            <title>Stories by Rob Satnarain on Medium</title>
            <link>https://medium.com/@pails-topper.3j?source=rss-132100fc896b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:37:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pails-topper.3j/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[Simulating the 9 AM ‘Thundering Herd’: Building an AWS SRE Load Test Lab with Terraform…]]></title>
            <link>https://medium.com/@pails-topper.3j/simulating-the-9-am-thundering-herd-building-an-aws-sre-load-test-lab-with-terraform-074db3e39a0b?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/074db3e39a0b</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Tue, 05 May 2026 22:25:13 GMT</pubDate>
            <atom:updated>2026-05-06T07:37:15.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simulating the 9 AM ‘Thundering Herd’: Building an AWS SRE Load Test Lab with Terraform, Prometheus, and k6</h3><p>“Your app has 1 million users. Every morning at exactly 9:00 AM, the server crashes. Nothing obvious is wrong. The CPU dashboards are green. What do you check first?”</p><p>This is a classic Site Reliability Engineering (SRE) interview question. It’s designed to test a fundamental truth of distributed systems: monitoring tools can lie, and averages mask deadly spikes. If your dashboards are scraping metrics every 5 minutes, a 15-second microburst of 15,000 concurrent user logins at 9:00 AM will be mathematically flattened out. The dashboard looks green, but the application is dead.</p><p>To truly understand how this invisible crash happens — and how to catch it — I decided to build it.</p><p>In this post, I will walk you through how I provisioned an intentionally vulnerable AWS infrastructure using Terraform, securely wired it to a local observability stack (Prometheus and Grafana) on my MacBook, and used k6 to unleash a simulated &quot;thundering herd&quot; to crash the network stack.</p><h3>Phase 1: Infrastructure as Code (The Trap)</h3><p>The goal was to transition away from ClickOps and deploy a repeatable, secure environment. The architecture consists of a single “Victim” EC2 instance (a t3.micro designed to fall over easily) running an Apache web server and a Prometheus Node Exporter.</p><h4>Security First: Network Isolation</h4><p>Even in a lab environment, leaving telemetry ports open to the world is a bad habit. I designed the Terraform aws_security_group to restrict SSH and Prometheus scraping exclusively to my local home IP address, while leaving port 80 open for the simulated public load test.</p><pre>resource &quot;aws_security_group&quot; &quot;victim_sg&quot; {<br>  name        = &quot;victim-server-sg&quot;<br>  description = &quot;Allow HTTP for Load Test, restricted Prometheus scraping&quot;<br><br>  ingress {<br>    description = &quot;Allow HTTP for Load Test&quot;<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    description = &quot;Allow SSH for Admin&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;hidden/32&quot;] # Locked to home network<br>  }<br><br>  ingress {<br>    description     = &quot;Prometheus Node Exporter (Isolated)&quot;<br>    from_port       = 9100<br>    to_port         = 9100<br>    protocol        = &quot;tcp&quot;<br>    cidr_blocks     = [&quot;hidden/32&quot;] # Locked to local Mac scraper<br>  }<br>}</pre><h4>The S3 Backend “Chicken and Egg”</h4><p>To maintain best practices, I used an S3 bucket with native locking (use_lockfile = true introduced in Terraform 1.7.0) to manage my .tfstate.</p><p>Setting this up requires a classic bootstrap maneuver. Because Terraform cannot store its memory in a bucket that doesn’t exist yet, I had to temporarily comment out my backend “s3” block, run terraform apply locally to create the bucket, and then run terraform init -migrate-state to push the local state file up to the cloud.</p><p>With the infrastructure deployed, the Victim server was successfully broadcasting its internal metrics on port 9100. Now, I needed something to catch them.</p><h3>Phase 2: Local Observability (The Watchtower)</h3><p>Rather than paying for a second EC2 instance to run my observability tools, I opted for a hybrid approach: hosting Prometheus and Grafana locally on my MacBook using Homebrew, and reaching into the AWS cloud to pull the metrics.</p><h4>1. Installing the Stack</h4><p>Using Homebrew, setting up the foundation takes seconds:</p><pre>brew install prometheus<br>brew install grafana<br><br># Start them as background services<br>brew services start prometheus<br>brew services start grafana</pre><h4>2. Bridging the Gap (Prometheus Configuration)</h4><p>Prometheus is blind until you tell it where to look. I opened the local config file (/opt/homebrew/etc/prometheus.yml on Apple Silicon) and appended my AWS EC2&#39;s public IP to the scrape_configs block.</p><p><em>Pro-tip: Set the </em><em>scrape_interval to something aggressive like </em><em>5s. We need high-resolution metrics to catch the micro-burst of our load test.</em></p><pre>scrape_configs:<br>  - job_name: &quot;aws-victim-server&quot;<br>    scrape_interval: 5s<br>    static_configs:<br>      - targets: [&quot;EC2_PUBLIC_IP:9100&quot;]</pre><p>After a quick brew services restart prometheus, a check of http://localhost:9090 confirmed the target was &quot;UP&quot;.</p><h4>3. Visualizing with Grafana</h4><p>Raw time-series data is hard to read during an active outage. I navigated to my local Grafana instance (http://localhost:9090), connected my local Prometheus as a Data Source, and imported the industry-standard <strong>Node Exporter Full</strong> dashboard (ID: 1860).</p><p>Instantly, the dashboard lit up with a massive array of gauges and graphs tracking the EC2 instance’s memory, disk space, and CPU.</p><p><em>[Image Placeholder: A screenshot of the “Node Exporter Full” Grafana dashboard showing a completely quiet, green, and healthy server state before the test begins.]</em></p><p>The trap was set. It was time to break it.</p><h3>Phase 3: Unleashing the Thundering Herd</h3><p>To simulate the “9 AM Crash”, I used <strong>k6</strong> by Grafana Labs. It is a wildly efficient load-testing tool written in Go that uses JavaScript for scripting.</p><p>Serving a static “Welcome to the Load Test” index.html requires almost zero CPU. If I sent 500 users to this server, the CPU wouldn&#39;t budge. To actually crash this instance, I needed to exhaust the Linux kernel&#39;s network stack. I wrote a script to aggressively ramp up to 15,000 concurrent virtual users.</p><p>load_test.js:</p><pre>import http from &#39;k6/http&#39;;<br><br>export const options = {<br>  stages: [<br>    { duration: &#39;15s&#39;, target: 2000 },  // Fast ramp-up<br>    { duration: &#39;1m&#39;, target: 15000 },  // Massive spike to simulate the 9 AM Herd<br>    { duration: &#39;15s&#39;, target: 0 },     // Wind down<br>  ],<br>};<br><br>export default function () {<br>  http.get(&#39;http://EC2_PUBLIC_IP&#39;); <br>}</pre><p>With my Grafana dashboard open on a secondary monitor, I executed the script in my terminal:</p><p>k6 run load_test.js</p><h3>Phase 4: Anatomy of a Crash</h3><p>Within 10 seconds, the dashboard exploded. The server didn’t just slow down; it completely suffocated. But the failure wasn’t where you might expect it to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0Yopsah4y5niDU_lH-WQA.png" /><figcaption>Normal before the crash</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Pqb3VAW37_UcDPCWkqaIfA.png" /><figcaption>CPU and Network Traffic (Basic) during the crash</figcaption></figure><p>Here is what the observability stack revealed about the crash:</p><h4>1. Network Sockets (The TIME_WAIT Trap)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqvxBi0wUycdOgAdyOMZGw.png" /></figure><p>When simulating a massive traffic spike, the most revealing panel isn’t always the CPU — it’s the <strong>Network Sockstat</strong> panel. Looking closely at the telemetry during the 15,000-user spike, a pattern emerges.</p><p>Notice that the <strong>In-Use Sockets</strong> line remains completely flat. Because the server is serving a tiny, static HTML file, it processes the request and closes the connection in milliseconds. The connections never linger long enough to be recorded as actively “in use.”</p><p>However, look at the <strong>Allocated Sockets</strong> and the sudden, aggressive spike in <strong>TIME_WAIT Sockets</strong> at the end of the burst.</p><p>When a Linux server closes a TCP connection, the port it used is not immediately released. The kernel places it into a TIME_WAIT state (usually for 60 seconds) to catch any lingering, delayed packets on the network. Because my k6 script forced the server to rapidly open and close thousands of connections in seconds, a massive queue of ports became locked in TIME_WAIT.</p><p>This is exactly how the “9 AM Crash” occurs in the real world. The server doesn’t necessarily run out of CPU or memory; it physically runs out of available ephemeral network ports. The OS is forced to reject all new incoming traffic until the TIME_WAIT queue clears, rendering the application completely unresponsive to users while the CPU dashboards deceptively show low utilization.</p><h4>2. The Deceptive CPU (When 10% looks like a crash)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*zx8CEEYN1zQFlIFI5bw_Ww.png" /></figure><p>Usually, when a server crashes, junior engineers immediately look for a CPU spike. If you look at the <strong>CPU</strong> panel during this massive 15,000-user traffic surge, you might think the monitoring tool is broken.</p><p>During the exact moment the server stopped responding to requests, the total CPU utilization barely crossed 10%. Looking at the breakdown:</p><ul><li>The <strong>User</strong> metric (the blue line, representing our Apache web server) peaked at a mere 4.97%.</li><li>The <strong>System</strong> metric (the green line, representing the OS kernel) only reached 4.18%.</li><li>The <strong>Irq</strong> (interrupts) remained completely flat at 0%.</li></ul><p>This is the ultimate SRE lesson in distributed systems: <strong>A server does not need to hit 100% CPU to be completely dead. </strong>Because Apache was serving a tiny, static HTML file, the computational cost was near zero. The EC2 instance had plenty of compute power left to give. However, because the network stack (as seen in the Sockstat panel) was completely paralyzed by port exhaustion and TIME_WAIT locks, traffic couldn&#39;t actually reach the CPU to be processed. The processor was sitting idle in an empty room while thousands of users were locked outside a jammed front door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qso2v8axih1YVZARRByVBQ.png" /></figure><h4>3. The Missing Queue (Why Load Average Didn’t Spike)</h4><p>In a traditional compute-bound crash, you expect to see the system’s Load Average skyrocket. Load average represents the number of processes actively waiting for CPU time. If an application is struggling to process complex database queries, processes stack up, and the load average shoots past the number of available CPU cores.</p><p>I fully expected the load average on this tiny 2-vCPU t3.micro to hit 10.0 or higher during the 15,000-user spike. Instead, I checked the <strong>System Load</strong> graph and found something: <strong>the 1-minute load average peaked at a mere 1.16. </strong>On a 2-vCPU instance, a load of 2.0 is 100% capacity. A peak of 1.16 means the server was operating at roughly 58% compute capacity during the height of the crash.</p><p><strong>Why was the load so low while the server was dead?</strong> This confirms the findings from the Sockstat panel. Because the Linux kernel exhausted its available network ports (TIME_WAIT lockup), it actively rejected the incoming connections at the OS level. The kernel essentially slammed the front door shut.</p><p>Because those requests were rejected immediately, the Apache web server never had a chance to spawn worker processes to handle them. No worker processes meant no queue. No queue meant no spike in the load average.</p><p>To the CPU, the 9 AM thundering herd didn’t look like a massive wave of users; it just looked like a quiet morning where the network card suddenly stopped letting people in.</p><h3>That is a great addition. In SRE, “I think” is a dangerous phrase; “I can prove” is the goal. Including the local verification step transforms the takeaway from a theoretical explanation into a practical troubleshooting guide.</h3><p>Here is the final, comprehensive <strong>SRE Takeaway</strong> for your Medium blog.</p><h3>The SRE Takeaway: The Danger of “Green” Dashboards</h3><p>The most dangerous outages are the ones where the dashboards look healthy. By building this infrastructure and actively breaking it, we proved a terrifying SRE reality: a server can be completely dead to the outside world while its CPU idles at 5% and its load average hums along at half capacity.</p><h4>The Ephemeral Port Math</h4><p>I discovered that even with a 1-second sleep pacing, 15,000 concurrent users were attempting to use 900,000 unique ports over a one-minute window. Since a Linux kernel only has about 28,000 ephemeral ports available, the system hit a hard mathematical wall. Even though the CPU was green, the network stack was paralyzed by the TIME_WAIT trap.</p><h4>How to Prove It: Look at Both Sides</h4><p>If you noticed that your Grafana dashboard only showed 2,000 TIME_WAIT sockets while sending 15,000 requests, you’ve hit the ultimate SRE lesson: <strong>Sampling Bias.</strong> Because Prometheus scrapes every 5–15 seconds, it often misses the true peak of a microburst. Furthermore, a crash is often client-side. To move from an educated guess to a concrete proof, you must check the source of the traffic. By running nestat -an|grep TIME_WAIT | wc -l on my local machine during the test, you can see if the ports are exhausted at the source. If the client can&#39;t open a port, the request never reaches the server, and the server-side dashboard stays deceptively calm.</p><p>An even better way to check is to run: watch -n 1 “netstat -an | grep TIME_WAIT | wc -l”. You can watch the actual number increase solidifying the cause as the ephemeral ports. The result climbed to well over 16,000.</p><h4>Engineering the Solution</h4><p>If an engineer only checks standard compute metrics during a “9 AM Crash,” the outage looks like a ghost. Even worse, if their gut reaction is to “vertically scale” by buying a bigger instance, the application will <strong>still crash</strong> the next morning. The bottleneck was never raw compute power; it was the “one-port-per-request” anti-pattern.</p><p>To mitigate a Thundering Herd in production, you don’t just buy bigger servers. You engineer for resilience:</p><ul><li><strong>Connection Pooling (Keep-Alive):</strong> Reusing long-lived TCP connections so that 15,000 users only use 15,000 ports, regardless of how many requests they send.</li><li><strong>Amazon SQS:</strong> Using a queue as a shock absorber to decouple the arrival of traffic from the processing work, ensuring no requests are dropped during spikes.</li><li><strong>Jitter:</strong> Staggering mathematical randomness into client retries and cache expirations to ensure the “army” of users doesn’t hit the door at the exact same millisecond.</li></ul><p>Infrastructure as Code makes provisioning environments easy, and tools like Prometheus and Grafana make them visible. But as my grandfather says, <em>“It is better to try and fail than fail to try.”</em> In Site Reliability Engineering, it is only by intentionally building systems to watch them fail that you learn how to engineer true, scalable reliability.</p><h3>Engineering the Solution</h3><h4>Using Amazon SQS as a Shock Absorber</h4><p>To truly solve the Thundering Herd, we have to decouple the arrival of the traffic from the processing of the work. By introducing <strong>Amazon SQS (Simple Queue Service)</strong>, we transform our architecture from a fragile, synchronous push model to a resilient, asynchronous pull model.</p><p>Instead of the user’s browser hitting our t3.micro directly—which risks TCP port exhaustion—the requests are dropped into an S3 queue. Our EC2 instance then acts as a worker, pulling messages from the queue at a pace it can safely handle.</p><h4>The Strategic Trade-off: Availability vs. Latency</h4><p>Implementing a queue introduces a fundamental trade-off. We are choosing <strong>Availability</strong> (the system is always up) over <strong>Latency</strong> (the system responds instantly).</p><ul><li><strong>Before SQS:</strong> The first 5,000 users get a 50ms response time; the next 10,000 users get a “Connection Refused” error. Total Failure.</li><li><strong>With SQS:</strong> All 15,000 users get a successful result, but during the peak, their wait time might stretch from 50ms to 60 seconds.</li></ul><h3>How to Discuss This with Executives</h3><p>When explaining this architecture to a CTO or a Product Manager, you shouldn’t focus on ephemeral ports. You should focus on <strong>Risk Mitigation</strong> and <strong>Customer Retention.</strong></p><p>Here is the framework for that conversation:</p><h4>1. Frame it as “Degrading Gracefully”</h4><p><strong>The Pitch:</strong> <em>“Instead of the site crashing and losing 60% of our customers during the morning rush, we are implementing a ‘Virtual Waiting Room.’ The system will stay 100% online, and users will see a loading state rather than a broken page.”</em></p><ul><li><strong>Executive Value:</strong> It protects the brand reputation. A “slow” site is a frustration; a “broken” site is a lost customer.</li></ul><h4>2. The Cost-Efficiency Argument</h4><p><strong>The Pitch:</strong> <em>“If we try to solve this by just buying bigger servers (Vertical Scaling), we will be paying for massive, idle compute power 23 hours a day just to survive a 5-minute spike. By using SQS, we can keep our infrastructure small and cost-effective, allowing the queue to level the load over time.”</em></p><ul><li><strong>Executive Value:</strong> It optimizes the AWS bill. You are saving the company money by using architectural intelligence instead of a brute force credit card.</li></ul><h4>3. Define the “Service Level Agreement” (SLA)</h4><p><strong>The Pitch:</strong> <em>“We are moving from a ‘Low Latency’ SLA to an ‘Eventual Consistency’ SLA during peak hours. This ensures that every transaction is captured and processed, even if the user has to wait a few extra moments for confirmation.”</em></p><ul><li><strong>Executive Value:</strong> It provides predictability. Executives love knowing that the system has a “ceiling” for failure and a plan for recovery.</li></ul><h4>4. The “Safety Net” for the Database</h4><p><strong>The Pitch:</strong> <em>“The queue doesn’t just protect the web server; it protects our most expensive asset — the database. It prevents the database from being ‘DoSed’ by our own users, ensuring that back-office operations and other critical services don’t get dragged down by the traffic spike.”</em></p><ul><li><strong>Executive Value:</strong> It protects the organization’s data.</li></ul><p>By presenting the SQS solution this way, you show that you aren’t just an engineer who knows how to write Terraform — you are a <strong>Site Reliability Engineer</strong> who understands how technology serves the business.</p><p>I know what some of you may be thinking. Why is isn’t high availability discussed? The best way to implement this is to have a highly available cloud architecture along with being resilient in handling the herd. High Availability is for <strong>Reliability</strong> (staying up during hardware failure). SQS is for <strong>Resiliency</strong> (staying up during traffic extremes). You don’t choose between the two, use both. You use multiple AZs to ensure that if one data center is down, the site stays up. Use Load Balancers to drop the traffic into SQS.</p><p>When an executive asks, <em>“Why can’t we just add more servers?”</em>, your SRE response is:</p><p><em>“Scaling our servers (HA) increases our </em><strong><em>throughput</em></strong><em>, but it doesn’t protect us from </em><strong><em>volatility</em></strong><em>. If we just add more servers, we are still vulnerable to a spike that is larger than our capacity. By adding SQS, we create a </em><strong><em>circuit breaker</em></strong><em>. It ensures that no matter how big the spike is, our database stays safe and our costs stay predictable. We aren’t just building a bigger engine. We’re adding a shock absorber.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=074db3e39a0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Portfolio Project Structure for AWS Deployment]]></title>
            <link>https://medium.com/@pails-topper.3j/next-js-portfolio-project-structure-for-aws-deployment-ca503118de92?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca503118de92</guid>
            <category><![CDATA[static-site]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 17:35:16 GMT</pubDate>
            <atom:updated>2026-04-28T17:35:16.126Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>This project is a Next.js portfolio site prepared for static deployment on AWS with Terraform. The app is organized around file-based routing, reusable components, and static assets, with next.config.js configured to export a static build for hosting in AWS.</p><p><strong>Project Structure Overview</strong> <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=15">0:15</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UnP4XReYciqDbnu5" /></figure><ul><li>The app is built around a standard Next.js structure.</li><li>The key folders are:</li><li>pages/ for routes</li><li>components/ for reusable UI pieces</li><li>public/ for static assets</li><li>A next.config.js file is used to configure the build for static export.</li></ul><p><strong>File-Based Routing in </strong>pages/ <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=36">0:36</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8NlrX28gTSxKJ-Do" /></figure><ul><li>pages/ is the most important folder in the app.</li><li>Next.js uses file-based routing, so each file in this directory becomes a route on the site.</li><li>pages/index.js serves as the homepage.</li><li>Adding pages/about.js would automatically create an /about route.</li><li>This keeps navigation simple and easy to maintain.</li></ul><p><strong>Reusable UI in </strong>components/ <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=78">1:18</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2VDlPuIVlPuAKJNx" /></figure><ul><li>components/ contains reusable building blocks for the interface.</li><li>Shared pieces such as a navigation bar, contact form, or custom button can live here.</li><li>These components can be imported into any page that needs them.</li><li>This helps keep the codebase clean and the design consistent across the portfolio.</li></ul><p><strong>Static Assets in </strong>public/ <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=113">1:53</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KyiIG2zqbc9P6eh9" /></figure><ul><li>public/ stores static files used by the site.</li><li>Typical assets include:</li><li>images</li><li>logos</li><li>custom fonts</li><li>icons</li><li>Next.js serves these files efficiently, which supports fast page loads.</li></ul><p><strong>Static Export Configuration in </strong>next.config.js <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=137">2:17</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9lYhde3M1GWdarO4" /></figure><ul><li>next.config.js is configured with output: &#39;export&#39; for AWS deployment.</li><li>This tells Next.js to compile the app into static HTML, CSS, and JavaScript.</li><li>Running the build generates an out/ directory containing the exported site.</li><li>Static output is cheaper and more secure to host, and it fits the goal of a highly available, cost-effective AWS deployment.</li></ul><p><strong>Next Step: AWS Infrastructure with Terraform</strong> <a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4?t=184">3:04</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E3E4h7S81kvq02Lt" /></figure><ul><li>The codebase is now clean, version-controlled, and ready for cloud infrastructure.</li><li>The next phase is writing Terraform to provision AWS resources.</li><li>The first major infrastructure piece will be a global CDN to serve the exported site worldwide.</li></ul><h3>Link to Loom</h3><p><a href="https://loom.com/share/25a8a8f0762542e78ede319665c256e4">https://loom.com/share/25a8a8f0762542e78ede319665c256e4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca503118de92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Self-Healing Cloud: Automated SRE Remediation in AWS]]></title>
            <link>https://medium.com/@pails-topper.3j/building-a-self-healing-cloud-automated-sre-remediation-in-aws-b3e64c7487fb?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e64c7487fb</guid>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cloudtrail]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 19:58:43 GMT</pubDate>
            <atom:updated>2026-04-24T19:58:43.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E5FWxFhkKXxuuWMq0L6QA.png" /></figure><p>I can see myself, and probably many cloud engineers, spend weeks perfectly crafting an Infrastructure as Code pipeline, securing the network, and locking down subnets. Then, at 2 AM on a Friday, someone urgently needs access to a private server, logs directly into the AWS Console, and manually opens SSH to the entire internet.</p><p>In a traditional operations team, this triggers an alert, wakes someone up, and starts a frantic Slack thread or email chain. But in Site Reliability Engineering, treat operations as a software problem.</p><p>This week, I decided to build a self-healing infrastructure. The goal was simple: if anyone manually modifies a Security Group to open Port 22 to the public internet, the system should instantly detect the violation and silently revert it.</p><p>Here is how I built an automated remediation engine using AWS EventBridge, Lambda, and Boto3 — and the real-world bugs I had to squash along the way.</p><h3>The Architecture: How It Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80b2yXiZApYj9ov9mRAF6Q.png" /></figure><p>To achieve a self-healing system, you need a way to detect state changes and a compute layer to execute the fix.</p><p>The flow relies on four core AWS services:</p><ol><li><strong>CloudTrail</strong> acts as the security camera, recording every API call made in the AWS account.</li><li><strong>EventBridge</strong> acts as the routing engine. It listens specifically for the AuthorizeSecurityGroupIngress API call.</li><li><strong>Lambda</strong> contains our Python logic. It inspects the event payload to see exactly what rule was added.</li><li><strong>EC2 API</strong> is called by the Lambda function to revoke the rule if it violates our security baseline.</li></ol><h3>Defining the Infrastructure as Code</h3><p>I deployed the entire environment using CloudFormation. Rather than clicking through the console to create VPCs and subnets, writing it all in YAML ensures the architecture is reproducible.</p><p>The template spins up a fresh VPC, a public subnet with an attached Internet Gateway, and a target Security Group. It also provisions an IAM Role with strict least-privilege permissions, allowing our Lambda function only to read and revoke Security Group rules.</p><h3>Writing the Remediation Logic</h3><p>The brain of the operation is a Python script using the Boto3 SDK. When triggered, the function parses the incoming event details. It loops through the requested IP permissions, looking for a specific combination: an ingress rule on port 22 attached to the 0.0.0.0/0 CIDR block.</p><p>If it finds that exact match, it executes the revoke_security_group_ingress command to instantly rip the rule back out.</p><h3>Hitting the Wall: Real-World Troubleshooting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIB9BUbUfVwhP4QM0zVN0g.png" /></figure><p>Building the theoretical architecture is the easy part. Getting the microservices to communicate flawlessly in reality is where the actual engineering happens. Here are the three hurdles I hit during deployment and how I solved them using standard SRE debugging methodologies.</p><p><strong>1. The Silent Failure (CloudTrail Blindness)</strong></p><p>After deploying the stack, I tested it by manually adding a bad rule to the Security Group. Nothing happened. Checking the Lambda metrics showed zero invocations.</p><p>The fix: EventBridge rules that rely on AWS API calls absolutely require an active CloudTrail trail to be running in the account. By default, EventBridge cannot see management events. Once I configured a proper CloudTrail bucket to capture write events, EventBridge woke up.</p><p><strong>2. The Mismatched Handler</strong></p><p>Once the event triggered, my Lambda function threw an error stating it was unable to import module ‘remediation’.</p><p>When writing inline Python code within a CloudFormation template using the ZipFile property, AWS automatically saves that code as a file named index.py behind the scenes. I had configured my Lambda handler to look for remediation.lambda_handler. Changing the handler configuration to index.lambda_handler instantly fixed the routing.</p><p><strong>3. The Case of the Mismatched Cases</strong></p><p>Finally, the Lambda executed perfectly but failed on the final API call with a parameter validation error. This was the most interesting bug of the project.</p><p>CloudTrail formats its JSON event payloads using camelCase. For example, it sends the port as fromPort. However, the Boto3 Python SDK is notoriously strict and requires parameters to be passed in PascalCase, expecting FromPort.</p><p>If you feed the raw CloudTrail payload directly back into Boto3, it rejects it. I had to write a data translation layer inside the Lambda function to map the camelCase event data into a properly formatted PascalCase dictionary before making the revoke call.</p><h3>The Result</h3><p>With the bugs squashed, the system is now a closed loop. If I go into the AWS EC2 console and open SSH to the world, the rule sits there for about 15 seconds before vanishing completely.</p><p>This project was an incredible deep dive into event-driven architecture. It proves that the console is just an interface for APIs, and with the right automation, you can enforce your desired state securely and instantly.</p><p>Treat your operations like software, and your infrastructure will take care of itself.</p><pre># Name: SRE Automated Remediation<br># Author: Rob Satnarain<br># Description: Designed to close all port 22s that are manually opened in AWS Console. <br># Creation Date: 2026-04-23<br><br># Update Date   Updated By     Version   Description<br># -----------  ------------   -------   ---------------------------------------------<br># 2026-04-23   Rob Satnarain  1.0       Initial creation of the SRE Automated Remediation playbook.<br># 2026-04-24   Rob Satnarain  1.1       Added detailed comments and logging for better traceability. Updated lambda handler to index instead of remediation_handler for consistency with AWS Lambda naming conventions.<br># 2026-04-24.  Rob Satnarain  1.2       Updated python to use Pascal Case for revoke_parameters to match Boto3 expectations. Added error handling in the Lambda function to catch and log any exceptions during the remediation process.<br>#<br><br>AWSTemplateFormatVersion: &quot;2010-09-09&quot;<br>Description: &quot;SRE Automated Remediation Playbook - Closes all port 22 rules are manually created in AWS Console.&quot;<br><br>Resources:<br>    # 1. Base Network (VPC, Subnet, IGW)<br>  RemediationVPC:<br>    Type: AWS::EC2::VPC<br>    Properties:<br>        CidrBlock: &quot;10.0.0.0/16&quot;<br>        EnableDnsHostnames: true<br>        EnableDnsSupport: true<br>        Tags:<br>            - Key: Name<br>              Value: SRE-Automated-Remediation-VPC<br><br>  RemediationSubnet:<br>    Type: AWS::EC2::Subnet<br>    Properties:<br>        VpcId: !Ref RemediationVPC<br>        CidrBlock: &quot;10.0.1.0/24&quot;<br>        Tags:<br>            - Key: Name<br>              Value: SRE-Automated-Remediation-Subnet<br><br>  RemediationIGW:<br>    Type: AWS::EC2::InternetGateway<br>    Properties:<br>        Tags:<br>            - Key: Name<br>              Value: SRE-Automated-Remediation-IGW<br><br>  RemediationVPCGatewayAttachment:<br>    Type: AWS::EC2::VPCGatewayAttachment<br>    Properties:<br>        VpcId: !Ref RemediationVPC<br>        InternetGatewayId: !Ref RemediationIGW<br><br>  PublicRouteTable:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>        VpcId: !Ref RemediationVPC<br>        Tags:<br>            - Key: Name<br>              Value: SRE-Automated-Remediation-Public-Route-Table<br><br>  PublicRoute:<br>    Type: AWS::EC2::Route<br>    DependsOn: RemediationVPCGatewayAttachment<br>    Properties:<br>        RouteTableId: !Ref PublicRouteTable<br>        DestinationCidrBlock: &quot;0.0.0.0/0&quot;<br>        GatewayId: !Ref RemediationIGW<br><br>  SubnetRouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties:<br>        SubnetId: !Ref RemediationSubnet<br>        RouteTableId: !Ref PublicRouteTable<br>  <br>  # 2. Target Security Group (Test Group)<br>  TargetSecurityGroup:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>        GroupDescription: &quot;Target Security Group for SRE Automated Remediation&quot;<br>        VpcId: !Ref RemediationVPC<br>        SecurityGroupIngress:<br>            - IpProtocol: tcp<br>              FromPort: 22<br>              ToPort: 22<br>              CidrIp: &quot;0.0.0.0/0&quot;<br>  <br>  #3. IAM Role for Lambda Function<br>  LambdaExecutionRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>        AssumeRolePolicyDocument:<br>            Version: &quot;2012-10-17&quot;<br>            Statement:<br>                - Effect: Allow<br>                  Principal:<br>                      Service: lambda.amazonaws.com<br>                  Action: sts:AssumeRole<br>        ManagedPolicyArns:<br>            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole<br>        Policies:<br>            - PolicyName: EC2SREAutomatedRemediationPolicy<br>              PolicyDocument:<br>                  Version: &quot;2012-10-17&quot;<br>                  Statement:<br>                      - Effect: Allow<br>                        Action:<br>                            - ec2:DescribeSecurityGroups<br>                            - ec2:RevokeSecurityGroupIngress<br>                        Resource: &quot;*&quot;<br>  <br>  # 4. Lambda Function for Automated Remediation<br>  SREAutomatedRemediationFunction:<br>    Type: AWS::Lambda::Function<br>    Properties:<br>      FunctionName: automated-sre-remediation<br>      Handler: index.lambda_handler<br>      Role: !GetAtt LambdaExecutionRole.Arn<br>      Runtime: python3.11<br>      Timeout: 10<br>      Code:<br>        ZipFile: |<br>          import boto3<br>          import json<br>          import logging<br><br>          logger = logging.getLogger()<br>          logger.setLevel(logging.INFO)<br><br>          def lambda_handler(event, context):<br>              ec2 = boto3.client(&#39;ec2&#39;)<br>              <br>              try:<br>                  detail = event.get(&#39;detail&#39;, {})<br>                  params = detail.get(&#39;requestParameters&#39;, {})<br>                  sg_id = params.get(&#39;groupId&#39;)<br>                  <br>                  # CloudTrail wraps the list in &#39;items&#39;<br>                  permissions_list = params.get(&#39;ipPermissions&#39;, {}).get(&#39;items&#39;, [])<br>                  <br>                  for p in permissions_list:<br>                      from_port = p.get(&#39;fromPort&#39;)<br>                      ip_protocol = p.get(&#39;ipProtocol&#39;, &#39;tcp&#39;)<br>                      to_port = p.get(&#39;toPort&#39;)<br>                      <br>                      # Safely handle the integer conversion<br>                      if int(from_port or 0) == 22:<br>                          <br>                          ranges = p.get(&#39;ipRanges&#39;, {}).get(&#39;items&#39;, [])<br>                          for r in ranges:<br>                              cidr_ip = r.get(&#39;cidrIp&#39;)<br>                              <br>                              if cidr_ip == &#39;0.0.0.0/0&#39;:<br>                                  logger.info(f&quot;VIOLATION DETECTED: Port 22 open to 0.0.0.0/0 on SG {sg_id}. Reverting...&quot;)<br>                                  <br>                                  # --- THE FIX ---<br>                                  # Must map the camelCase CloudTrail data to PascalCase Boto3 parameters<br>                                  revoke_params = {<br>                                      &#39;IpProtocol&#39;: ip_protocol,<br>                                      &#39;FromPort&#39;: int(from_port),<br>                                      &#39;ToPort&#39;: int(to_port),<br>                                      &#39;IpRanges&#39;: [{&#39;CidrIp&#39;: cidr_ip}]<br>                                  }<br>                                  <br>                                  ec2.revoke_security_group_ingress(<br>                                      GroupId=sg_id,<br>                                      IpPermissions=[revoke_params]<br>                                  )<br>                                  logger.info(f&quot;Successfully revoked unauthorized rule from {sg_id}&quot;)<br><br>              except Exception as e:<br>                  logger.error(f&quot;Error during remediation: {e}&quot;)<br><br>  # 5. EventBridge Rule to Trigger Lambda on Security Group Changes<br>  SecurityGroupChangeRule:<br>    Type: AWS::Events::Rule<br>    Properties:<br>      Description: &quot;Trigger Lambda function on Security Group Ingress changes&quot;<br>      Name: SREAutomatedRemediationRule<br>      EventPattern:<br>        source:<br>          - &quot;aws.ec2&quot;<br>        detail-type:<br>          - &quot;AWS API Call via CloudTrail&quot;<br>        detail:<br>          eventSource:<br>            - &quot;ec2.amazonaws.com&quot;<br>          eventName:<br>            - &quot;AuthorizeSecurityGroupIngress&quot;<br>      State: &quot;ENABLED&quot;      <br>      Targets:<br>        - Arn: !GetAtt SREAutomatedRemediationFunction.Arn<br>          Id: &quot;SREAutomatedRemediationFunctionTarget&quot;<br>  <br>  # 6. Permissions for EventBridge to Invoke Lambda<br>  LambdaInvokePermission:<br>    Type: AWS::Lambda::Permission<br>    Properties:<br>      FunctionName: !Ref SREAutomatedRemediationFunction<br>      Action: &quot;lambda:InvokeFunction&quot;<br>      Principal: &quot;events.amazonaws.com&quot;<br>      SourceArn: !GetAtt SecurityGroupChangeRule.Arn</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvdOzci826SGxHirpGEJyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuO2bg3WFwMHepasH13iRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keC4JLKGTN3yyiREt6VPTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jdArErbxvJvxE3l65VPlg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e64c7487fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the Grind: Testing and Auto-Deploying CloudFormation with GitHub Actions]]></title>
            <link>https://medium.com/@pails-topper.3j/automating-the-grind-testing-and-auto-deploying-cloudformation-with-github-actions-1b4ca58692f7?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b4ca58692f7</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 19:48:58 GMT</pubDate>
            <atom:updated>2026-04-13T20:00:45.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCuxv4QW8wVQpTFBB7wVDQ.png" /></figure><p>Let’s be real. Running manual AWS CLI commands to deploy your infrastructure is a one-way ticket to Headache City. I recently spent about four hours of my life diving deep into GitHub Actions to fix this exact pain point. Between writing the YAML files, debugging the configs, and fighting the urge to just use Click-Ops in the AWS Console, it was a journey.</p><p>My goal was simple: create an antidote for the manual deployment pain. Here’s how I built an automated pipeline that lints, tests, and deploys CloudFormation templates while keeping me updated on Slack.</p><p>As always, this was done in a working branch off the main branch. Multiple commits after each update in the working branch kept the main branch code pristine, trackable and auditable pushes, and makes collaborating a breeze.</p><h3>The Powerhouse: yamlTestandDeploy.yaml</h3><p>This workflow is the heart of the operation. It lives in the .github/workflows directory and handles everything from the moment I push code to the second the stack is live.</p><h3>The Triggers and Setup</h3><p>We start by defining when the action runs. It triggers on <strong>pushes</strong> and <strong>pull requests</strong> to the main branch.</p><ul><li><strong>Checkout Code</strong>: The runner grabs the latest code from the repo.</li><li><strong>Filter Changed Files</strong>: I didn’t want to redeploy everything every time. This step identifies only the .yaml or .yml files that changed, specifically excluding anything inside the .github folder to avoid infinite loops or unnecessary runs.</li></ul><h3>Linting via Docker (No More “Creative” Bugs)</h3><p>Before we even touch AWS, we lint. I used a Docker container to run con-lint.</p><blockquote><strong><em>What is linting?</em></strong><em> It’s an automated process that flags potential bugs or “creative licenses” that stray too far from best practices. It saves me from the embarrassment of a failed deployment caused by a simple syntax error.</em></blockquote><h3>The Deployment Logic</h3><p>If the linting gets a ✅, the runner logs into AWS using secrets stored in GitHub and kicks off the deployment.</p><ul><li><strong>Automatic Stack Naming</strong>: The runner generates the stack name based on the filename.</li><li><strong>Self-Healing</strong>: It checks if a previous run left a stack in a ROLLBACK_COMPLETE state. If it did, it deletes it and waits for completion so it can start fresh.</li><li><strong>Smart Deploy</strong>: I used “aws cloudformation deploy” instead of “create-stack”. Why? Because deploy is smarter. It checks if the stack exists and chooses between “create-stack” or &quot;update-stack&quot; automatically.</li></ul><h3>Security First: github-deployer.yaml</h3><p>You can’t just give a GitHub Action the keys to the kingdom. Following the principle of <strong>least privilege</strong>, I created a dedicated IAM service user via a separate CloudFormation template.</p><p>YAML</p><pre># Snippet from github-deployer.yaml<br>GitHubActionsUser:<br>  Type: &#39;AWS::IAM::User&#39;<br>  Properties:<br>    UserName: &#39;GitHub-actions-deployer&#39;<br>    ManagedPolicyArns:<br>      - &#39;arn:aws:iam::aws:policy/AWSCloudFormationFullAccess&#39;</pre><p>Instead of full AdministratorAccess, I granted AWSCloudFormationFullAccess. The template also generates the AccessKeyId and SecretAccessKey needed for the GitHub secrets.</p><h3>The Stay Informed Step: Slack Notifications</h3><p>Whether the job passes or fails, I need to know without constantly refreshing the GitHub Actions tab. I used a Slack webhook to send a notification to a specific channel at the very end of the process.</p><p>The payload includes:</p><ul><li><strong>Job Status</strong>: Did it pass or fail?</li><li><strong>Repo &amp; Workflow Links</strong>: So I can jump straight to the logs if something went sideways.</li></ul><h3>Lessons Learned</h3><p>Building this taught me that a little bit of upfront automation saves hours of manual work later. I’ll admit, I leaned on GitHub and AWS documentation (and a bit of AI) to nail the stack name formatting and the file filtering logic, but the result is a clean, repeatable process that keeps me out of the AWS Console.</p><p>If you’re still deploying infrastructure manually, do yourself a favor, build a pipeline. Your future self will thank you.</p><p><strong>#AWS #CloudEngineering #GitHubActions #CloudFormation #DevOps #Automation</strong></p><p>How are you currently handling stack rollbacks in your automated pipelines?</p><p>References:</p><pre># Name: CloudFormation Test and Deploy Workflow<br># Description: GitHub Actions workflow to test and deploy CloudFormation templates with Slack notifications.<br># Author: Rob<br># Created: 2026-04-13<br># Updated By     Date         Version    Description<br># Rob            2026-04-13   1.0        Initial creation of the GitHub Actions workflow for testing and deploying CloudFormation templates with Slack notifications.<br># Rob            2026-04-13   1.1        Updated AWS credentials step to use<br># Rob            2026-04-13   1.2        Added logic to handle ROLLBACK_COMPLETE state and fetch failure reasons for better Slack notifications.<br># Rob            2026-04-13   1.3        Updated Slack notification to use modern with: syntax and include more detailed information about the deployment status.<br># <br><br>name: CloudFormation Test and Deploy<br>run-name: ${{ github.actor }} is running CloudFormation Test and Deploy ▄︻デ══━一💥 &lt;/&gt;<br><br>on:<br>  push:<br>    branches: [main]<br>  pull_request:<br>    branches: [main]<br><br>jobs:<br>  test-and-deploy:<br>    name: Test and Deploy CFN<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0<br><br>      - name: Get list of changed files<br>        id: changed-files<br>        run: |<br>          # Finds changed .yaml files but EXCLUDES the .github directory<br>          FILES=$(git diff --name-only ${{ github.event.before }} ${{ github.event.after }} | grep -E &#39;\.(yaml|yml)$&#39; | grep -v &#39;^.github/&#39; | xargs || true)<br>          echo &quot;files=$FILES&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>      - name: Build and Run Docker Tester<br>        if: steps.changed-files.outputs.files != &#39;&#39;<br>        run: |<br>          echo &quot;FROM python:3.9-slim<br>          RUN pip install cfn-lint awscli<br>          WORKDIR /data&quot; &gt; Dockerfile.test<br>          docker build -t cfn-tester -f Dockerfile.test .<br>          <br>          for file in ${{ steps.changed-files.outputs.files }}; do<br>            echo &quot;::group::Linting $file&quot;<br>            docker run --rm -v $(pwd):/data cfn-tester cfn-lint &quot;$file&quot;<br>            echo &quot;::endgroup::&quot;<br>          done<br><br>      - name: Configure AWS credentials<br>        # Updated to use _GITHUB suffix for secrets<br>        if: github.ref == &#39;refs/heads/main&#39; &amp;&amp; github.event_name == &#39;push&#39; &amp;&amp; steps.changed-files.outputs.files != &#39;&#39;<br>        uses: aws-actions/configure-aws-credentials@v4<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID_GITHUB }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY_GITHUB }}<br>          aws-region: us-east-1<br><br>      - name: Deploy and Log Status<br>        if: github.ref == &#39;refs/heads/main&#39; &amp;&amp; github.event_name == &#39;push&#39; &amp;&amp; steps.changed-files.outputs.files != &#39;&#39;<br>        run: |<br>          for file in ${{ steps.changed-files.outputs.files }}; do<br>            STACK_NAME=$(basename &quot;$file&quot; | sed &#39;s/\.[^.]*$//&#39;)-stack<br>            echo &quot;🔍 Checking status of stack: $STACK_NAME&quot;<br><br>            # Check if stack is in a failed &#39;ROLLBACK_COMPLETE&#39; state from a previous bad run<br>            STACK_STATUS=$(aws cloudformation describe-stacks --stack-name &quot;$STACK_NAME&quot; --query &#39;Stacks[0].StackStatus&#39; --output text 2&gt;/dev/null || echo &quot;NOT_FOUND&quot;)<br><br>            if [ &quot;$STACK_STATUS&quot; == &quot;ROLLBACK_COMPLETE&quot; ]; then<br>              echo &quot;⚠️ Stack is in ROLLBACK_COMPLETE. Deleting so it can be recreated...&quot;<br>              aws cloudformation delete-stack --stack-name &quot;$STACK_NAME&quot;<br>              aws cloudformation wait stack-delete-complete --stack-name &quot;$STACK_NAME&quot;<br>            fi<br><br>            echo &quot;🚀 Deploying $file...&quot;<br>            # Deploy handles create/update automatically and rolls back on failure by default<br>            if aws cloudformation deploy \<br>              --template-file &quot;$file&quot; \<br>              --stack-name &quot;$STACK_NAME&quot; \<br>              --capabilities CAPABILITY_NAMED_IAM \<br>              --no-fail-on-empty-changeset; then<br>              <br>              echo &quot;✅ Deployment successful for $STACK_NAME&quot;<br>            else<br>              echo &quot;❌ Deployment failed for $STACK_NAME. Automatic rollback initiated by AWS.&quot;<br>              <br>              # Fetch failure reason for the Slack notification/Logs<br>              aws cloudformation describe-stack-events \<br>                --stack-name &quot;$STACK_NAME&quot; \<br>                --query &#39;StackEvents[?ResourceStatus==`CREATE_FAILED` || ResourceStatus==`UPDATE_FAILED`].[LogicalResourceId, ResourceStatusReason]&#39; \<br>                --output table<br>              <br>              exit 1 # Fail the job so Slack notification reflects the failure<br>            fi<br>          done<br><br>      # Final step: Send notification using modern with: syntax<br>      - name: Send Slack Notification<br>        if: always() &amp;&amp; steps.changed-files.outputs.files != &#39;&#39;<br>        uses: slackapi/slack-github-action@v2.0.0<br>        with:<br>          # The modern syntax uses webhook: inside the with block<br>          webhook: ${{ secrets.SLACK_WEBHOOK_URL }}<br>          webhook-type: incoming-webhook<br>          payload: |<br>            {<br>              &quot;text&quot;: &quot;CloudFormation Deployment Status: ${{ job.status }}\nRepo: ${{ github.repository }}\nWorkflow: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\nTriggered by: ${{ github.actor }}&quot;<br>            }</pre><pre># Name: github-deployer.yaml<br># Description: CloudFormation template to create an IAM user and group for GitHub Actions deployment with necessary permissions.<br># Author: Rob<br># Created: 2026-04-12<br># Updated By     Date         Version    Description<br># Rob            2026-04-13   1.0        Initial creation of the IAM CloudFormation template for GitHub Actions deployment.<br># Rob            2026-04-14   1.1        Correct IAM policy ARN for GitHub Actions deployment in github-deployer.yaml<br><br>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: Creates an IAM User for GitHub Actions with Admin permissions and generates access keys.<br><br>Resources:<br>  GitHubActionsUser:<br>    Type: &#39;AWS::IAM::User&#39;<br>    Properties:<br>      UserName: &#39;GitHub-actions-deployer&#39;<br>      ManagedPolicyArns:<br>        - &#39;arn:aws:iam::aws:policy/AWSCloudFormationFullAccess&#39;<br><br>  GitHubActionsAccessKey:<br>    Type: &#39;AWS::IAM::AccessKey&#39;<br>    Properties:<br>      UserName: !Ref GitHubActionsUser<br><br>Outputs:<br>  AccessKeyId:<br>    Description: The Access Key ID for the new IAM user.<br>    Value: !Ref GitHubActionsAccessKey<br>  <br>  SecretAccessKey:<br>    Description: The Secret Access Key for the new IAM user.<br>    Value: !GetAtt GitHubActionsAccessKey.SecretAccessKey</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b4ca58692f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infrastructure as Code: Application Load Balancer and an Auto-Scaling Group of EC2s (and Surviving…]]></title>
            <link>https://medium.com/@pails-topper.3j/infrastructure-as-code-application-load-balancer-and-an-auto-scaling-group-of-ec2s-and-surviving-9715eb298946?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9715eb298946</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-auto-scaling]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 19:55:37 GMT</pubDate>
            <atom:updated>2026-04-12T20:10:32.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>Infrastructure as Code: Application Load Balancer and an Auto-Scaling Group of EC2s (and Surviving the Launch Template Trap)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrlKlrs2oi1Up_5gYCmeIA.png" /></figure><p>Welcome back to another build log. If you are stepping into the world of Cloud Architecture, there is a moment when you realize that clicking through the AWS Management Console just isn’t going to cut it anymore.</p><p>To build environments that are secure, repeatable, and scalable, you need Infrastructure as Code (IaC).</p><p>Recently, I sat down to write a CloudFormation template to deploy a highly available web server environment. The goal was to build a solid foundation: a custom Virtual Private Cloud (VPC), multi-tier subnets, an Auto Scaling Group (ASG), and an Application Load Balancer (ALB) to distribute traffic across my fleet of instances.</p><p>It was going great — until the stack creation threw a massive red ROLLBACK_COMPLETED error in my face.</p><p>Here is a breakdown of how the architecture was built, piece by piece, and the major troubleshooting moments that saved the deployment.</p><p>Before I forget, I also completed all of this using version control in GitHub and creating a working branch to never update the main branch directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*ckJuSzExDpkfsZAhP74bLg.png" /><figcaption>Creating the working branch and the stack using AWS CLI.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*AS5BRLT6WfpppbeEseBhFQ.png" /><figcaption>Developing in a working branch</figcaption></figure><p>All while monitoring pushes to and pulls into the main branch in Slack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pe0ADlHOIA485I_tuKpdmA.png" /><figcaption>Slack Notifications using GitHub Actions</figcaption></figure><h3>1. The Foundation: The VPC and Subnets</h3><p>You can’t build a house without a foundation, and in AWS, that foundation is your VPC. I started by carving out a custom network (172.16.0.0/16).</p><p>To ensure high availability and proper security zoning, I split the network across two different Availability Zones (AZs). Inside each AZ, I created three specific subnets:</p><ul><li><strong>Public Subnets:</strong> Where internet-facing resources (like our Load Balancer) live.</li><li><strong>App Private Subnets:</strong> Reserved for backend application logic.</li><li><strong>Data Private Subnets:</strong> Locked down tightly for databases.</li></ul><h3>2. The Front Door: Internet Gateway &amp; Load Balancing</h3><p>A VPC is completely isolated by default. To let our public subnets talk to the internet, we need an Internet Gateway (IGW) and a Public Route Table pointing 0.0.0.0/0 to that IGW.</p><p>But we don’t want users talking directly to our EC2 instances. We want them talking to a Load Balancer. Enter the <strong>Application Load Balancer (ALB)</strong>.</p><p>The ALB sits in our Public Subnets and acts as a traffic cop. To make it work, I had to define three CloudFormation resources:</p><ol><li><strong>The ALB itself </strong>AWS::ElasticLoadBalancingV2::LoadBalancer<strong>:</strong> Set to internet-facing and attached to my two Public Subnets.</li><li><strong>The Target Group </strong>AWS::ElasticLoadBalancingV2::TargetGroup<strong>:</strong> This is the logical grouping of my EC2 instances. It tells the ALB on which port to send the traffic (Port 80) and how to perform health checks.</li><li><strong>The Listener </strong>AWS::ElasticLoadBalancingV2::Listener<strong>:</strong> This sits on the ALB, listens for incoming HTTP requests on Port 80, and forwards them to the Target Group.</li></ol><h3>3. The Fleet: Auto Scaling Groups (Separate Project)</h3><p>Instead of manually launching EC2 instances and adding them to the Load Balancer, I defined an Auto Scaling Group (ASG) to handle it for me. I configured it with a minimum size of 1, a maximum size of 3, and a desired capacity of 2.</p><h3>4. The Watcher: CloudWatch Alarms</h3><p>Scaling is great, but it needs a trigger. I implemented an AWS::CloudWatch::Alarm to monitor the CPUUtilization metric of the ASG. If the average CPU usage spikes above 70% for 5 minutes, the alarm trips. This triggers a Scaling Policy that adds one additional EC2 instance to the group to handle the incoming load.</p><h3>The “Aha!” Moments</h3><p>Building infrastructure via CloudFormation forces you to think deeply about how AWS services interconnect. Naturally, I ran into two massive roadblocks.</p><h3>Gotcha #1: The Deprecation Trap</h3><p>When building out the ASG, I initially used AWS::AutoScaling::LaunchConfiguration to define my EC2 template. The stack immediately failed with this error:</p><blockquote>“This AWS::AutoScaling::LaunchConfiguration resource is in a CREATE_FAILED state.</blockquote><blockquote>Resource handler returned message: “The Launch Configuration creation operation is not available in your account. Use launch templates to create configuration templates for your Auto Scaling groups.”</blockquote><blockquote>CloudFormation error message</blockquote><p><strong>The Fix:</strong> I was relying on legacy documentation. AWS is actively deprecating Launch Configurations. I had to update the YAML by migrating to AWS::EC2::LaunchTemplate. It requires nesting properties under a LaunchTemplateData block and using SecurityGroupIds instead of SecurityGroups. Once updated, the template deployed.</p><h3>Gotcha #2: The Health Check Loop of Death</h3><p>The stack finally created successfully, but when I looked at the EC2 console, my instances were constantly terminating and recreating themselves every few minutes.</p><p><strong>What went wrong?</strong> Security Groups. I had attached my web servers to a Security Group, but I forgot to explicitly allow traffic <em>from</em> the ALB. Because the ALB couldn’t reach the EC2 instances on Port 80, the ALB’s Health Check failed.</p><p>When a Target Group health check fails, the ALB tells the Auto Scaling Group, <em>“Hey, this instance is broken.”</em> The ASG responds by terminating the “broken” instance and spinning up a new one… which also fails the health check. Hence, the infinite loop of death.</p><p><strong>The Fix:</strong> I updated the WebServerSecurityGroup to explicitly allow inbound TCP Port 80 traffic sourced directly from the Load Balancer&#39;s Security Group. Instantly, the health checks passed, the instances stabilized, and my &quot;Hello World&quot; webpage was beautifully load-balanced.</p><h3>Wrapping Up</h3><p>A single syntax error, a deprecated resource, or a missing security group rule can bring a whole deployment down. But those failures are where the real learning happens.</p><p>Always check the latest AWS documentation, don’t be afraid of the error logs, and remember: friends don’t let friends use Launch Configurations in 2026!</p><pre># Name:        Application Load Balancing Project<br># Created By:  Rob Satnarain<br># Create Date: 4/11/2026<br># <br># Updated By    Version     Date          Notes<br># Rob           1.0         4/11/2026     Initial creation of EC2 instances in public and private subnets<br># Rob           1.1         4/12/2026     Added Application Load Balancer and Target Group with Web Server instances as targets<br><br><br>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: &quot;CloudFormation template for EC2 instances in public and private subnets with an Application Load Balancer&quot;<br><br>Resources: <br>#My VPC<br>  MyVPC: <br>    Type: &#39;AWS::EC2::VPC&#39;<br>    Properties: <br>      CidrBlock: &#39;172.16.0.0/16&#39;<br>      EnableDnsSupport: true<br>      EnableDnsHostnames: true<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC <br>#Public Subnet is AZ 1  <br>  PublicSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.1.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1A<br><br> #App Private Subnet in AZ 1 <br>  AppPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.2.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1A<br>  <br># Data Private Subnet in AZ 1 <br>  DataPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.3.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1A<br><br># Public Subnet in AZ 2             <br>  PublicSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.4.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1B<br>  <br># App Private Subnet in AZ 2  <br>  AppPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.5.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1B<br><br># Data Private Subnet in AZ 2  <br>  DataPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.6.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1B<br><br>  # Create Internet Gateway<br>  InternetGateway:<br>    Type: AWS::EC2::InternetGateway<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC-IGW<br><br>  # Attach the Internet Gateway to MyVPC<br>  AttachGateway:<br>    Type: AWS::EC2::VPCGatewayAttachment<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      InternetGatewayId: !Ref InternetGateway<br><br>  # Public Route Tables<br>  PublicRouteTable:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      Tags:<br>        - Key: Name<br>          Value: PublicRouteTable<br><br>  # Public Routes<br>  PublicRoute:<br>    Type: AWS::EC2::Route<br>    DependsOn: AttachGateway<br>    Properties:<br>      RouteTableId: !Ref PublicRouteTable<br>      DestinationCidrBlock: 0.0.0.0/0<br>      GatewayId: !Ref InternetGateway<br><br>  # Public Subnet 1A Route Table Association<br>  PublicSubnet1ARouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1A<br>      RouteTableId: !Ref PublicRouteTable<br><br>  # Public Subnet 1B Route Table Association<br>  PublicSubnet1BRouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1B<br>      RouteTableId: !Ref PublicRouteTable<br><br>  #application load balance<br>  MyLoadBalancer:<br>    Type: &#39;AWS::ElasticLoadBalancingV2::LoadBalancer&#39;<br>    Properties:<br>      Name: MyLoadBalancer<br>      Subnets:<br>        - !Ref PublicSubnet1A<br>        - !Ref PublicSubnet1B<br>      SecurityGroups:<br>        - !Ref WebServerSecurityGroup<br>      Tags:<br>        - Key: Name<br>          Value: MyLoadBalancer<br><br>  # Target Group for the Load Balancer<br>  MyTargetGroup:<br>    Type: &#39;AWS::ElasticLoadBalancingV2::TargetGroup&#39;<br>    Properties:<br>      Name: MyTargetGroup<br>      Port: 80<br>      Protocol: &#39;HTTP&#39;<br>      VpcId: !Ref MyVPC<br>      Targets:<br>        - Id: !Ref WebServerInstance1A<br>        - Id: !Ref WebServerInstance1B<br>      Tags:<br>        - Key: Name<br>          Value: MyTargetGroup<br><br>  # Listener for the Load Balancer<br>  MyListener:<br>    Type: &#39;AWS::ElasticLoadBalancingV2::Listener&#39;<br>    Properties:<br>      LoadBalancerArn: !Ref MyLoadBalancer<br>      Port: 80<br>      Protocol: &#39;HTTP&#39;<br>      DefaultActions:<br>        - Type: &#39;forward&#39;<br>          TargetGroupArn: !Ref MyTargetGroup  <br>  <br>  #Web Server Security Group and ALB SG<br>  WebServerSecurityGroup: <br>    Type: &#39;AWS::EC2::SecurityGroup&#39;<br>    Properties:<br>      GroupDescription: &#39;Security group for web servers and ALB using HTTP&#39;<br>      VpcId: !Ref MyVPC<br>      SecurityGroupIngress:<br>        - IpProtocol: &#39;tcp&#39;<br>          FromPort: 80<br>          ToPort: 80<br>          CidrIp: &#39;0.0.0.0/0&#39;<br><br>  <br>  #webServerInstance1A with an Apache Web Server installed and running<br>  WebServerInstance1A:<br>    Type: &#39;AWS::EC2::Instance&#39;<br>    Properties:<br>      InstanceType: t3.micro<br>      ImageId: ami-0ea87431b78a82070<br>      SubnetId: !Ref PublicSubnet1A<br>      SecurityGroupIds:<br>         - !Ref WebServerSecurityGroup<br>      Tags:<br>        - Key: Name<br>          Value: WebServerInstance1A<br>      UserData: <br>        Fn::Base64: |<br>          #!/bin/bash<br>          yum install -y httpd<br>          systemctl start httpd<br>          systemctl enable httpd<br>          echo &quot;Hello World from WebServerInstance1A&quot; &gt; /var/www/html/index.html<br><br>  #webServerInstance1B with an Apache Web Server installed and running<br>  WebServerInstance1B:<br>    Type: &#39;AWS::EC2::Instance&#39;<br>    Properties:<br>      InstanceType: t3.micro<br>      ImageId: ami-0ea87431b78a82070<br>      SubnetId: !Ref PublicSubnet1B<br>      SecurityGroupIds:<br>         - !Ref WebServerSecurityGroup<br>      Tags:<br>        - Key: Name<br>          Value: WebServerInstance1B<br>      UserData: <br>        Fn::Base64: |<br>          #!/bin/bash<br>          yum install -y httpd<br>          systemctl start httpd<br>          systemctl enable httpd<br>          echo &quot;Hello World from WebServerInstance1B&quot; &gt; /var/www/html/index.htm<br></pre><pre># Name: Auto Scaling Group Project<br># Created By: Rob Satnarain<br># Create Date: 4/12/2026<br># <br># Updated By    Version     Date          Notes<br># Rob           1.0         4/12/2026     Initial creation of EC2 instances in public and private subnets<br># Rob           1.1         4/12/2026     Added Application Load Balancer and Target Group with Web Server instances as targets<br># Rob           1.2         4/12/2026     Added Auto Scaling Group with Web Server instances as targets and updated ALB Target Group to reference ASG instead of individual instances<br># Rob           1.3         4/12/2026     Added CloudWatch Alarm for Auto Scaling Group to trigger scale out policy based on high CPU utilization and added Scaling Policy to scale out by adding 1 instance when the alarm is triggered<br># Rob           1.4         4/12/2026     Updated Launch Configuration to Launch Template and updated Auto Scaling Group to reference Launch Template instead of Launch Configuration<br><br>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: &quot;CloudFormation template for EC2 instances in public and private subnets with an Application Load Balancer and Auto Scaling Group&quot;<br><br>Resources: <br>#My VPC<br>  MyVPC: <br>    Type: &#39;AWS::EC2::VPC&#39;<br>    Properties: <br>      CidrBlock: &#39;172.16.0.0/16&#39;<br>      EnableDnsSupport: true<br>      EnableDnsHostnames: true<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC <br>#Public Subnet is AZ 1  <br>  PublicSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.1.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1A<br><br> #App Private Subnet in AZ 1 <br>  AppPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.2.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1A<br>  <br># Data Private Subnet in AZ 1 <br>  DataPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.3.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1A<br><br># Public Subnet in AZ 2             <br>  PublicSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.4.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1B<br>  <br># App Private Subnet in AZ 2  <br>  AppPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.5.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1B<br><br># Data Private Subnet in AZ 2  <br>  DataPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.6.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1B<br><br>  # Create Internet Gateway<br>  InternetGateway:<br>    Type: AWS::EC2::InternetGateway<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC-IGW<br><br>  # Attach the Internet Gateway to MyVPC<br>  AttachGateway:<br>    Type: AWS::EC2::VPCGatewayAttachment<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      InternetGatewayId: !Ref InternetGateway<br><br>  # Public Route Tables<br>  PublicRouteTable:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      Tags:<br>        - Key: Name<br>          Value: PublicRouteTable<br><br>  # Public Routes<br>  PublicRoute:<br>    Type: AWS::EC2::Route<br>    DependsOn: AttachGateway<br>    Properties:<br>      RouteTableId: !Ref PublicRouteTable<br>      DestinationCidrBlock: 0.0.0.0/0<br>      GatewayId: !Ref InternetGateway<br><br>  # Public Subnet 1A Route Table Association<br>  PublicSubnet1ARouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1A<br>      RouteTableId: !Ref PublicRouteTable<br><br>  # Public Subnet 1B Route Table Association<br>  PublicSubnet1BRouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1B<br>      RouteTableId: !Ref PublicRouteTable<br><br>  #Web Server Security Group and ALB SG<br>  WebServerSecurityGroup: <br>    Type: &#39;AWS::EC2::SecurityGroup&#39;<br>    Properties:<br>      GroupDescription: &#39;Security group for web servers and ALB using HTTP&#39;<br>      VpcId: !Ref MyVPC<br>      SecurityGroupIngress:<br>        - IpProtocol: &#39;tcp&#39;<br>          FromPort: 80<br>          ToPort: 80<br>          CidrIp: &#39;0.0.0.0/0&#39;<br>  <br>  #My Launch Configuration<br>  MyLaunchConfiguration:<br>    Type: &#39;AWS::EC2::LaunchTemplate&#39;<br>    Properties:<br>      LaunchTemplateData:<br>        ImageId: ami-0ea87431b78a82070 # Amazon Linux 2 AMI (HVM), SSD Volume Type - us-east-1<br>        InstanceType: t3.micro<br>        SecurityGroupIds:<br>          - !Ref WebServerSecurityGroup<br>        UserData: <br>          Fn::Base64: !Sub |<br>            #!/bin/bash<br>            echo &quot;Hello World from $(hostname -f)&quot; &gt; /var/www/html/index.html<br>            yum install -y httpd<br>            systemctl enable httpd<br>            systemctl start httpd<br><br>  #My Auto Scaling Group<br>  MyAutoScalingGroup:<br>    Type: &#39;AWS::AutoScaling::AutoScalingGroup&#39;<br>    Properties:<br>      LaunchTemplate:<br>        LaunchTemplateId: !Ref MyLaunchConfiguration<br>        Version: !GetAtt MyLaunchConfiguration.LatestVersionNumber<br>      MinSize: &#39;1&#39;<br>      MaxSize: &#39;3&#39;<br>      DesiredCapacity: &#39;2&#39;<br>      VPCZoneIdentifier: <br>        - !Ref PublicSubnet1A<br>        - !Ref PublicSubnet1B<br><br>  #Alarm for Auto Scaling Group for High CPU Utilization<br>  CPUAlarmHigh:<br>    Type: &#39;AWS::CloudWatch::Alarm&#39;<br>    Properties:<br>      AlarmDescription: &#39;Alarm if CPU exceeds 70%&#39;<br>      Namespace: AWS/EC2<br>      MetricName: CPUUtilization<br>      Dimensions:<br>        - Name: AutoScalingGroupName<br>          Value: !Ref MyAutoScalingGroup<br>      Statistic: Average<br>      Period: 300<br>      EvaluationPeriods: 1<br>      Threshold: 70<br>      ComparisonOperator: GreaterThanThreshold<br>      AlarmActions:<br>        - !Ref ScaleOutPolicy<br><br>  #Scaling Policy to Scale Out<br>  ScaleOutPolicy:<br>    Type: &#39;AWS::AutoScaling::ScalingPolicy&#39;<br>    Properties:<br>      AutoScalingGroupName: !Ref MyAutoScalingGroup<br>      PolicyType: SimpleScaling<br>      ScalingAdjustment: 1<br>      Cooldown: 300 <br>      AdjustmentType: ChangeInCapacity</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9715eb298946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Red to Green: Building a Custom GitHub Action for Slack Notifications]]></title>
            <link>https://medium.com/@pails-topper.3j/from-red-to-green-building-a-custom-github-action-for-slack-notifications-353e3393d007?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/353e3393d007</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 22:26:05 GMT</pubDate>
            <atom:updated>2026-04-11T22:26:05.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*bT4Tp_z2dT2Ug5vuNdvCow.png" /></figure><h3>Wait… I thought the title said it was a success.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_Kp7Frw6iOmxV1FVWERRg.png" /><figcaption>Github Actions workflow logs</figcaption></figure><p>Failed. Success. Failed again.</p><p>If you’ve spent any time working with CI/CD pipelines, that cycle probably sounds very familiar. But recently, after wrestling a few red X’s into green checkmarks, I finally grabbed the bull by the horns and built a custom GitHub Action that pushes notifications directly to a Slack channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ws2UVoCzC7bAiuQQqoHJYg.png" /><figcaption>Sample Slack notification triggered by a Github Action.</figcaption></figure><p>The goal was simple: trigger a Slack message whenever code is pushed to the main branch or a pull request targeting main is opened.</p><p>Why bother? Because visibility speeds up delivery. Real-time PR notifications reduce the time to resolution for outstanding fixes, cleanups, and new features. When the team knows exactly what’s happening in the repository, customers (internal and external) get a stable environment faster, and we get to focus on building rather than babysitting the pipeline.</p><p>Here is how I set it up, along with a few Aha! troubleshooting moments I encountered along the way.</p><h3>Prerequisites</h3><p>Before writing any YAML, you need a place for your notifications to land.<br><a href="https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/">Documentation from Slack</a></p><ol><li><strong>A Slack Workspace:</strong> You can use the free version of Slack.</li><li><strong>A Slack App:</strong> Create a new Slack app (or use an existing one) in your workspace.</li><li><strong>The Webhook URL:</strong> The main objective here is to generate an Incoming Webhook. Once you configure it for a specific channel, copy that Webhook URL from the Slack App’s dashboard. Keep it handy — we’ll need it soon.</li></ol><h3>Step 1: Configuring the GitHub Action</h3><p>For this project, I used the official <a href="https://github.com/slackapi/slack-github-action">Slack GitHub Action</a>.</p><p>GitHub Actions live inside your repository in a specific folder structure. If you don’t have one yet, create a directory called .github/workflows at the root of your project. Inside that directory, create a configuration file. I named mine slack.yaml.</p><p>Here is the finalized code:</p><pre>name: Slack Notification Demo<br>on:<br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main<br><br>jobs:<br>  notify:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Send custom JSON data to Slack<br>        id: slack<br>        uses: slackapi/slack-github-action@v2.0.0<br>        with:<br>          webhook: ${{ secrets.SLACK_WEBHOOK_URL }}<br>          webhook-type: incoming-webhook<br>          payload: |<br>            {<br>              &quot;text&quot;: &quot;GitHub Action Build Result: ${{ job.status }}&quot;,<br>              &quot;blocks&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;section&quot;,<br>                  &quot;text&quot;: {<br>                    &quot;type&quot;: &quot;mrkdwn&quot;,<br>                    &quot;text&quot;: &quot;*Hello* ${{ github.actor }}\n\n*Status:* ${{ job.status }}\n*Repo:* ${{ github.repository }}\n*Commit:* ${{ github.sha }}\n*Event:* ${{ github.event_name }}\n*Workflow:* ${{ github.workflow }}\n*Actor:* ${{ github.actor }}\n*Run ID:* ${{ github.run_id }}\n*Run Number:* ${{ github.run_number }}\n*Job:* ${{ github.job }}\n*Ref:* ${{ github.ref }}\n*Workflow URL:* &lt;${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow Run&gt;&quot;<br>                  }<br>                }<br>              ]<br>            }</pre><p><em>Note: If you are testing this on a working branch — which you should be, kudos to you for not pushing straight to main! This action won’t trigger until you actually open a PR against main or merge it.</em></p><h3>Step 2: Securing Your Webhook URL</h3><p>You should <strong>never</strong> hardcode credentials or webhook URLs directly into your repository code. Instead, we use GitHub Secrets.</p><ol><li>Navigate to your repository on GitHub.</li><li>Go to <strong>Settings &gt; Secrets and variables &gt; Actions</strong>.</li><li>Click <strong>New repository secret</strong>.</li><li>Set the name to SLACK_WEBHOOK_URL and paste your Slack Webhook URL into the secret field.</li></ol><p>Now, when the YAML file calls ${{ secrets.SLACK_WEBHOOK_URL }}, GitHub will securely add it at runtime.</p><h3>The “Aha!” Moments (Learning from the Logs)</h3><p>Remember those failures I mentioned earlier? Writing the code is only half the battle. Reading the logs is the other. By navigating to the <strong>Actions</strong> tab in my repository, I was able to click through my workflow runs and see exactly where things went sideways.</p><p>Here are the two biggest hurdles I hit, so you don’t have to:</p><h3>1. RTFM: The Versioning Trap :)</h3><p>Initially, I was referencing older documentation. In version 1.x of the Slack action, parameters like the webhook URL and type were passed as environment variables under the env: key.</p><p>However, v2.0.0 modernized this approach. The maintainers moved these variables into the with: block. If you try to use env: with version 2, the action will fail and complain about missing inputs. Always check the README for the specific tag version you are pulling!</p><h3>2. The Missing Quote Mystery</h3><p>While customizing the JSON payload to include more dynamic GitHub variables (like run IDs and commit hashes), I accidentally deleted a single closing double quote at the end of my markdown text block.</p><p>This triggered the following pipeline error:</p><pre>SlackError: Invalid input! Failed to parse contents of the provided payload<br>    at Content.getContentPayload (file:///.../src/content.js:93:1)</pre><p><strong>The lesson:</strong> Even when you use the YAML multi-line string indicator ( | ), the payload inside must still be strictly valid JSON. A single missing quote or rogue trailing comma will break the parser. If you ever want to get fancy with your Slack messages, I highly recommend building them in the <a href="https://app.slack.com/block-kit-builder">Slack Block Kit Builder</a> first to validate your JSON before pasting it into your action.</p><h3>Wrapping Up</h3><p>With the action successfully running on pushes and PRs, I now have instant visibility into the main branch activity. It’s a small bit of automation that yields massive communication benefits.</p><p>Give it a try in your own repository, test out different variables in your payload, and enjoy the satisfaction of seeing those automated Slack pings roll in!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=353e3393d007" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CloudFormation Redefined My Architecture]]></title>
            <link>https://medium.com/@pails-topper.3j/how-cloudformation-redefined-my-architecture-mental-model-c7924b3ae72c?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7924b3ae72c</guid>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[cloud-automation]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 23:20:04 GMT</pubDate>
            <atom:updated>2026-04-08T23:48:56.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rN9Zr7PxdIaQGDB44DoojQ.png" /></figure><p>In the world of cloud engineering, there is a distinct click that happens when you move from the AWS Management Console to Infrastructure as Code (IaC). For a long time, building in the cloud felt like manual labor. Clicking through menus, checking boxes, and hoping you didn’t miss a security group rule.</p><p>Adopting <strong>AWS CloudFormation</strong> is a fundamental shift in how I conceptualize, secure, and scale infrastructure. Moving to a declarative model turns architecture from a to-do list into a blueprinted reality.</p><p>The manual ClickOps version can be found <a href="https://medium.com/@pails-topper.3j/engineering-secure-access-with-a-multi-tier-bastion-architecture-3fd858054dd9">here</a>.<br><a href="https://medium.com/@pails-topper.3j/engineering-secure-access-with-a-multi-tier-bastion-architecture-3fd858054dd9">Engineering Secure Access with a Multi-Tier Bastion Architecture</a></p><h3>From “How” to “What”: The Declarative Shift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gqM3gzph1ucuzbKHr4s0Q.png" /></figure><p>The biggest hurdle in moving away from manual configuration is unlearning <strong>imperative</strong> thinking. In a manual setup, you think in steps: Create the VPC, then create the subnets, then attach the gateway…</p><p>CloudFormation demands a <strong>declarative</strong> approach. You define the end state, the “what”, and let AWS handle the “how.”</p><p>In my current multi-tier VPC project, I don’t manage the order of operations. I simply declare that PublicSubnet1Abelongs to MyVPC, and CloudFormation orchestrates the dependencies.</p><h3>Anatomy of a Robust Multi-Tier Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4TkNLtf12S9_FJsMS0olQ.png" /></figure><p>Using my recent vpc.yaml as a reference, we can see how this code-first approach builds a production-ready environment:</p><ul><li><strong>The Foundation:</strong> The VPC is defined with a 172.16.0.0/16 CIDR block. Codifying this ensures that every deployment—whether for testing or production—is identical and free from &quot;configuration drift.&quot;</li><li><strong>Networking &amp; Connectivity:</strong> The template explicitly defines an <strong>Internet Gateway (IGW)</strong> and a <strong>Public Route Table</strong>. By associating specific subnets like PublicSubnet1A and PublicSubnet1B with these resources, the network topology is documented in plain text.</li><li><strong>Tiered Segmentation:</strong> The architecture uses three distinct layers: Public (for the Bastion), App (for logic), and Data (for storage).</li></ul><h3>The Three Pillars of Modern Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAgkslSg6htxWyhGevrSlg.png" /></figure><p>When evaluating any AWS service like CloudFormation, the focus should remain on the three pillars that define professional-grade architecture.</p><h4>High Availability</h4><p>By using functions like !GetAZs, the template automatically distributes resources across multiple <strong>Availability Zones (AZs)</strong>. This ensures that if one zone fails, the application remains operational.</p><h4>Scaling</h4><p>CloudFormation supports <strong>horizontal scaling</strong> by allowing you to deploy identical stacks across regions instantly. It also simplifies <strong>vertical scaling</strong> (changing instance types, such as from t3.micro) through simple parameter updates in the YAML file.</p><h4>Cost Efficiency</h4><p>IaC is inherently cost-efficient because it prevents orphaned resources. You can tear down an entire environment at the end of a project and recreate it perfectly the next morning, ensuring you only pay for what you are actively using.</p><h3>Security as a Tiered Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHlpl11yWQMHjYyxqEOuMw.png" /></figure><p>For anyone pursuing a path in <strong>Cloud Security</strong>, CloudFormation is the ultimate gatekeeper. In this project, security isn’t just an add-on; it’s baked into the resource definitions:</p><ul><li><strong>The Bastion Host:</strong> A jump box is deployed into the public subnet to provide a single, secure entry point.</li><li><strong>Security Group Referencing:</strong> Instead of opening ports to wide IP ranges, I use <strong>Security Group Referencing</strong>. The application instances in the private subnets <em>only</em> accept traffic if it originates from the BastionSG.</li><li><strong>Perimeter Control:</strong> Management ports like SSH (Port 22) are restricted to a specific IP address (65.35.126.205/32), significantly reducing the attack surface.</li></ul><h3>The Conclusion: A New Way to Build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slvCVu2SggXvri1KcPIRKQ.png" /></figure><p>Transitioning to CloudFormation is about more than just writing YAML. It’s about moving from being a technician who manages components to an architect who manages systems. It provides the predictability needed for complex environments and the security required for modern cloud roles.</p><p>By treating infrastructure as code, I’m not just building a VPC. I’m building a repeatable, secure, and scalable framework for everything that comes next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PQemGMKwk2d4hSguQF6zg.png" /></figure><p>As I look at the expansive diagram detailing my completed, multi-tier VPC architecture , with its resilient Multi-AZ configuration and automated scaling, a deep sense of pride fills me. Creating the codified framework represents a massive personal and professional milestone. This file isn’t just a blueprint. It’s the engine driving my decisive move away from a world of manual ClickOps, where ephemeral configurations are hard to reproduce and optimize, to a future of declarative Automation. Every optimized instance, every adaptive scaling group, and every security tier is now defined precisely in that code, transforming my role from managing point-solutions to engineering the robust frameworks essential for my future growth. Here is the full file to review:</p><pre># Created By: Rob<br># Create Date: 4/6/2026<br># Version 2.1<br># Updated By         Date          Notes<br># Rob                4/6/2026      Added AZ 2 public and private subnets<br># Rob                4/6/2026     Added Private Subnets AZ 2<br># Rob                4/7/2026     Added IGW, Public Route Table and Routes<br># Rob                4/7/2026     Added AZ 2 subnets and route tables<br># Rob                4/7/2026     Added Private Subnets AZ 2 and Route Table Associations<br># Rob                4/8/2026     Added Bastion Host EC2 and SG - new git branch test<br># Rob                4/8/2026     Added App Instances and SG&#39;s in the private subnets<br><br><br>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: &quot;CloudFormation with VPC&quot;<br><br>Resources: <br>#My VPC<br>  MyVPC: <br>    Type: &#39;AWS::EC2::VPC&#39;<br>    Properties: <br>      CidrBlock: &#39;172.16.0.0/16&#39;<br>      EnableDnsSupport: true<br>      EnableDnsHostnames: true<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC <br><br>#Public Subnet is AZ 1  <br>  PublicSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.1.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1A<br><br> #App Private Subnet in AZ 1 <br>  AppPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.2.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1A<br>  <br># Data Private Subnet in AZ 1 <br>  DataPrivateSubnet1A:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.3.0/24&#39;<br>      AvailabilityZone: !Select [0, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1A<br><br># Public Subnet in AZ 2             <br>  PublicSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.4.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      MapPublicIpOnLaunch: true<br>      Tags:<br>        - Key: Name<br>          Value: PublicSubnet1B<br>  <br># App Private Subnet in AZ 2  <br>  AppPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.5.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: AppPrivateSubnet1B<br><br># Data Private Subnet in AZ 2  <br>  DataPrivateSubnet1B:<br>    Type: &#39;AWS::EC2::Subnet&#39;<br>    Properties: <br>      VpcId: !Ref MyVPC<br>      CidrBlock: &#39;172.16.6.0/24&#39;<br>      AvailabilityZone: !Select [1, !GetAZs &#39;&#39;]<br>      Tags:<br>        - Key: Name<br>          Value: DataPrivateSubnet1B<br><br>  # Create Internet Gateway<br>  InternetGateway:<br>    Type: AWS::EC2::InternetGateway<br>    Properties:<br>      Tags:<br>        - Key: Name<br>          Value: MyVPC-IGW<br><br>  # Attach the Internet Gateway to MyVPC<br>  AttachGateway:<br>    Type: AWS::EC2::VPCGatewayAttachment<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      InternetGatewayId: !Ref InternetGateway<br><br>  # Public Route Tables<br>  PublicRouteTable:<br>    Type: AWS::EC2::RouteTable<br>    Properties:<br>      VpcId: !Ref MyVPC<br>      Tags:<br>        - Key: Name<br>          Value: PublicRouteTable<br><br>  # Public Routes<br>  PublicRoute:<br>    Type: AWS::EC2::Route<br>    DependsOn: AttachGateway<br>    Properties:<br>      RouteTableId: !Ref PublicRouteTable<br>      DestinationCidrBlock: 0.0.0.0/0<br>      GatewayId: !Ref InternetGateway<br><br>  # Public Subnet 1A Route Table Association<br>  PublicSubnet1ARouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1A<br>      RouteTableId: !Ref PublicRouteTable<br><br>  # Public Subnet 1B Route Table Association<br>  PublicSubnet1BRouteTableAssociation:<br>    Type: AWS::EC2::SubnetRouteTableAssociation<br>    Properties: <br>      SubnetId: !Ref PublicSubnet1B<br>      RouteTableId: !Ref PublicRouteTable<br><br>  # Bastion Host EC2<br>  BastionHost:<br>    Type: &#39;AWS::EC2::Instance&#39;<br>    Properties:<br>      InstanceType: t3.micro<br>      KeyName: RobBastion<br>      ImageId: ami-0ea87431b78a82070<br>      SubnetId: !Ref PublicSubnet1A<br>      SecurityGroupIds:<br>         - !Ref BastionSG<br>      Tags:<br>        - Key: Name<br>          Value: BastionHost<br><br>  # Bastion Security Group<br>  BastionSG:<br>    Type: &#39;AWS::EC2::SecurityGroup&#39;<br>    Properties:<br>      GroupDescription: &#39;Enable SSH access&#39;<br>      VpcId: !Ref MyVPC<br>      SecurityGroupIngress:<br>        - IpProtocol: tcp<br>          FromPort: 22<br>          ToPort: 22<br>          CidrIp: Masked/32<br><br>  # AppInstance1A<br>  AppInstance1A:<br>    Type: &#39;AWS::EC2::Instance&#39;<br>    Properties:<br>      InstanceType: t3.micro<br>      KeyName: RobBastion<br>      ImageId: ami-0ea87431b78a82070<br>      SubnetId: !Ref AppPrivateSubnet1A<br>      SecurityGroupIds:<br>        - !Ref AppInstance1ASG<br>      Tags:<br>        - Key: Name<br>          Value: App1A<br><br>  # AppInstance1B<br>  AppInstance1B:<br>    Type: &#39;AWS::EC2::Instance&#39;<br>    Properties:<br>      InstanceType: t3.micro<br>      KeyName: RobBastion<br>      ImageId: ami-0ea87431b78a82070<br>      SubnetId: !Ref AppPrivateSubnet1B<br>      SecurityGroupIds:<br>        - !Ref AppInstance1BSG<br>      Tags:<br>        - Key: Name<br>          Value: App1B<br>  <br>  # AppInstance1ASG<br>  AppInstance1ASG:<br>    Type: &#39;AWS::EC2::SecurityGroup&#39;<br>    Properties:<br>      GroupDescription: &#39;App Instance 1A Security Group - SSH from Bastion Only&#39;<br>      VpcId: !Ref MyVPC<br>      SecurityGroupIngress:<br>        - IpProtocol: tcp<br>          FromPort: 22<br>          ToPort: 22<br>          SourceSecurityGroupId: !Ref BastionSG<br>  <br>  # AppInstance1BSG<br>  AppInstance1BSG:<br>    Type: &#39;AWS::EC2::SecurityGroup&#39;<br>    Properties:<br>      GroupDescription: &#39;App Instance 1B Security Group - ICMP Access only from AppInstance1ASG&#39;<br>      VpcId: !Ref MyVPC<br>      SecurityGroupIngress:<br>        - IpProtocol: icmp<br>          FromPort: -1<br>          ToPort: -1<br>          SourceSecurityGroupId: !Ref AppInstance1ASG</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7924b3ae72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering Secure Access with a Multi-Tier Bastion Architecture]]></title>
            <link>https://medium.com/@pails-topper.3j/engineering-secure-access-with-a-multi-tier-bastion-architecture-3fd858054dd9?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd858054dd9</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[file-permission]]></category>
            <category><![CDATA[aws-networking]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-security-group]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 15:20:42 GMT</pubDate>
            <atom:updated>2026-04-05T15:20:42.985Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern cloud architecture, Public and Private aren’t just labels, they are the boundaries that keep your data safe. One of the most effective ways to manage private instances without exposing them to the open web is through a <strong>Bastion Host</strong>.</p><p>This project explores how to navigate a multi-tier environment, jumping from a public entry point to an isolated private server, and finally verifying internal connectivity between Availability Zones (AZs) using ICMP.</p><h3>The Real-World Significance</h3><p>In professional cloud engineering, this architecture is vital for several reasons:</p><ul><li><strong>Attack Surface Reduction:</strong> By placing application and database servers in private subnets with no public IP addresses, they become invisible to automated internet scanners and botnets.</li><li><strong>Centralized Access Control:</strong> The Bastion Host acts as a single, hardened point of entry. Security teams can focus their monitoring and auditing efforts on this one instance rather than dozens of scattered servers.</li><li><strong>Blast Radius Control:</strong> By using security group chaining, even if a Bastion is compromised, the attacker is still restricted by the specific permissions defined between the Bastion and the internal tiers.</li></ul><h3>Technical Setup and Methodology</h3><p>This project involved a three-tier deployment in the us-east-1 region, focusing on strict isolation and the principle of least privilege.</p><h4>1. The Networking Foundation</h4><p>I utilized a VPC with a 10.0.0.0/16 CIDR block, carved into specific segments:</p><ul><li><strong>Public Subnet:</strong> Hosted the Bastion Host. This is the only subnet with an entry in the route table pointing to the Internet Gateway.</li><li><strong>Private Subnet AZ1:</strong> Hosted the primary App Server.</li><li><strong>Private Subnet AZ2:</strong> Hosted a secondary App Server to verify cross-zone internal communication.</li></ul><h4>2. Security Group Chaining (The Keycard System)</h4><p>Instead of allowing SSH from any IP address, I configured the security groups for the App Servers to accept traffic only from the Security Group ID of the Bastion Host. This ensures that only the specific Bastion instance can ever initiate a connection, regardless of what its IP might be.</p><h3>Phase 1: Provisioning the Fleet</h3><p>I launched three EC2 instances to represent a 3-tier environment. I verified that all three were in a “Running” state before moving to the configuration phase.</p><ul><li><strong>Bastion Host:</strong> Public-facing gateway.</li><li><strong>App Server AZ1:</strong> Private, allowing SSH only from the Bastion.</li><li><strong>App Server AZ2:</strong> Private, allowing ICMP (Ping) only from App Server AZ1.</li></ul><h3>Phase 2: Key Preparation and the First Jump</h3><p>AWS requires private keys to be handled with strict permissions. I used the command <strong>chmod 400</strong> on my .pem file to restrict access so only the owner has read permissions. Without this, AWS will reject the key as being too “open” and insecure.</p><p>With the key secured, I initiated the first jump by SSHing from my local terminal into the Bastion Host using its public IPv4 address.</p><h3>Phase 3: Moving Deep into the Private Subnet</h3><p>To reach the App Server in AZ1, the Bastion needed my private key for authentication. I used <strong>Secure Copy (SCP)</strong> to move the key file from my local machine to the Bastion.</p><p>Once the key was present on the Bastion, I performed the second jump. I grabbed the private IP of App Server AZ1 and established the SSH connection. At this stage, I was successfully operating inside a private subnet with no direct internet access.</p><h3>Phase 4: Verifying Internal Connectivity (The ICMP Test)</h3><p>The final task was to prove that App Server AZ1 could talk to App Server AZ2. This is crucial for architectures where servers in different zones must communicate without crossing the public internet.</p><p>I retrieved the private IP for App Server AZ2 and ran a ping test from the terminal of App Server AZ1. Because the security group for AZ2 was specifically configured to allow ICMP traffic from AZ1, the packets traveled across the internal AWS network with extremely low latency.</p><h3>Phase 5: Clean Up and Cost Management</h3><p>In the cloud, fiscal responsibility is part of the job. Once the verification was complete and the architecture was proven, I terminated all instances to ensure no unnecessary costs were incurred.</p><h3>Skills Demonstrated</h3><ul><li><strong>VPC Design:</strong> Implementing public and private subnetting with appropriate routing via an Internet Gateway.</li><li><strong>Linux Administration:</strong> Managing file permissions, navigating remote shells, and using SCP for secure file transfers.</li><li><strong>Network Security:</strong> Configuring stateful firewalls (Security Groups) to enforce the principle of least privilege through chaining.</li><li><strong>Infrastructure Verification:</strong> Using standard networking tools to confirm reachability and low-latency internal communication between Availability Zones.</li></ul><p>This project highlights the move from basic cloud hosting to professional cloud engineering, where security and isolation are the foundation of every design decision. Screenshots of each step are below.</p><h3>Create the EC2 Instances</h3><h3>Bastion Host (Public Subnet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSfqSQQXKgWAIXRu6kUnTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*2jdgMnMC6hQK2VXOuMtvdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*nn2CyjzCKSxK1CBl3w7MGA.png" /></figure><h3>EC2 App Server in AZ 1 (Private Subnet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*W1UqqMftKt-yhDG4mpp9XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*FpHqe38XeApbZXhxlVf9OA.png" /></figure><p>SSH allowed from the Bastion Security Group only</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ps-wM3MSOjYSrtIaMZ98bw.png" /></figure><h3>EC2 App Server in AZ 2 (Private Subnet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*gLZlHt0sWtPwC85GD1MUkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ONCUlEbZPmja431At8F6cQ.png" /></figure><p>Allow pings from the EC2 App Server in AZ1 only</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q3ql9EFGI_doKgm4UZc7A.png" /></figure><h3>Verify all three EC2 are Running</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODtPZnvZ-O73QY6KHJYnHw.png" /></figure><h3>Check the current permissions on the key file</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*bgZtAzivnSSeVNAPSjQ6DA.png" /><figcaption>Key file is read-only for the Owner. No access for Groups or Others.</figcaption></figure><h3>SSH into the Bastion Host</h3><p>Copy the public IPv4 address for the bastion and create the tunnel in the Terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*ndyFBXRL4ai5WND3DciNig.png" /></figure><h3>Copy the key file to the Bastion Host</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*zNy5msde-JjVSgoIgP4Sag.png" /></figure><h3>SSH into the EC2 App Server in AZ1</h3><p>Copy the private IPv4 address for the App Server in AZ1</p><p>Verify the ky file is now in the Bastion</p><p>SSH into the App Server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*1gMbqTk58_X6kcykVtdp2g.png" /></figure><h3>Ping the EC2 App Server in AZ2</h3><p>Get the private IPv4 address for the App Server in AZ2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*hsBzzGdKgA6gFYAlfrujHQ.png" /></figure><h3>Terminating All EC2 Instances</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UYL_zL6_0vorTTOvBYoxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*rJFgXqJO8n_0xQ6LLZPKXg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd858054dd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecture Deep Dive: Building a Resilient 3-Tier VPC for Cloud Growth Limited]]></title>
            <link>https://medium.com/@pails-topper.3j/architecture-deep-dive-building-a-resilient-3-tier-vpc-for-cloud-growth-limited-8c4288e3e36d?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4288e3e36d</guid>
            <category><![CDATA[aws-security-group]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[aws-security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 16:37:54 GMT</pubDate>
            <atom:updated>2026-04-04T14:31:36.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mvdCXQH6onKrXeQ8BIZww.png" /></figure><h3>The Foundation: VPC and Subnet Strategy</h3><p>Building the environment on a primary VPC with a CIDR block of 10.0.0.0/16 was a strategic decision. This range provides 65,536 available IP addresses. In a large-scale enterprise environment, having this much overhead is critical for adding secondary services later, such as management VPCs, logging subnets, or specialized containers, without needing to re-architect the entire network.</p><h3>High Availability through Regional Distribution</h3><p>I leveraged the Amazon Global Infrastructure by splitting the architecture across two Availability Zones: us-east-1a and us-east-1b. By doing this, we are protected against a physical failure at any single data center. If one zone experiences a power outage or hardware failure, the Application Load Balancer immediately shifts traffic to the healthy resources in the second zone.</p><h3>Subnet Segmentation and IP Allocation</h3><p>I assigned each subnet a /24 CIDR block. While a /24 provides 256 addresses, it is important to remember that AWS reserves five IP addresses in every subnet for networking tasks like DNS, the VPC router, and the network broadcast address. This leaves us with 251 usable IPs per tier, per zone.</p><ul><li><strong>Public Subnets:</strong> These act as the ingress and egress points. They are the only subnets with a route to the Internet Gateway. By hosting the Application Load Balancer and NAT Gateways here, we create a secure perimeter.</li><li><strong>Private Web and App Subnets:</strong> In a standard setup, web servers are often public. I chose to move them into private subnets to hide them from direct internet scans. They communicate with the internet only through the Load Balancer (inbound) and the NAT Gateway (outbound).</li><li><strong>Private Data Subnets:</strong> These are the most protected areas of the network. They have no direct path to the public internet and are strictly isolated to allow only database traffic from the application tier.</li></ul><h3>The Defense-in-Depth Model</h3><p>A single layer of security is never enough for sensitive data. I implemented a layered approach that provides redundancy in our defense.</p><h3>Security Groups: The Stateful Guard</h3><p>Security Groups act as an instance-level firewall. They are stateful, meaning if an inbound request is allowed on port 443, the return traffic is automatically allowed back out, regardless of outbound rules. This makes them easier to manage than stateless firewalls.</p><p>I used a technique called security group chaining. Instead of allowing traffic from an IP range, the App Security Group is configured to allow traffic only if it originates from the Web Security Group ID. This ensures that even if a server within the VPC is compromised, a hacker cannot easily move laterally to the database because their traffic wouldn’t carry the correct security group identity.</p><h3>The Stateless Control</h3><p>Network Access Control Lists provide a second layer of security at the subnet boundary. Unlike Security Groups, NACLs are stateless, meaning we must explicitly define rules for both inbound and outbound traffic.</p><p>I used NACLs as a coarse filter to block known high-risk ports globally. For example, while a Security Group might allow SSH for a specific admin IP, the NACL on the database subnet can be configured to block port 22 for the entire subnet. This ensures that even an internal mistake cannot accidentally expose the database tier to administrative ports.</p><h3>Database Selection: Why Amazon Aurora?</h3><p>The decision to use Amazon Aurora instead of standard RDS MySQL was driven by the requirements for high availability and performance.</p><h3>Availability and Resilience</h3><p>Standard RDS uses a primary instance and a synchronous standby instance in a different zone. If the primary fails, AWS must switch the DNS record to the standby, a process that can take up to two minutes. Aurora, however, uses a shared storage volume that is replicated six times across three Availability Zones. This allows for nearly instantaneous failover, often in under 30 seconds, because the data is already present in all zones.</p><h3>Scalable Performance</h3><p>Aurora is designed for cloud-native scaling. It can support up to 15 read replicas, and these replicas share the same underlying storage as the primary instance. This significantly reduces replication lag compared to standard RDS, where each replica must maintain its own copy of the data. As Cloud Growth Limited grows, we can scale out read capacity with minimal impact on performance.</p><h3>Cost-Effectiveness through Storage Optimization</h3><p>In standard RDS, you pay for the storage you provision, even if you don’t use it all. Aurora uses a pay-as-you-go storage model. It starts small and grows automatically in 10GB increments up to 128TB. This ensures we are only paying for the data we actually store, which is highly cost-effective for a growing application.</p><h3>Intelligent Routing and Connectivity</h3><p>Managing how data leaves and enters the VPC is just as important as where it is stored.</p><h3>Internet Gateway (IGW)</h3><p>The IGW provides a target in the VPC route tables for internet-bound traffic. It is a horizontally scaled, redundant, and highly available VPC component that allows communication between instances in your VPC and the internet.</p><h3>NAT Gateway: Managed Egress</h3><p>For the private instances to download security patches or communicate with external APIs, they need a way to reach the internet without being reachable from it. I chose a NAT Gateway over a NAT Instance because it is a managed service that scales automatically and requires no maintenance.</p><p>I deployed one NAT Gateway per Availability Zone. While this doubles the hourly cost of the gateways, it is a production requirement for high availability. If we relied on a single gateway and that zone went down, the entire application’s ability to communicate with the outside world would be severed. Furthermore, this avoids cross-zone data transfer charges, which can often be more expensive than the hourly cost of a second gateway.</p><h3><strong>Route Tables</strong></h3><p>To ensure high availability and proper traffic flow for Cloud Growth Limited, the route tables are configured to distinguish between traffic staying inside the network and traffic heading out to the internet.</p><p>In a production-ready environment, we use three distinct route tables to manage our two Availability Zones (AZs) and their respective NAT Gateways.</p><h3>1. The Public Route Table</h3><p>This table is associated with both public subnets (10.0.1.0/24 and 10.0.11.0/24). It allows the Application Load Balancer and NAT Gateways to communicate with the internet.</p><ul><li><strong>Destination: 10.0.0.0/16 | Target: Local</strong> This is the default route that allows all subnets within the VPC to talk to each other.</li><li><strong>Destination: 0.0.0.0/0 | Target: Internet Gateway (IGW-id)</strong> This “quad-zero” route sends any traffic not destined for the internal network out to the internet through the Internet Gateway.</li></ul><h3>2. The Private Route Table (Availability Zone 1a)</h3><p>This table is associated with the private web, app, and data subnets in the first AZ (10.0.2.0/24 and 10.0.3.0/24).</p><ul><li><strong>Destination: 10.0.0.0/16 | Target: Local</strong> Enables internal communication with resources in any other subnet or AZ within the VPC.</li><li><strong>Destination: 0.0.0.0/0 | Target: NAT Gateway A (nat-1a-id)</strong> Instead of an Internet Gateway, these private subnets point to the NAT Gateway located in the public subnet of AZ 1a. This allows them to pull updates or reach external APIs securely without being directly exposed to the internet.</li></ul><h3>3. The Private Route Table (Availability Zone 1b)</h3><p>This table is associated with the private web, app, and data subnets in the second AZ (10.0.12.0/24 and 10.0.13.0/24).</p><ul><li><strong>Destination: 10.0.0.0/16 | Target: Local</strong> Provides the same internal connectivity as the other tables.</li><li><strong>Destination: 0.0.0.0/0 | Target: NAT Gateway B (nat-1b-id)</strong> To maintain high availability, these subnets point to the NAT Gateway located in their own AZ (1b). This ensures that if the first AZ goes down, the resources in this zone still have an active path to the internet.</li></ul><p>Here are my Route Tables</p><p>Public Subnets</p><p>Destination Target<br>0.0.0.0/0____IGW<br>10.0.0.0/16__Local IPs</p><p>Web Subnets<br>Destination Target<br>0.0.0.0/0___NAT<br>10.0.0.0/16_Local IPs</p><p>App Subnets<br>Destination Target<br>0.0.0.0/0___NAT<br>10.0.0.0/16_Local IPs</p><p>DB Subnets<br>Destination Target<br>0.0.0.0/0___None<br>10.0.0.0/16_Local IPs<br> — — DB connection outside of the VPC is not required. I’m using a cloud native DB. If I decided to use SQL Server or Oracle, a connection to the NAT is needed, and not the Internet Gateway, to download patches/upgrades.</p><h3>Scalability and Availability Summary</h3><h3>Application Load Balancer (ALB)</h3><p>The ALB is the primary entry point. It is highly available by design and scales its capacity automatically based on the volume of incoming traffic. By terminating SSL/TLS at the ALB, we reduce the CPU load on our backend web servers, making the entire system more efficient.</p><h3>Amazon Aurora Storage</h3><p>Aurora’s storage layer is separate from the compute layer. This means if a database instance fails, the data remains safe and available to a new instance immediately. The self-healing nature of the storage volume, which automatically scans and repairs data blocks, provides a level of durability that standard databases cannot match.</p><h3>Final Rationale</h3><p>This architecture was designed to meet a strict production standard. By isolating every tier in private subnets and using a combination of stateful and stateless firewalls, I have ensured that the most sensitive assets of Cloud Growth Limited are protected by multiple layers of defense. The choice of managed, highly available services like Aurora and the ALB ensures that the system is not only secure but also resilient and prepared for rapid growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4288e3e36d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Permissions Using CLI]]></title>
            <link>https://medium.com/@pails-topper.3j/file-permissions-using-cli-054782752cfc?source=rss-132100fc896b------2</link>
            <guid isPermaLink="false">https://medium.com/p/054782752cfc</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[linux-commands]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[linux-file-permission]]></category>
            <dc:creator><![CDATA[Rob Satnarain]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 21:55:45 GMT</pubDate>
            <atom:updated>2026-03-29T21:55:45.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJZa-RbTiETVT2qJcr1kWg.png" /></figure><h3>S3 and File Permissions After Connecting to the EC2</h3><p>Alright, let’s talk about file permissions. Usually, when we think of file permissions, we think of the standard chmod and ls -l kind of stuff. We&#39;re on a Linux box, we&#39;ve got a file, and we need to lock it down or open it up. In other words, make it read only, writable, or executable by the user, groups, or others.</p><p>The image above is a perfect example of that. You can see me messing around with a text file, class-notes.txt, on an EC2 instance. I&#39;m checking its permissions with ls-l, changing them with various chmod commands, and then checking them again to make sure they&#39;ve stuck.</p><ul><li>ls -l class-notes.txt: Here, the file is writable by the user, but not by the group or others. The rw- indicates read/write for the user, and r- - for the others. The filename class-notes.txt is highlighted in green, which is a cool touch.</li><li>chmod 444 class-notes.txt: I&#39;m changing the file to be read only. The user, group, and others can all read the file, but nobody can write to it. A good move for something like public documentation.</li><li>chmod 644 class-notes.txt: The user can read and write, while everyone else can only read. It&#39;s the standard for files that should be readable by all but only editable by the owner.</li><li>chmod 744 class-notes.txt: The user gets full access—read, write, and execute. The group and others, however, are restricted to read-only access. The green highlight is back, signaling that the user now has full permissions.</li></ul><p>chmod u+x to make it executable for the user, chmod g+x for the group, chmod a-w to remove write permission from everyone, and so on. We use these commands to make sure our scripts, configuration files, and data are secure.</p><p><strong>But here’s where it gets interesting.</strong></p><p>What happens when your files aren’t on a server, but are sitting in an S3 bucket? S3 isn’t a traditional file system, and you can’t just ssh in and start running chmod commands.</p><p>So, how do you handle permissions?</p><h3>The AWS CLI: Your Remote Control for S3</h3><p>This is where the AWS Command Line Interface (CLI) becomes your new best friend. It’s the tool that bridges the gap between your local command line and the AWS cloud.</p><p>The S3 commands in the AWS CLI give you granular control over your objects and buckets, and that includes managing access. Managing files individually becomes quite the task when there are hundreds or thousands needing security review. There has to be a better way.</p><p>The most common way to manage permissions in S3 are with Bucket Policies.</p><h3>Bucket Policies</h3><p>A Bucket Policy is a JSON-based policy that attaches directly to your S3 bucket. Think of it as a set of rules for the entire bucket. You can use it to:</p><ul><li>You can allow your colleague to read objects in a certain folder, or let another AWS account upload files.</li><li>You can require all uploads to use server-side encryption or block all public access to the bucket.</li><li>You can set rules based on the source IP address, the time of day, or the specific object tags.</li></ul><p>Here’s an example of how you can use the AWS CLI to apply a bucket policy:</p><p>Bash</p><pre># To apply a bucket policy from a JSON file<br>aws s3api put-bucket-policy --bucket robs3-test --policy file://policy.json</pre><p>The policy.json file would contain your specific rules, written in the standard AWS IAM policy language.</p><p>This is my attempt at creating a policy for my user to allow all actions. Block all others that are not within the range of IP Addresses used by my workplace. All of this is hypothetical, of course.</p><pre>{<br>    &quot;Version&quot;: &quot;2026-03-29&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;AllowEC2UserFullAccess&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;arn:aws:iam::123456789012:role/ec2-s3-all&quot;<br>            },<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::robs3-test&quot;,<br>                &quot;arn:aws:s3:::robs3-test/*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;RestrictToSpecificIP&quot;,<br>            &quot;Effect&quot;: &quot;Deny&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::robs3-test&quot;,<br>                &quot;arn:aws:s3:::robs3-test/*&quot;<br>            ],<br>            &quot;Condition&quot;: {<br>                &quot;NotIpAddress&quot;: {<br>                    &quot;aws:SourceIp&quot;: &quot;203.0.113.0/24&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><h4><strong>What are your favorite AWS CLI tricks for managing S3 permissions? Share them in the comments below!</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=054782752cfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>