<?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 Roshan Poudel on Medium]]></title>
        <description><![CDATA[Stories by Roshan Poudel on Medium]]></description>
        <link>https://medium.com/@roshanpoudel.me?source=rss-1998c448e05c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xWK9GE6aa-y3BOGD</url>
            <title>Stories by Roshan Poudel on Medium</title>
            <link>https://medium.com/@roshanpoudel.me?source=rss-1998c448e05c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:00:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roshanpoudel.me/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[Chaos Engineering on a Budget with AWS Fault Injection Service]]></title>
            <link>https://medium.com/@roshanpoudel.me/chaos-engineering-on-a-budget-with-aws-fault-injection-service-94d1c9f8b2c1?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d1c9f8b2c1</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[chaos-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 08:00:08 GMT</pubDate>
            <atom:updated>2026-11-14T08:00:08.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHIbaRK4GEljL0W7_Z9uQA.png" /></figure><p>You don’t need a dedicated game-day platform or a fleet of AWS accounts to start practising chaos engineering. One account, a small Auto Scaling group behind an Application Load Balancer, and AWS Fault Injection Service (FIS) are enough to stop instances and max out CPU on purpose. Then you can see whether your alarms, health checks and scaling policies behave the way you think they do.</p><p>Everything in this post is built with Terraform, and a stop condition acts as a safety net so the experiment can’t turn into a real outage.</p><h3>Why break things on purpose?</h3><p>Every Auto Scaling group is supposed to replace an instance that dies. Every target tracking policy is supposed to scale out when load climbs. Yet most of us have never watched either of those things happen under controlled conditions. We find out how they really behave on the day it matters, usually with an incident channel open.</p><p>Chaos engineering closes that gap deliberately. You write down a hypothesis, introduce a small, controlled failure, and compare what happens with what you expected. The aim is to find where your mental model of the system and its real behaviour differ, while the stakes are still low.</p><p>FIS is AWS’s managed service for exactly this. You define an <strong>experiment template</strong> (the actions to run, the resources to target, the conditions that should halt it, and an IAM role to act with), start it, and FIS carries out and logs every step. EC2 actions such as stopping instances don’t need an agent. For things like CPU stress, FIS uses AWS Systems Manager, which most operations teams already run.</p><h3>What we’re building</h3><p>The lab is deliberately small and lives in a single AWS account:</p><ul><li>A VPC with two public subnets (more on that choice below)</li><li>An Application Load Balancer (ALB) and a target group</li><li>An Auto Scaling group (ASG) of two to four small instances running a basic web server</li><li>A target tracking scaling policy based on average CPU</li><li>A CloudWatch alarm on healthy host count, which also serves as the FIS stop condition</li><li>One FIS experiment template per experiment</li></ul><p>We’ll use it to run two experiments:</p><ol><li><strong>Stop an instance.</strong> Does the ASG replace it, and do users notice?</li><li><strong>Stress the CPU.</strong> Does the scaling policy react, and how long does it take?</li></ol><h3>Keeping costs down</h3><p>The ALB is the largest fixed cost in this lab, followed by the EC2 instances. The cheapest approach is to build it, run your experiments in one sitting, and then run terraform destroy. FIS charges per action-minute, so a handful of short experiments costs very little. Still, check current FIS and ALB pricing for your region before you start.</p><h3>Why public subnets?</h3><p>The CPU stress experiment uses SSM Run Command and installs stress-ng at runtime, so the instances need outbound internet access or VPC endpoints. NAT gateways and interface endpoints are billed by the hour. For a throwaway lab, public subnets with a security group that only accepts traffic from the ALB are the cheaper trade-off. Please don’t carry this pattern into production.</p><h3>Prerequisites</h3><p>Before you start, make sure you have:</p><ul><li>An AWS account and Terraform installed</li><li>Instances running the SSM Agent (Amazon Linux 2023 ships with it), with an instance profile that includes the AmazonSSMManagedInstanceCore managed policy</li><li>Permission to create IAM roles, Auto Scaling groups, load balancers and FIS experiment templates</li></ul><h3>Step 1: Build the steady-state infrastructure</h3><p>Every chaos experiment starts with a definition of “healthy”. For this lab, healthy means at least one healthy target behind the ALB and users getting HTTP 200 responses.</p><p>Two settings on the Auto Scaling group do most of the work. health_check_type = &quot;ELB&quot; tells the ASG to trust the load balancer’s view of whether an instance is healthy, rather than relying on EC2 status checks alone. The Environment tag, propagated to every instance at launch, is what lets FIS target lab instances and nothing else.</p><pre>resource &quot;aws_autoscaling_group&quot; &quot;web&quot; {<br>  name                      = &quot;chaos-lab-asg&quot;<br>  min_size                  = 2<br>  max_size                  = 4<br>  desired_capacity          = 2<br>  vpc_zone_identifier       = var.public_subnet_ids<br>  target_group_arns         = [aws_lb_target_group.web.arn]<br>  health_check_type         = &quot;ELB&quot;<br>  health_check_grace_period = 120</pre><pre>  launch_template {<br>    id      = aws_launch_template.web.id<br>    version = &quot;$Latest&quot;<br>  }</pre><pre>  tag {<br>    key                 = &quot;Environment&quot;<br>    value               = &quot;chaos-lab&quot;<br>    propagate_at_launch = true<br>  }<br>}</pre><p>Next, add a target tracking policy so the CPU experiment has something to trigger:</p><pre>resource &quot;aws_autoscaling_policy&quot; &quot;cpu&quot; {<br>  name                   = &quot;cpu-target-tracking&quot;<br>  autoscaling_group_name = aws_autoscaling_group.web.name<br>  policy_type            = &quot;TargetTrackingScaling&quot;</pre><pre>  target_tracking_configuration {<br>    predefined_metric_specification {<br>      predefined_metric_type = &quot;ASGAverageCPUUtilization&quot;<br>    }<br>    target_value = 50<br>  }<br>}</pre><p>Step 2: Write the hypotheses and build the safety net</p><p>Before touching FIS, write down what you expect to happen. Here are mine:</p><ol><li><strong>Experiment 1: Stop 1 of 2 instances.</strong> The ALB stops routing traffic to it, users see no errors, and the ASG launches a replacement within a few minutes.</li><li><strong>Experiment 2: 90% CPU for 5 minutes on all instances.</strong> Average CPU rises above the 50% target, the policy scales out, and CPU drops back down.</li></ol><p>Next comes the stop condition, which is simply a CloudWatch alarm. If it enters the ALARM state while an experiment is running, FIS halts the experiment. This one trips when the target group has no healthy hosts at all, which would mean the experiment has gone further than planned.</p><pre>resource &quot;aws_cloudwatch_metric_alarm&quot; &quot;no_healthy_hosts&quot; {<br>  alarm_name          = &quot;chaos-lab-no-healthy-hosts&quot;<br>  namespace           = &quot;AWS/ApplicationELB&quot;<br>  metric_name         = &quot;HealthyHostCount&quot;<br>  statistic           = &quot;Minimum&quot;<br>  period              = 60<br>  evaluation_periods  = 1<br>  threshold           = 1<br>  comparison_operator = &quot;LessThanThreshold&quot;<br>  treat_missing_data  = &quot;notBreaching&quot;</pre><pre>  dimensions = {<br>    TargetGroup  = aws_lb_target_group.web.arn_suffix<br>    LoadBalancer = aws_lb.web.arn_suffix<br>  }<br>}</pre><h3>Step 3: Give FIS permission to act</h3><p>FIS performs actions on your behalf through an IAM role. AWS publishes managed policies for common scenarios, so you don’t need to hand-write permissions to stop instances or send SSM commands. Double-check the exact policy names in the IAM console before you apply this.</p><pre>resource &quot;aws_iam_role&quot; &quot;fis&quot; {<br>  name = &quot;chaos-lab-fis-role&quot;</pre><pre>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Effect    = &quot;Allow&quot;<br>      Principal = { Service = &quot;fis.amazonaws.com&quot; }<br>      Action    = &quot;sts:AssumeRole&quot;<br>    }]<br>  })<br>}</pre><pre>resource &quot;aws_iam_role_policy_attachment&quot; &quot;fis_ec2&quot; {<br>  role       = aws_iam_role.fis.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSFaultInjectionSimulatorEC2Access&quot;<br>}</pre><pre>resource &quot;aws_iam_role_policy_attachment&quot; &quot;fis_ssm&quot; {<br>  role       = aws_iam_role.fis.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSFaultInjectionSimulatorSSMAccess&quot;<br>}</pre><p>Managed policies are fine for a lab. For anything beyond that, replace them with a custom policy scoped to tagged resources.</p><h3>Step 4: Stop an instance (Experiment 1)</h3><pre>resource &quot;aws_fis_experiment_template&quot; &quot;stop_one&quot; {<br>  description = &quot;Stop one instance in the chaos-lab ASG&quot;<br>  role_arn    = aws_iam_role.fis.arn</pre><pre>  stop_condition {<br>    source = &quot;aws:cloudwatch:alarm&quot;<br>    value  = aws_cloudwatch_metric_alarm.no_healthy_hosts.arn<br>  }</pre><pre>  action {<br>    name      = &quot;stop-one-instance&quot;<br>    action_id = &quot;aws:ec2:stop-instances&quot;</pre><pre>    parameter {<br>      key   = &quot;startInstancesAfterDuration&quot;<br>      value = &quot;PT10M&quot;<br>    }</pre><pre>    target {<br>      key   = &quot;Instances&quot;<br>      value = &quot;lab-instances&quot;<br>    }<br>  }</pre><pre>  target {<br>    name           = &quot;lab-instances&quot;<br>    resource_type  = &quot;aws:ec2:instance&quot;<br>    selection_mode = &quot;COUNT(1)&quot;</pre><pre>    resource_tag {<br>      key   = &quot;Environment&quot;<br>      value = &quot;chaos-lab&quot;<br>    }</pre><pre>    filter {<br>      path   = &quot;State.Name&quot;<br>      values = [&quot;running&quot;]<br>    }<br>  }</pre><pre>  tags = {<br>    Name = &quot;chaos-lab-stop-one&quot;<br>  }<br>}</pre><p>Three details are worth calling out:</p><ul><li>selection_mode = &quot;COUNT(1)&quot; targets exactly one instance, the smallest blast radius that still tells you something useful.</li><li>The tag and state filter mean only running instances tagged as lab instances are eligible.</li><li>startInstancesAfterDuration tells FIS to start the instance again after 10 minutes. In practice, the ASG will most likely have replaced it by then, and that replacement is exactly what we’re testing.</li></ul><p>Start the experiment from the console or the CLI:</p><pre>aws fis list-experiment-templates<br>aws fis start-experiment --experiment-template-id &lt;template-id&gt;<br>aws fis get-experiment --id &lt;experiment-id&gt;</pre><h3>What to watch</h3><ul><li><strong>ALB target group, Targets tab:</strong> the stopped instance turns unhealthy, then gets deregistered.</li><li><strong>ASG, Activity tab:</strong> the unhealthy instance is terminated and a replacement launches.</li><li><strong>CloudWatch:</strong> HealthyHostCount, HTTPCode_Target_5XX_Count and TargetResponseTime.</li></ul><p>To see what a user would actually experience, run a simple request loop from your laptop:</p><pre>while true; do curl -s -o /dev/null -w &#39;%{http_code} %{time_total}s &#39; http://&lt;alb-dns-name&gt;; date +%T; sleep 1; done</pre><h3>Record the timeline</h3><p>Note the time of each event as it happens. This timeline is the most useful thing the experiment produces.</p><ol><li>Experiment started:</li><li>Target marked unhealthy:</li><li>First failed request (if any):</li><li>Replacement instance launched:</li><li>Replacement healthy in the ALB:</li></ol><h3>What this experiment often reveals</h3><ul><li>The health check interval or unhealthy threshold is slower than you assumed, so traffic keeps reaching a dead target for longer than expected.</li><li>The health check grace period delays the replacement.</li><li>There’s only one instance per Availability Zone, so a single failure removes half your capacity.</li><li>An alarm you expected to fire stays silent because it’s watching the wrong metric.</li></ul><h3>Step 5: Stress the CPU (Experiment 2)</h3><p>This experiment uses the AWS-provided SSM document AWSFIS-Run-CPU-Stress, run through the aws:ssm:send-command action.</p><pre>resource &quot;aws_fis_experiment_template&quot; &quot;cpu_stress&quot; {<br>  description = &quot;Burn CPU on all chaos-lab instances&quot;<br>  role_arn    = aws_iam_role.fis.arn</pre><pre>  stop_condition {<br>    source = &quot;aws:cloudwatch:alarm&quot;<br>    value  = aws_cloudwatch_metric_alarm.no_healthy_hosts.arn<br>  }</pre><pre>  action {<br>    name      = &quot;cpu-stress&quot;<br>    action_id = &quot;aws:ssm:send-command&quot;</pre><pre>    parameter {<br>      key   = &quot;documentArn&quot;<br>      value = &quot;arn:aws:ssm:${var.region}::document/AWSFIS-Run-CPU-Stress&quot;<br>    }</pre><pre>    parameter {<br>      key   = &quot;documentParameters&quot;<br>      value = jsonencode({<br>        DurationSeconds     = &quot;300&quot;<br>        LoadPercent         = &quot;90&quot;<br>        InstallDependencies = &quot;True&quot;<br>      })<br>    }</pre><pre>    parameter {<br>      key   = &quot;duration&quot;<br>      value = &quot;PT5M&quot;<br>    }</pre><pre>    target {<br>      key   = &quot;Instances&quot;<br>      value = &quot;lab-instances&quot;<br>    }<br>  }</pre><pre>  target {<br>    name           = &quot;lab-instances&quot;<br>    resource_type  = &quot;aws:ec2:instance&quot;<br>    selection_mode = &quot;ALL&quot;</pre><pre>    resource_tag {<br>      key   = &quot;Environment&quot;<br>      value = &quot;chaos-lab&quot;<br>    }</pre><pre>    filter {<br>      path   = &quot;State.Name&quot;<br>      values = [&quot;running&quot;]<br>    }<br>  }</pre><pre>  tags = {<br>    Name = &quot;chaos-lab-cpu-stress&quot;<br>  }<br>}</pre><h3>Hypothesis versus reality</h3><p>Target tracking works through CloudWatch alarms that AWS creates and manages for you. Scale-out only happens after several consecutive data points above the target, and even then the new instance needs time to launch, boot and pass health checks. Scale-in is deliberately slower and more conservative.</p><p>So don’t be surprised if scale-out lags a few minutes behind the CPU spike. That lag is your finding. If real traffic can ramp up faster than your scaling reacts, you’ll need more baseline headroom, a lower target value, or a different policy type.</p><h3>Step 6: Clean up</h3><p>When you’re done, tear everything down:</p><pre>terraform destroy</pre><p>Then check the console to confirm the ALB, instances and any stray EBS volumes are gone. Keep the Terraform code in Git, and your next game day is a single terraform apply away.</p><h3>Lessons and gotchas</h3><ul><li><strong>Start with the smallest blast radius.</strong> Work up from COUNT(1) to PERCENT(50) to ALL, in that order.</li><li><strong>Treat stop conditions as mandatory.</strong> Build the alarm first, then the experiment.</li><li><strong>Target by tag, never by instance ID.</strong> Tag-based targets keep working as instances come and go.</li><li><strong>Remember that stopped isn’t terminated.</strong> An ASG treats a stopped instance as unhealthy and replaces it, but how quickly depends on your health check settings.</li><li><strong>Expect SSM prerequisites to bite.</strong> If the CPU stress action fails, check the SSM Agent, the instance profile and outbound network access first.</li><li><strong>Tell your team.</strong> Even in a lab, let people know what you’re doing. In real environments, run experiments during business hours with people watching.</li><li><strong>Write the hypothesis first.</strong> Otherwise you’ll find a way to rationalise whatever happens.</li></ul><h3>Where to go next</h3><ul><li>Try FIS’s pre-built scenarios, such as simulating an Availability Zone event, once you have a multi-AZ design worth testing.</li><li>Inject network latency or packet loss with the SSM-based actions, and see how your timeouts and retries hold up.</li><li>Pair experiments with SLOs: run an experiment and measure how much error budget it consumes. That’s the topic of my next post.</li><li>Turn the lab into a recurring game day, with a short written report after each run.</li></ul><h3>Conclusion</h3><p>Chaos engineering is often treated as something only large companies with dedicated reliability teams can afford. It doesn’t have to be. A small Auto Scaling group, a couple of alarms and FIS are enough to test two of the most important assumptions in any AWS architecture: that failed capacity gets replaced, and that extra load gets absorbed.</p><p>Breaking things is the easy part. The real value comes from the timeline you record and the fixes you make afterwards.</p><p><em>Have you run FIS experiments in your own account? I’d love to hear which failure surprised you most.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d1c9f8b2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use AWS S3 Locally with LocalStack (A Practical Guide for Developers)]]></title>
            <link>https://medium.com/@roshanpoudel.me/how-to-use-aws-s3-locally-with-localstack-a-practical-guide-for-developers-7b8dad16bbf1?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8dad16bbf1</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[aws-s3-bucket]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 04:46:20 GMT</pubDate>
            <atom:updated>2026-03-31T05:06:50.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yunJ20qIcTqGSnH1G6r3ZA.png" /></figure><p>If you’ve ever built an app that stores files in AWS S3, you already know the pain: testing S3 locally is… not really a thing. At least, not without help.</p><p>You either mock everything (which never feels real), or you push to AWS every time you want to test an upload. That’s slow, expensive, and honestly unnecessary.</p><p>This is where <strong>LocalStack</strong> steps in a fully local AWS cloud emulator that lets you run S3, Lambda, DynamoDB, SQS, SNS, and more right on your machine. No AWS bill. No internet required. No surprises.</p><p>In this post, I’ll walk you through how to use <strong>AWS S3 locally via LocalStack</strong> for real development work including uploads, downloads, bucket creation, and integration with your backend.</p><h3>1. Install LocalStack</h3><p>If you’re using Docker (and you should), the setup is tiny.</p><pre>services:<br>  localstack:<br>    image: localstack/localstack:3.0.2<br>    ports:<br>      - &quot;4566:4566&quot;<br>    environment:<br>      - SERVICES=s3<br>      - DEBUG=1<br>      - LOCALSTACK_HOST=localstack<br>    volumes:<br>      - &quot;/var/run/docker.sock:/var/run/docker.sock&quot;<br>      - &quot;./localstack-init:/etc/localstack/init/ready.d&quot;</pre><p>Start it:</p><pre>docker-compose up</pre><p>LocalStack will boot and expose all AWS services on port <strong>4566</strong>.</p><h3>2. Install AWS CLI (or awslocal)</h3><p>You can use the normal AWS CLI, but awslocal is something else:</p><pre>pip install awscli-local<br><br># Eventhough keys don&#39;t matter; use keys placeholder <br><br>export AWS_ACCESS_KEY_ID=test<br>export AWS_SECRET_ACCESS_KEY=test<br><br># Now you can run aws command<br><br>awslocal s3 ls</pre><h3>3. Create an S3 Bucket Locally</h3><pre>awslocal s3 mb s3://my-local-bucket<br><br># Check it<br>awslocal s3 ls</pre><p>You’ll see your bucket instantly.</p><h3>4. Upload a File to Local S3</h3><pre>echo &quot;hello world&quot; &gt; test.txt<br>awslocal s3 cp test.txt s3://my-local-bucket</pre><p>List objects:</p><pre>awslocal s3 ls s3://my-local-bucket<br><br># For Multiple Files and folders<br>awslocal s3 ls s3://my-local-bucket --recursive</pre><h3>5. Use LocalStack S3 in Your Backend</h3><p>Your backend code doesn’t need to change much. Just point boto3 client to endpoint URL</p><pre>import boto3<br>import os<br><br>def get_s3_client():<br>    return boto3.client(<br>        &quot;s3&quot;,<br>        endpoint_url=&quot;http://localhost:4566&quot;,<br>        aws_access_key_id=&quot;test&quot;,<br>        aws_secret_access_key=&quot;test&quot;,<br>        region_name=&quot;us-east-1&quot;<br>    )<br><br># Now you can upload<br><br>s3 = get_s3_client()<br>s3.upload_fileobj(file, &quot;my-local-bucket&quot;, &quot;uploads/file.pdf&quot;)<br><br># And generate presigned URLs<br><br>url = s3.generate_presigned_url(https://medium.com/%3Cbr%3E%20%20%20%20&quot;get_object&quot;,%3Cbr%3E%20%20%20%20Params=%7B&quot;Bucket&quot;:%20&quot;my-local-bucket&quot;,%20&quot;Key&quot;:%20&quot;uploads/file.pdf&quot;%7D,%3Cbr%3E%20%20%20%20ExpiresIn=3600%3Cbr%3E)</pre><p>If you’re running inside Docker, replace localhost with localstack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8dad16bbf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster Development & Deployment: Running AWS Lambda Locally with Docker]]></title>
            <link>https://medium.com/@roshanpoudel.me/faster-development-deployment-running-aws-lambda-locally-with-docker-d4694a19f64e?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4694a19f64e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 05:24:39 GMT</pubDate>
            <atom:updated>2026-03-25T05:24:39.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld3X3UsGiJRhd7d6HbXHoQ.png" /></figure><p>As a developer, there’s nothing more frustrating than the “deploy-to-test” cycle. Waiting several minutes for a CloudFormation stack to update just to find a small syntax error in your Python code is a massive productivity killer.</p><p>By running <strong>AWS Lambda on Docker locally</strong>, you can test your functions in an environment that almost perfectly mimics the AWS cloud, cutting your feedback loop down to seconds.</p><p>The Setup: A Simple Python Lambda</p><p>To get started, we’ll build a basic Lambda function that greets a user.</p><p><strong>1. The Application (</strong><strong>app.py)</strong></p><p>This script contains our handler. It looks for a name in the incoming event and returns a JSON response.</p><pre>import json<br>import os<br>def handler(event, context):<br>    # Get a name from the event or default to &quot;Stranger&quot;<br>    name = event.get(&quot;name&quot;, &quot;Stranger&quot;)<br>    <br>    message = f&quot;Hello {name}! Your Lambda is running inside a local Docker container.&quot;<br>    <br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps({<br>            &quot;message&quot;: message,<br>            &quot;environment&quot;: os.environ.get(&quot;ENV&quot;, &quot;local&quot;)<br>        })<br>    }</pre><p><strong>2. The Dockerfile</strong></p><p>We’ll use the <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-create.html">official AWS Lambda base image</a>. These images come pre-installed with the <strong>Runtime Interface Emulator (RIE)</strong>, which allows you to test your function by sending standard HTTP requests to a local endpoint.</p><pre># Use the official AWS Lambda Python 3.12 image<br>FROM public.ecr.aws/lambda/python:3.12<br><br># Copy the function code into the task root directory<br>COPY app.py ${LAMBDA_TASK_ROOT}<br><br># Set the CMD to your handler (file_name.function_name)<br>CMD [ &quot;app.handler&quot; ]</pre><p>Building and Running Your Container</p><p>With your files ready, follow these steps to see it in action:</p><p><strong>Step 1: Build the image</strong></p><p>With your files ready build your Container</p><pre>docker build -t local-lambda-test .</pre><p><strong>Step 2: Start the container</strong><br>Map port <strong>9000</strong> on your host machine to port <strong>8080</strong> (the default Lambda internal port) inside the container.</p><pre>docker run -p 9000:8080 local-lambda-test</pre><p><strong>Step 3: Trigger the function</strong><br>Since this is an emulator, you must send a <strong>POST</strong> request to a specific invocation path. Open a new terminal and run:</p><pre>curl -X POST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; \<br>-d &#39;{&quot;name&quot;: &quot;Developer&quot;}&#39;</pre><p><strong>Expected Result:</strong></p><pre>{&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;{\&quot;message\&quot;: \&quot;Hello Developer!...\&quot;, \&quot;environment\&quot;: \&quot;local\&quot;}&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI5iF10uayslpy0lg1xuuQ.png" /></figure><p><strong>Professional Tips for Local Iteration</strong></p><p>To master local Lambda development, keep these best practices in mind:</p><ul><li><strong>Avoid Rebuilding with Volumes</strong>: Don’t rebuild your image for every small code change. Instead, mount your local code directory directly into the container using the -v flag:<br>docker run -p 9000:8080 -v $(pwd):/var/task local-lambda-test.</li><li><strong>Emulate the Full Cloud</strong>: If your Lambda needs to talk to S3 or DynamoDB, use <a href="https://docs.localstack.cloud/aws/services/lambda/">LocalStack</a> to run a full mock AWS environment locally.</li><li><strong>Manage Dependencies</strong>: If you have a requirements.txt, ensure you RUN pip install it in your Dockerfile before copying your application code to speed up image build times via layer caching.</li><li><strong>Use the AWS SAM CLI</strong>: For larger projects, the AWS SAM CLI can automate this entire Docker workflow for you, including managing multiple functions and local API Gateways.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4694a19f64e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Patch Management in AWS EC2 with Systems Manager Patch Manager]]></title>
            <link>https://medium.com/@roshanpoudel.me/automating-patch-management-in-aws-ec2-with-systems-manager-patch-manager-664b9ef81f7f?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/664b9ef81f7f</guid>
            <category><![CDATA[patch-management]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 14:27:22 GMT</pubDate>
            <atom:updated>2025-09-18T14:28:59.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnbuoraZGBB3wiNKl2jl2Q.png" /><figcaption>Patch Management Architecture</figcaption></figure><p>Maintaining a secure and compliant environment in the cloud requires consistent patching. Unpatched systems expose organizations to vulnerabilities, compliance failures, and potential downtime. AWS Systems Manager Patch Manager provides a structured and automated way to manage patching across EC2 instances. By combining patch baselines, patch groups, maintenance windows, and monitoring, administrators can ensure systems remain up to date with minimal manual intervention.</p><p>This article provides a step-by-step guide for setting up patch management in AWS using Systems Manager, along with best practices and integration options for enhanced compliance and visibility.</p><h4>AWS Systems Manager Patch Manager Configuration</h4><p>AWS Systems Manager Patch Manager is the primary tool used for automating the patching process.</p><ul><li><strong>Patch Baseline</strong>: We use a default patch baseline from aws named as”AWS-DefaultPatchBaseline”, to ensure only critical and security-related patches are applied. This baseline is configured with the following attributes:</li><li><strong>Patching Frequency</strong>: Weekly patch scans and installations occur every Sunday at 1:00 AM UTC via an automated CRON expression.</li><li><strong>Patching Rules</strong>: Critical and security patches are automatically approved 7 days after release.</li><li><strong>Patch Deployment</strong>: Patches are first deployed to non-production environments, followed by production.</li><li><strong>Patch Groups</strong>: Instances are grouped using AWS Resource Groups based on tags like environment, project, and Auto Scaling Group names.</li><li><strong>Maintenance Windows</strong>: AWS Systems Manager Maintenance Windows ensure patches are applied during non-peak hours.</li></ul><p><strong>Sample Configuration</strong>:</p><pre>{<br>  &quot;PatchBaselineId&quot;: &quot;pb-123456&quot;,<br>  &quot;PatchRules&quot;: {<br>    &quot;Classification&quot;: [&quot;CriticalUpdates&quot;, &quot;SecurityUpdates&quot;],<br>    &quot;ApproveAfterDays&quot;: 7,<br>    &quot;Schedule&quot;: &quot;cron(0 1 ? * SUN *)&quot;<br>  },<br>  &quot;PatchGroups&quot;: [&quot;ProductionServers&quot;],<br>  &quot;MaintenanceWindow&quot;: &quot;mw-abc123&quot;<br>}</pre><h3>Prerequisites</h3><p>Before configuring patching in AWS, ensure that the following requirements are in place:</p><p><strong>1.SSM Agent Installed and Running</strong><br>Every EC2 instance that will be managed must have the AWS Systems Manager Agent (SSM Agent) installed and running. The agent allows Systems Manager to communicate with the instance.</p><p><strong>2. IAM Roles and Permissions</strong><br> The instances and automation workflows must have appropriate IAM roles attached. At minimum, the following AWS managed policies should be applied:</p><ul><li>AmazonEC2RoleforSSM</li><li>AmazonSSMPatchCompliancePolicy</li><li>SSMMaintenanceWindowRole</li><li>AmazonSSManagedInstanceCore</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk5FqcxQrdpYvo9VlwgAfA.png" /><figcaption>Required Polices</figcaption></figure><p>3.<strong>VPC Endpoints (for instances in private subnets)</strong>: Ensure the required <strong>VPC Endpoints</strong> for Systems Manager services (SSM, EC2Messages, SSMMessages) are set up.</p><h3>Step 1: Create a Patch Baseline</h3><p>A patch baseline defines which patches are approved for installation and how compliance is determined.</p><ol><li>Open the <strong>AWS Systems Manager Console</strong> and navigate to <strong>Patch Manager</strong>.</li><li>Choose <strong>Create patch baseline</strong>.</li><li>Provide a descriptive name, for example: Custom-Windows-Patch-Baseline.</li><li>Select the operating system (e.g., Windows or Amazon Linux).</li><li>Configure approval rules:</li></ol><ul><li>Classification: CriticalUpdates and SecurityUpdates</li><li>Severity: Critical and Important</li><li>Auto-approval delay: 7 days (allows time for validation before rollout)</li></ul><p>6. Click on Create the baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpRldeuTAG9EqWs-bdjS8Q.png" /><figcaption>Default Baseline</figcaption></figure><h3>Step 2: Assign Patch Baseline to Patch Groups</h3><h4>2.1 Define a Patch Group</h4><ul><li>Create a patch group by tagging your instances with a specific key-value pair (e.g., Patch Group = Windows-Prod-Servers).</li></ul><h4>2.2 Assign the Baseline to the Patch Group</h4><ul><li>In the <strong>Patch Manager</strong> dashboard, select the custom patch baseline created earlier.</li><li>Choose <strong>Actions</strong>, then <strong>Modify Patch Groups</strong>.</li><li>Assign a <strong>tag</strong> to your instances to define the P<strong>atch group</strong>. Example: (Key: Patch Group Value: Windows-Prod-Servers)</li><li>Choose <strong>Add Patch Group</strong>, then <strong>Save Changes</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ser72F3d0-jXMfD79iqDA.png" /><figcaption>EC2- Windows Server Default Patch Baseline Within Patch Group</figcaption></figure><h3>Step 3: Create a Maintenance Window</h3><h4>3.1 Navigate to Maintenance Windows</h4><ul><li>In the <strong>AWS Systems Manager</strong> console, navigate to <strong>Maintenance Windows</strong> under <strong>Shared Resources</strong>.</li></ul><h4>3.2 Create a New Maintenance Window</h4><ul><li>Choose <strong>Create maintenance window</strong>.</li><li>Provide a <strong>name</strong> for the maintenance window, such as Windows-Patch-Maintenance-Window.</li></ul><h4>3.3 Set Maintenance Window Schedule</h4><ul><li>Under <strong>Schedule</strong>, enter a CRON or rate expression for the desired schedule.</li><li>Example: cron(0 3 ? * SUN *) (Runs every Sunday at 3 AM UTC).</li><li><strong>Duration</strong>: Set the duration for how long the window should remain open (e.g., 4 hours).</li><li><strong>Stop Tasks on Expiry</strong>: Enable this to ensure tasks are halted when the window expires.</li><li>Enable the option <strong>Stop tasks on expiry</strong> to ensure no tasks run beyond the defined window.</li><li>Choose <strong>Create Maintenance Window</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_zqmnWgd3TOGpq1Dr-0Zg.png" /><figcaption>Image Showing a Maintenance Window</figcaption></figure><h3>Step 4: Register Patch Task with Maintenance Window</h3><h4>4.1 Register a Task for Patching</h4><ul><li>Choose the newly created maintenance window from the list.</li><li>Select <strong>Actions</strong>, then <strong>Register task</strong>.</li></ul><h4>4.2 Set the Task Type</h4><ul><li>For <strong>Task Type</strong>, select <strong>Run Command</strong>.</li><li>Choose <strong>AWS-RunPatchBaseline</strong> as the command document.</li></ul><h4>4.3 Configure Patch Command</h4><ul><li>In the <strong>Targets</strong> section, choose <strong>Patch Group</strong> as the target type.</li><li>Select the appropriate patch group tag (e.g., Windows-Prod-Servers).</li><li>In <strong>Command Parameters</strong>, specify the following:</li><li><strong>Operation</strong>: Set to Install.</li><li><strong>Snapshot ID</strong>: Optional, used for auditing purposes.</li><li>Choose <strong>Register</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwVWIn8hS7AG6E_s8vCuYA.png" /><figcaption>Patch Group</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsMugSXEywIPRC0DnBOTbA.png" /><figcaption>Next Maintenance Window Execution</figcaption></figure><h3>Step 5: Configure Notifications (Optional)</h3><h4>5.1 Set Up SNS for Notifications</h4><ul><li>Create an SNS topic to receive notifications about patching tasks.</li></ul><h4>5.2 Add SNS Notification</h4><ul><li>In the <strong>Patch Manager</strong> console, choose the created maintenance window.</li><li>Under <strong>Configure Notifications</strong>, add the SNS topic to receive patch status updates.</li></ul><h3>Step 6: Verify Patch Installation and Reporting</h3><h4>6.1 Monitoring via AWS Systems Manager</h4><ul><li>After the patch operation runs, monitor the status of the operation by going to <strong>Systems Manager &gt; Run Command</strong>.</li><li>Check for successful patch installations and any issues flagged during the process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyuJ8a-RvH049AiDn59uHQ.png" /></figure><h4>6.2 Review Patch Compliance Reports</h4><ul><li>Navigate to <strong>Patch Manager</strong> and select <strong>Patch Compliance</strong> to view the compliance status of instances.</li><li>Instances marked as <strong>Non-compliant</strong> will be highlighted for missing patches or issues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zu584nP-d5-yt6j5gGFwlQ.png" /><figcaption>Patch Manager With Compliance Reporting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0lzjZqvk9KFWwuF2kl2Uw.png" /><figcaption>Patch Manager Configuration Manager</figcaption></figure><h3>Step 7: Integrate with AWS Security Hub and Config (Optional)</h3><h4>7.1 Enable AWS Security Hub</h4><ul><li>Ensure that <strong>AWS Security Hub</strong> is enabled.</li><li>AWS Security Hub can automatically receive findings from <strong>AWS Systems Manager Patch Manager</strong> regarding non-compliant nodes.</li></ul><h4>7.2 Enable AWS Config Rules</h4><ul><li>Enable <strong>AWS Config</strong> and add a custom rule to validate compliance for patched nodes.</li><li>Use the patch-compliance rule to ensure instances are continuously monitored for missing patches.</li></ul><h3>Step 8: Testing and Validation</h3><h4>8.1 Test Patch Application</h4><ul><li>Test the patch management solution on non-production instances by assigning them to a test patch group.</li><li>Monitor for any issues during the installation of patches and ensure compliance before rolling out to production.</li></ul><h3>Step 9: Post-Patch Maintenance</h3><h4>9.1 Review Patch Logs</h4><ul><li>After patches have been installed, review the patch logs in the <strong>S3 bucket</strong> configured for logging patch operations.</li></ul><h4>9.2 Reboot Instances (If Required)</h4><ul><li>If patching requires instance reboots, ensure that all systems are properly restarted. Systems Manager can automatically handle reboots during patching if configured.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPU76g9tK2_rN6VYRVOmeA.png" /><figcaption>Patch Manager Configuration Details with Association Drill Down</figcaption></figure><p>Scan Report From Scan for Patches:</p><pre>Patch Summary for i-07cfae93c02a42576<br>PatchGroup          : <br>BaselineId          : pb-09ca3fb51f0412ec3<br>Baseline            : {&quot;AccountId&quot;:&quot;**********&quot;,&quot;BaselineId&quot;:&quot;pb-09ca3fb51f0412ec3&quot;,&quot;Name&quot;:&quot;AWS-DefaultPatchBaseline&quot;,&quot;GlobalFilters&quot;:{&quot;Filters&quot;:[{&quot;Key&quot;:&quot;PRODUCT&quot;,&quot;Values&quot;:[&quot;*&quot;]}]},&quot;ApprovalRules&quot;:{&quot;Rules&quot;:[{&quot;ApproveAfterDays&quot;:7,&quot;FilterGroup&quot;:{&quot;Filters&quot;:[{&quot;Key&quot;:&quot;CLASSIFICATION&quot;,&quot;Values&quot;:[&quot;CriticalUpdates&quot;,&quot;SecurityUpdates&quot;]},{&quot;Key&quot;:&quot;MSRC_SEVERITY&quot;,&quot;Values&quot;:[&quot;Critical&quot;,&quot;Important&quot;]}]}}]},&quot;ApprovedPatches&quot;:[],&quot;RejectedPatches&quot;:[],&quot;RejectedPatchesAction&quot;:&quot;ALLOW_AS_DEPENDENCY&quot;,&quot;CreatedTime&quot;:1525194800.068,&quot;ModifiedTime&quot;:1525194800.068,&quot;Description&quot;:&quot;Default Patch Baseline Provided by AWS.&quot;}<br>SnapshotId          : e69f4f48-a305-49de-8183-b35e4df6276f<br>ExecutionId         : 13e63f82-d51c-4f6a-b829-aabeeb6aeb5a<br>RebootOption        : NoReboot<br>OwnerInformation    : <br>OperationType       : Scan<br>OperationStartTime  : 2024-09-18T19:11:57.6562057Z<br>OperationEndTime    : 2024-09-18T19:12:28.6799891Z<br>InstalledCount      : 2<br>InstalledRejectedCount : 0<br>InstalledPendingRebootCount : 0<br>InstalledOtherCount : 7<br>FailedCount         : 0<br>MissingCount        : 0<br>CriticalNonCompliantCount : 0<br>SecurityNonCompliantCount : 0<br>OtherNonCompliantCount : 0<br>NotApplicableCount  : 2453<br>UnreportedNotApplicableCount : 0<br>EC2AMAZ-4CPTN15 - PatchBaselineOperations Assessment Results - 2024-09-18T19:12:29.117<br>Scan found no missing updates.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664b9ef81f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Private PostgreSQL RDS with Terraform, Private EC2 and AWS Systems Manager]]></title>
            <link>https://medium.com/@roshanpoudel.me/automating-private-postgresql-rds-with-terraform-private-ec2-and-aws-systems-manager-d931803d9907?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d931803d9907</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database-automation]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 18:27:35 GMT</pubDate>
            <atom:updated>2025-08-06T18:45:06.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure PostgreSQL RDS Automation with Terraform: No Bastion Host Required</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTRCEi1gBM-mfPBoPPRFZQ.png" /></figure><p>Managing PostgreSQL databases within private Amazon RDS instances poses significant challenges for DevOps and platform engineering teams. Manual processes are inefficient, and traditional automation methods often compromise security or scalability. This guide presents a robust, production-ready solution using <strong>Terraform</strong> and <strong>AWS Systems Manager (SSM)</strong> to automate PostgreSQL RDS database provisioning, user management, and extension configuration in private subnets.</p><h4>Key Objectives</h4><ul><li>Implement secure, API-driven database automation.</li><li>Ensure scalability for production environments.</li><li>Maintain compliance with enterprise security standards.</li><li>Streamline repetitive tasks, such as enabling the pgvector extension</li></ul><h4>Bastion Host Challenges</h4><ul><li><strong>Security Risks</strong>: Exposed SSH ports and complex key management increase vulnerabilities.</li><li><strong>Operational Constraints</strong>: Network dependencies create single points of failure and hinder scalability.</li></ul><h4>The SSM Worker Pattern</h4><p>The <strong>SSM Worker Pattern</strong> leverages AWS Systems Manager to deliver a secure, API-driven approach to PostgreSQL RDS automation. This method eliminates network dependencies, enhances reliability, and aligns with enterprise security standards.</p><h4>Architecture Overview</h4><ul><li><strong>Terraform</strong>: Initiates automation tasks via AWS SSM APIs.</li><li><strong>EC2 Worker</strong>: A lightweight instance in a private subnet executes database operations.</li><li><strong>RDS Instance</strong>: Hosted in the same private subnet, ensuring secure communication.</li><li><strong>AWS Secrets Manager</strong>: Manages credentials with automated rotation and least-privilege access.</li></ul><h4>Network Design</h4><ul><li><strong>Public Subnet</strong>: Contains a NAT Gateway for outbound internet access.</li><li><strong>Private Subnet</strong>: Hosts the EC2 worker and RDS instance, isolated from external access.</li><li><strong>Security Controls</strong>: Security groups restrict traffic to PostgreSQL (port 5432) and HTTPS (port 443) for AWS API calls.</li></ul><h4>Implementation</h4><p>Now, it’s time to move from theory to implementation. Before we begin, ensure you have the following prerequisites in place:</p><ul><li><strong>AWS Account and Credentials</strong></li><li><strong>Terraform v1.x Installed:</strong> <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fwww.terraform.io%2Fdownloads.html">Download Terraform</a></li><li><strong>AWS CLI Installed and Configured:</strong> <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Faws.amazon.com%2Fcli%2F">Install the AWS CLI</a></li></ul><p>This Terraform project provisions a complete, private, and automated PostgreSQL database environment on AWS. A central and indispensable component of this architecture is the NAT Gateway, which enables the secure and reliable operation of the automation process. <a href="https://github.com/soocrates/private-rds-with-ssm-driven-db-automation"><strong>Git Repo link</strong></a></p><pre>git clone https://github.com/soocrates/private-rds-with-ssm-driven-db-automation.git<br><br>cd private-rds-with-ssm-driven-db-automation</pre><h4>Phase 1: Foundational Infrastructure</h4><ul><li><strong>Centralized Configuration (</strong>locals<strong>,)</strong>: Defines all configuration values and naming conventions in a single, easy-to-manage locals block. This includes VPC CIDRs,region and the full configuration for the RDS instance.</li><li><strong>Dynamic Credential Generation ( </strong>random_pet<strong>, </strong>random_password<strong>)</strong>: Securely generates unique, random usernames and strong passwords for both the RDS master user and each of the application databases. This avoids hardcoding secrets.</li><li><strong>VPC and Networking (</strong>module &quot;vpc&quot;<strong>)</strong>: Deploys a new, highly available VPC with public and private subnets across multiple AZs, including a NAT Gateway to allow secure outbound internet access for private resources. <br>The <strong>NAT Gateway is explicitly created (</strong>enable_nat_gateway = true<strong>) and placed in a public subnet</strong>. A route is then added to the <strong>private subnets’ route tables</strong> that directs all internet-bound traffic (0.0.0.0/0) to this NAT Gateway.</li></ul><pre>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;6.0.1&quot;<br><br>  name = &quot;${local.naming_prefix}-vpc&quot;<br>  cidr = local.vpc.vpc_cidr<br><br>  azs             = local.vpc.azs<br>  private_subnets = [for k, v in local.vpc.azs : cidrsubnet(local.vpc.vpc_cidr, 4, k)]<br>  public_subnets  = [for k, v in local.vpc.azs : cidrsubnet(local.vpc.vpc_cidr, 4, k + 4)]<br><br>  enable_nat_gateway = true<br>  single_nat_gateway = true<br><br>  tags = local.tags<br>}</pre><ul><li><strong>Security Groups (</strong>aws_security_group<strong>, </strong>aws_security_group_rule<strong>)</strong>: Establishes a zero-trust network policy. It creates separate firewalls for the RDS instance and the EC2 worker, then adds a single, explicit rule to allow the EC2 worker to communicate with the RDS instance over the PostgreSQL port (5432).</li></ul><pre>resource &quot;aws_security_group&quot; &quot;rds_sg&quot; {<br>  name        = &quot;${local.naming_prefix}-db-sg&quot;<br>  description = &quot;Allows PostgreSQL access&quot;<br>  vpc_id      = module.vpc.vpc_id<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br>resource &quot;aws_security_group&quot; &quot;rds_connector_ec2_sg&quot; {<br>  name        = &quot;${local.naming_prefix}-rds-connector-sg&quot;<br>  description = &quot;Allows outbound for SSM and RDS access&quot;<br>  vpc_id      = module.vpc.vpc_id<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br>resource &quot;aws_security_group_rule&quot; &quot;rds_allow_from_ec2&quot; {<br>  type                     = &quot;ingress&quot;<br>  from_port                = 5432<br>  to_port                  = 5432<br>  protocol                 = &quot;tcp&quot;<br>  source_security_group_id = aws_security_group.rds_connector_ec2_sg.id<br>  security_group_id        = aws_security_group.rds_sg.id<br>  description              = &quot;Allow PostgreSQL traffic from EC2 to RDS&quot;<br>}</pre><h4>Phase 2: Database and Secrets Provisioning</h4><ul><li><strong>RDS Instance (</strong>module &quot;rds&quot;<strong>)</strong>: Deploys a new, private PostgreSQL 14 database instance using the official AWS module. It’s configured to be non-publicly accessible, has deletion protection disabled (typical for development), and uses the dynamically generated master credentials.</li></ul><pre>module &quot;rds&quot; {<br>  source  = &quot;terraform-aws-modules/rds/aws&quot;<br>  version = &quot;6.7.0&quot;<br><br>  identifier                  = local.rds.identifier<br>  engine                      = local.rds.engine<br>  engine_version              = local.rds.engine_version<br>  family                      = local.rds.family<br>  port                        = local.rds.port<br>  apply_immediately           = local.rds.apply_immediately<br>  publicly_accessible         = local.rds.publicly_accessible<br>  manage_master_user_password = local.rds.manage_master_user_password<br>  skip_final_snapshot         = local.rds.skip_final_snapshot<br><br>  instance_class      = local.rds.instance_class<br>  allocated_storage   = local.rds.allocated_storage<br>  deletion_protection = local.rds.deletion_protection<br><br>  username = local.rds.username<br>  password = local.rds.password<br><br>  subnet_ids             = local.rds.subnet_ids<br>  vpc_security_group_ids = local.rds.vpc_security_group_ids<br>  create_db_subnet_group = local.rds.create_db_subnet_group<br><br>}</pre><ul><li><strong>Master Secret(</strong>module &quot;master_secrets&quot;<strong>)</strong>: Creates a dedicated secret in AWS Secrets Manager to securely store the master username and password for the RDS instance.</li></ul><pre>module &quot;master_secret&quot; {<br>  source  = &quot;terraform-aws-modules/secrets-manager/aws&quot;<br>  version = &quot;1.3.1&quot;<br><br>  name_prefix             = &quot;${local.naming_prefix}-master-db-secrets&quot;<br>  description             = &quot;Master DB credentials&quot;<br>  recovery_window_in_days = 7<br>  enable_rotation         = false<br><br>  secret_string = jsonencode({<br>    username = random_pet.master.id<br>    password = random_password.master.result<br>    db_host  = module.rds.db_instance_endpoint<br>  })<br>}</pre><ul><li><strong>Application Secrets (</strong>module &quot;app_db_secrets&quot;<strong>)</strong>: For each application database name defined in the var.app_db_names variable, this block iterates (for_each) and creates a separate, dedicated secret in Secrets Manager containing that database’s unique, randomly generated credentials.</li></ul><pre>module &quot;app_db_secrets&quot; {<br>  source  = &quot;terraform-aws-modules/secrets-manager/aws&quot;<br>  version = &quot;1.3.1&quot;<br><br>  for_each = toset(var.app_db_names)<br><br>  name_prefix             = &quot;${local.naming_prefix}-${each.key}-db-secrets&quot;<br>  description             = &quot;App DB credentials for ${each.key}&quot;<br>  recovery_window_in_days = 7<br>  enable_rotation         = false<br><br>  secret_string = jsonencode({<br>    username = random_pet.app_db_usernames[each.key].id<br>    password = random_password.app_db_passwords[each.key].result<br>    db_name  = each.key<br>    db_host  = module.rds.db_instance_endpoint<br>  })</pre><h4>Phase 3: The Automation Engine (EC2 Worker, SSM Documents, Provisioners)</h4><p>The core of the automation relies on a private EC2 “worker” instance that executes scripts via AWS Systems Manager (SSM). This worker’s ability to function is <strong>entirely dependent on the NAT Gateway</strong>. The NAT Gateway is used at several crucial steps in the process:</p><p><strong>The Worker (</strong>aws_instance &quot;rds_connector&quot;<strong>)</strong>: A private Ubuntu EC2 instance is created. It is assigned an IAM role that grants it permissions to be managed by SSM and to read the secrets from Secrets Manager.</p><pre>resource &quot;aws_instance&quot; &quot;rds_connector&quot; {<br>  ami                         = local.connector_instance.ami  <br>  instance_type               = local.connector_instance.instance_type<br>  subnet_id                   = module.vpc.private_subnets[0]<br>  vpc_security_group_ids      = [aws_security_group.rds_connector_ec2_sg.id]<br>  iam_instance_profile        = aws_iam_instance_profile.ssm_profile.name<br>  associate_public_ip_address = false<br><br>  root_block_device {<br>    volume_size           = 8<br>    volume_type           = &quot;gp3&quot;<br>    delete_on_termination = true<br>  }<br>  tags = {<br>    Name = &quot;${local.naming_prefix}-rds-connector&quot;<br>  }<br>  depends_on = [module.rds]<br>}<br><br>resource &quot;null_resource&quot; &quot;configure_instance&quot; {<br>  triggers = {<br>    instance_id   = aws_instance.rds_connector.id<br>    document_hash = sha256(aws_ssm_document.install_tools.content)<br>  }<br><br>  depends_on = [<br>    aws_instance.rds_connector,<br>    module.rds<br>  ]<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &lt;&lt;-EOT<br>      #!/bin/bash<br>      set -e<br>      echo &quot;&gt;&gt;&gt; STAGE 1: Configuring instance ${self.triggers.instance_id} with required tools...&quot;<br>      COMMAND_ID=$(aws ssm send-command --instance-ids &quot;${self.triggers.instance_id}&quot; --document-name &quot;${aws_ssm_document.install_tools.name}&quot; --query &quot;Command.CommandId&quot; --output text)<br>      echo &quot;Configuration command sent. Waiting for completion... (Command ID: $COMMAND_ID)&quot;<br>      aws ssm wait command-executed --command-id $COMMAND_ID --instance-id &quot;${self.triggers.instance_id}&quot;<br>      STATUS=$(aws ssm list-command-invocations --command-id $COMMAND_ID --details --query &quot;CommandInvocations[0].Status&quot; --output text)<br>      if [ &quot;$STATUS&quot; != &quot;Success&quot; ]; then<br>        echo &quot;ERROR: Instance configuration failed with status: $STATUS&quot;<br>        aws ssm get-command-invocation --command-id $COMMAND_ID --instance-id &quot;${self.triggers.instance_id}&quot; --query &quot;StandardErrorContent&quot; --output text<br>        exit 1<br>      fi<br>      echo &quot;&gt;&gt;&gt; STAGE 1: Instance configuration successful. &lt;&lt;&lt;&quot;<br>    EOT<br>    interpreter = [&quot;bash&quot;, &quot;-c&quot;]<br>  }<br>}<br><br>resource &quot;null_resource&quot; &quot;invoke_db_creator&quot; {<br>  for_each = toset(var.app_db_names)<br><br>  triggers = {<br>    instance_id   = aws_instance.rds_connector.id<br>    db_name       = each.key<br>    db_host       = module.rds.db_instance_address<br>    document_hash = sha256(aws_ssm_document.db_creator.content)<br>    app_secret    = module.app_db_secrets[each.key].secret_arn<br>    master_secret = module.master_secret.secret_arn<br>  }<br><br>  depends_on = [<br>    null_resource.configure_instance,<br>    aws_instance.rds_connector,<br>    module.rds,<br>    module.app_db_secrets,<br>    module.master_secret,<br>    aws_ssm_document.db_creator<br>  ]<br><br>  provisioner &quot;local-exec&quot; {<br>    command     = &lt;&lt;-EOT<br>      #!/bin/bash<br>      set -e<br>      echo &quot;&gt;&gt;&gt; STAGE 2: Sending command for database: ${self.triggers.db_name}...&quot;<br><br>      COMMAND_ID=$(aws ssm send-command \<br>        --instance-ids &quot;${self.triggers.instance_id}&quot; \<br>        --document-name &quot;${aws_ssm_document.db_creator.name}&quot; \<br>        --parameters &quot;NewDBName=[&#39;${self.triggers.db_name}&#39;],NewUserPasswordSecretArn=[&#39;${self.triggers.app_secret}&#39;],MasterSecretArn=[&#39;${self.triggers.master_secret}&#39;],DBHost=[&#39;${self.triggers.db_host}&#39;]&quot; \<br>        --query &quot;Command.CommandId&quot; \<br>        --output text)<br><br>      echo &quot;Waiting for DB creation for ${self.triggers.db_name}... (Command ID: $COMMAND_ID)&quot;<br>      aws ssm wait command-executed --command-id $COMMAND_ID --instance-id &quot;${self.triggers.instance_id}&quot;<br><br>      STATUS=$(aws ssm list-command-invocations --command-id $COMMAND_ID --details --query &quot;CommandInvocations[0].Status&quot; --output text)<br>      if [ &quot;$STATUS&quot; != &quot;Success&quot; ]; then<br>          echo &quot;ERROR: DB creation command failed for ${self.triggers.db_name} with status: $STATUS&quot;<br>          aws ssm get-command-invocation --command-id $COMMAND_ID --instance-id &quot;${self.triggers.instance_id}&quot; --query &quot;StandardErrorContent&quot; --output text<br>          exit 1<br>      fi<br><br>      echo &quot;&gt;&gt;&gt; STAGE 2: Database ${self.triggers.db_name} created successfully. &lt;&lt;&lt;&quot;<br>    EOT<br>    interpreter = [&quot;bash&quot;, &quot;-c&quot;]<br>  }<br>}</pre><ul><li><strong>Stage 1: Instance Configuration (</strong>null_resource configure_instance&quot;<strong>)</strong>:</li><li>This is the first operational step. It triggers the InstallDBWorkerTools-Ubuntu SSM document.</li><li>This document’s sole responsibility is to prepare the EC2 instance by installing all necessary tools (aws-cli, jq, postgresql-client) in a robust way, handling OS-specific issues like the apt lock.</li><li>The provisioner <strong>waits</strong> for this configuration to complete successfully before allowing Stage 2 to begin.</li></ul><pre># =========================================================================<br># STAGE 1: CONFIGURE THE INSTANCE (runs only ONCE)<br># =========================================================================<br><br># This SSM Document&#39;s only job is to install software.<br>resource &quot;aws_ssm_document&quot; &quot;install_tools&quot; {<br>  name            = &quot;InstallDBWorkerTools-Ubuntu&quot;<br>  document_format = &quot;YAML&quot;<br>  document_type   = &quot;Command&quot;<br><br>  content = &lt;&lt;-YAML<br>schemaVersion: &quot;2.2&quot;<br>description: &quot;Installs all necessary tools for the DB worker instance.&quot;<br>mainSteps:<br>  - action: &quot;aws:runShellScript&quot;<br>    name: &quot;InstallTools&quot;<br>    inputs:<br>      runCommand:<br>        - |<br>          #!/bin/bash<br>          set -e<br>          echo &quot;--- Waiting for OS to stabilize and release APT lock...&quot;<br>          while sudo fuser /var/lib/dpkg/lock-frontend &gt;/dev/null 2&gt;&amp;1 || sudo fuser /var/lib/apt/lists/lock &gt;/dev/null 2&gt;&amp;1 ; do<br>             echo &quot;APT lock is held, waiting 15 seconds...&quot;<br>             sleep 15<br>          done<br><br>          echo &quot;--- Installing prerequisite tools...&quot;<br>          export DEBIAN_FRONTEND=noninteractive<br>          sudo apt-get update -y<br>          sudo apt-get install -y curl unzip jq postgresql-client<br><br>          echo &quot;--- Installing/Updating AWS CLI v2...&quot;<br>          curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>          unzip -o awscliv2.zip<br>          sudo ./aws/install --update<br><br>          echo &quot;--- All tools installed successfully ---&quot;<br>YAML<br>}<br><br># =========================================================================<br># STAGE 2: CREATE DATABASES (runs in parallel for each DB)<br># =========================================================================<br><br>resource &quot;aws_ssm_document&quot; &quot;db_creator&quot; {<br>  name            = &quot;CreatePostgresDBAndUserWithVector&quot;<br>  document_format = &quot;YAML&quot;<br>  document_type   = &quot;Command&quot;<br><br>  content = &lt;&lt;-YAML<br>schemaVersion: &quot;2.2&quot;<br>description: &quot;Idempotently creates a PostgreSQL database and user. Skips creation if they already exist.&quot;<br>parameters:<br>  NewDBName:<br>    type: String<br>  NewUserPasswordSecretArn:<br>    type: String<br>  MasterSecretArn:<br>    type: String<br>  DBHost:<br>    type: String<br>mainSteps:<br>  - action: &quot;aws:runShellScript&quot;<br>    name: &quot;CreateDatabase&quot;<br>    inputs:<br>      runCommand:<br>        - |<br>          #!/bin/bash<br>          set -e<br>          echo &quot;--- Starting idempotent DB setup for {{ NewDBName }} ---&quot;<br><br>          # This part assumes tools are already installed by the configure_instance stage.<br><br>          echo &quot;Step 1: Fetching credentials...&quot;<br>          MASTER_SECRET=$(aws secretsmanager get-secret-value --secret-id &quot;{{ MasterSecretArn }}&quot; --query SecretString --output text)<br>          NEW_USER_SECRET=$(aws secretsmanager get-secret-value --secret-id &quot;{{ NewUserPasswordSecretArn }}&quot; --query SecretString --output text)<br><br>          echo &quot;Step 2: Preparing shell variables...&quot;<br>          export DB_MASTER_USER=$(echo $MASTER_SECRET | jq -r .username)<br>          export PGPASSWORD=$(echo $MASTER_SECRET | jq -r .password)<br>          DB_HOST=&quot;{{ DBHost }}&quot;<br>          NEW_DB_NAME=&quot;{{ NewDBName }}&quot;<br>          NEW_DB_USER=&quot;$${NEW_DB_NAME}_user&quot;<br>          NEW_DB_PASSWORD=$(echo $NEW_USER_SECRET | jq -r .password)<br><br>          # =========================================================================<br>          # LOGIC FOR THE ROLE (USER)<br>          # =========================================================================<br>          echo &quot;Step 3: Checking if role &#39;$NEW_DB_USER&#39; already exists...&quot;<br>          # The -t flag gives tuples-only output. psql returns exit code 0 even if no rows are found.<br>          # We check if the result string is empty (-z).<br>          if [[ -z $(psql -h $DB_HOST -U $DB_MASTER_USER -d postgres -t -c &quot;SELECT 1 FROM pg_roles WHERE rolname = &#39;$NEW_DB_USER&#39;&quot;) ]]; then<br>            echo &quot;Role &#39;$NEW_DB_USER&#39; not found. Creating...&quot;<br>            psql -h $DB_HOST -U $DB_MASTER_USER -d postgres -c &quot;CREATE ROLE \&quot;$NEW_DB_USER\&quot; WITH LOGIN PASSWORD &#39;$NEW_DB_PASSWORD&#39;;&quot;<br>            echo &quot;Role &#39;$NEW_DB_USER&#39; created.&quot;<br>          else<br>            echo &quot;Role &#39;$NEW_DB_USER&#39; already exists. Skipping role creation.&quot;<br>          fi<br><br>          # =========================================================================<br>          # LOGIC FOR THE DATABASE<br>          # =========================================================================<br>          echo &quot;Step 4: Checking if database &#39;$NEW_DB_NAME&#39; already exists...&quot;<br>          if [[ -z $(psql -h $DB_HOST -U $DB_MASTER_USER -d postgres -t -c &quot;SELECT 1 FROM pg_database WHERE datname = &#39;$NEW_DB_NAME&#39;&quot;) ]]; then<br>            echo &quot;Database &#39;$NEW_DB<br><br>_NAME&#39; not found. Creating...&quot;<br>            psql -h $DB_HOST -U $DB_MASTER_USER -d postgres -c &quot;CREATE DATABASE \&quot;$NEW_DB_NAME\&quot; OWNER \&quot;$NEW_DB_USER\&quot;;&quot;<br>            echo &quot;Database &#39;$NEW_DB_NAME&#39; created.&quot;<br>          else<br>            echo &quot;Database &#39;$NEW_DB_NAME&#39; already exists. Skipping database creation.&quot;<br>          fi<br><br>          # =========================================================================<br>          # LOGIC FOR THE EXTENSION (built-in)<br>          # =========================================================================<br>          echo &quot;Step 5: Ensuring &#39;vector&#39; extension exists in database &#39;$NEW_DB_NAME&#39;...&quot;<br>          psql -h $DB_HOST -U $DB_MASTER_USER -d $NEW_DB_NAME -c &quot;CREATE EXTENSION IF NOT EXISTS vector;&quot;<br>          echo &quot;Extension &#39;vector&#39; is present.&quot;<br><br>          echo &quot;--- SUCCESS: Idempotent setup for database $NEW_DB_NAME is complete. ---&quot;<br>YAML<br>}</pre><ul><li><strong>Stage 2 Database Creation (</strong>null_resource &quot;invoke_db_creator&quot;<strong>)</strong>:</li><li>This stage only begins after the instance is successfully configured.</li><li>It iterates (for_each) over the list of application databases.</li><li>For each database, it triggers the CreatePostgresDBAndUserWithVector SSM document.</li><li>This document is <strong>idempotent</strong>: it connects to the RDS instance as the master user and checks if the application’s database and user already exist before attempting to create them. It also enables the vector extension.</li><li>The provisioner <strong>waits</strong> for each command to complete and verifies its success, ensuring a reliable and predictable outcome.</li></ul><p><strong>NAT Gateway’s Role</strong>:</p><p>The SSM Agent initiates this <strong>outbound connection</strong>. The traffic is routed from the private subnet to the NAT Gateway, which translates the private IP to its public IP and forwards the request to the AWS SSM endpoints.</p><p>Without the NAT Gateway, the SSM Agent would be completely isolated and could never receive the commands sent by Terraform. The aws ssm send-command call would eventually time out and fail.</p><h3>Steps to Verify the implementation</h3><p>After a successful terraform apply,let’s check all components were configured as expected. So i will walk you through connecting to the private EC2 worker via SSM Session Manager and inspecting the RDS instance to confirm the successful creation of databases, users, and permissions.</p><p><strong>Start an SSM Session:</strong><br>Catch your instance ID from from terraform output and start the session.</p><pre>aws ssm start-session --target &lt;your_instance_id_here&gt;<br><br>bash<br>cd ~</pre><h3>Verify Tool Installation</h3><p>Before checking the database, let’s confirm that the “Stage 1” configuration script ran successfully and installed all the necessary command-line tools.</p><pre>which psql  # Check for psql<br>which jq    # Check for jq<br>which aws   # Check for awscli</pre><h3>Verify Databases, Users, and Permissions</h3><p>Now, we will connect to the private PostgreSQL database to perform our checks. We need to fetch the master user’s credentials from AWS Secrets Manager to have the necessary privileges for inspection.</p><p><strong>See All Databases and Their Owners:</strong></p><p>The \l command lists all databases and shows who owns them.</p><pre>psql -h $YOUR_DB_HOST -p 5432 -U $YOUR_MASTER_USER -d postgres -c &quot;\l&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DquG7r5kCKL422Q4louY6A.png" /></figure><p><strong>See All New Users (Roles):</strong><br>The \du command lists all user roles in the database cluster.</p><pre>psql -h $YOUR_DB_HOST -U $YOUR_MASTER_USER -d postgres -c &quot;\du&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnX8QEOstHFC_nkhn2_38Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao8Irm-R0s7ICDz7B2K1_w.png" /></figure><p><strong>Verify User Permissions on Their Respective Databases:</strong><br>This is a crucial check. A user being the “owner” of a database grants them all privileges on it (create tables, select, insert, etc.). We can verify this by checking the access privileges.</p><pre>psql -h $YOUR_DB_HOST -U $YOUR_MASTER_USER -d postgres -c &quot;\l db001&quot;</pre><p><strong>Verify the </strong>vector<strong> Extension is Enabled:</strong><br>Finally, we need to connect to each new database individually and check for the extension. You can use this convenient for loop to check all of them at once.</p><pre>psql -h $db_host  -p 5432 -U $db_user -d $db_name -c &quot;\dx vector&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Z13rDxuZFhct-65JRq_5Aw.png" /></figure><h4>Optimization</h4><p>To optimize cost by avoiding unnecessary compute charges, you can stop an EC2 instance using stop-instance command when it’s not in use, and start it again when needed using start-instances .</p><pre>aws ec2 stop-instances --instance-ids &lt;instance-id&gt; # to stop instance<br>aws ec2 start-instances --instance-ids &lt;instance-id&gt; # to start instance</pre><p>You can find entire project this repository: <a href="https://github.com/soocrates"><strong>soocrates</strong></a><strong>/</strong><a href="https://github.com/soocrates/private-rds-with-ssm-driven-db-automation"><strong>private-rds-with-ssm-driven-db-automatio</strong></a>n</p><p>Looking for your comments, suggestions and improvements and let’s connect on <a href="https://www.linkedin.com/in/roshan-poudel-845964364/">LinkedIn</a> !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d931803d9907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Unnecessary Terraform Replacements: Understanding lifecycle.ignore_changes]]></title>
            <link>https://medium.com/@roshanpoudel.me/avoiding-unnecessary-terraform-replacements-understanding-lifecycle-ignore-changes-e8cabdada7b6?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8cabdada7b6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lifecycle-management]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 09:03:05 GMT</pubDate>
            <atom:updated>2025-07-24T09:03:05.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJnLiXykrSIZ8hkzhyRxNw.jpeg" /></figure><p>When managing infrastructure with Terraform, one of the most frustrating experiences is seeing it attempt to recreate entire AWS resources for minor changes — especially when AWS allows those changes in-place.</p><p>A common culprit of this behavior is the aws_security_group resource, particularly when you update fields like description.</p><p>In this post, we’ll explore:</p><ul><li>Why Terraform forces replacements</li><li>How the lifecycle.ignore_changes block works</li><li>Real-world examples</li><li>Best practices to avoid disruptions in your AWS infrastructure</li></ul><h3>The Problem: Terraform Forces Unnecessary Resource Replacements</h3><p>Consider a Terraform-managed security group:</p><pre>resource &quot;aws_security_group&quot; &quot;database&quot; {<br>  name        = &quot;sg-name&quot;<br>  description = &quot;Security group for xxxxx database&quot;<br>  vpc_id      = var.vpc_id<br><br>  ingress {<br>    from_port   = 5432<br>    to_port     = 5432<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;10.0.0.0/16&quot;]<br>  }<br>}</pre><p>When you modify the description:</p><pre>- description = &quot;Security group for xxxxx database&quot;<br>+ description = &quot;Security group for YYYYYY database&quot;</pre><p>Running terraform plan reveals:</p><pre>-/+ resource &quot;aws_security_group&quot; &quot;database&quot; {<br>    ~ description = &quot;Security group for xxxxx database&quot; -&gt; &quot;Security group for YYYYYY database&quot; # forces replacement<br>    ...<br>}</pre><p>This triggers a complete resource replacement for what should be a simple in-place update.</p><h3>Why Terraform Forces Replacement for Description Changes</h3><p>While the AWS API supports in-place changes for security group descriptions through the console or CLI, Terraform’s AWS provider treats the description field with the internal flag ForceNew = true.</p><p>This behavior exists because:</p><ul><li>Descriptions may not be updateable via certain low-level EC2 APIs</li><li>They are considered immutable in specific contexts to prevent unpredictable behavior</li><li>The provider maintains consistency across different AWS services</li></ul><h3>The Solution: Using lifecycle.ignore_changes</h3><p>Terraform provides the lifecycle.ignore_changes block to prevent destructive behavior for specific attributes:</p><pre>resource &quot;aws_security_group&quot; &quot;database&quot; {<br>  name        = &quot;sg-name&quot;<br>  description = &quot;Security group for agrowfarm database&quot;<br>  vpc_id      = var.vpc_id <br> <br> ingress {<br>    from_port   = 5432<br>    to_port     = 5432<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;10.0.0.0/16&quot;]<br>  }<br><br>  lifecycle {<br>    ignore_changes = [description]<br>  }<br>}</pre><p>With this configuration, Terraform will not attempt to update the description, even if it differs from the state file.</p><h3>Real-World Implementation Examples</h3><h3>Ignoring Description Changes Only</h3><pre>lifecycle {<br>  ignore_changes = [description]<br>}</pre><p>Use this when you want to prevent security group replacement due to description updates while maintaining control over other attributes.</p><h3>Preventing Tag Drift</h3><p>Terraform often becomes out of sync with tags added outside of Terraform (manually or via default_tags):</p><pre>lifecycle {<br>  ignore_changes = [<br>    description,<br>    tags,<br>  ]<br>}</pre><p>This prevents replacements caused by tag modifications while allowing other important changes.</p><h3>Managing Rules with Separate Resources</h3><p>When using aws_security_group_rule resources for rule management (recommended for production), ignore inline rule changes:</p><pre>resource &quot;aws_security_group&quot; &quot;app&quot; {<br>  name   = &quot;app-sg&quot;<br>  vpc_id = var.vpc_id<br>  lifecycle {<br>    ignore_changes = [<br>      ingress,<br>      egress,<br>    ]<br>  }<br>}</pre><p>This prevents conflicts between inline rules and separately managed rule resources.</p><h3>Important Considerations</h3><h3>Understanding the Implications</h3><p>When using ignore_changes, Terraform will not report diffs for specified fields. To maintain visibility into configuration drift, consider using:</p><ul><li>terraform state show for current state inspection</li><li>AWS Config for compliance monitoring</li><li>CloudTrail for change auditing</li><li>Third-party drift detection tools</li></ul><h3>Avoiding Overuse</h3><p>While it’s tempting to ignore all problematic changes:</p><pre>lifecycle {<br>  ignore_changes = all<br>}</pre><p>This approach undermines infrastructure as code principles. Only ignore changes that are:</p><ul><li>Outside your direct control</li><li>Not worth resource recreation</li><li>Safe to drift without compliance or security implications</li></ul><h3>Production-Ready Security Group Pattern</h3><p>For security groups attached to critical resources like databases or EKS clusters, resource recreation can cause significant downtime:</p><pre>resource &quot;aws_security_group&quot; &quot;database&quot; {<br>  name        = &quot;db-sg&quot;<br>  description = &quot;Database security group&quot;<br>  vpc_id      = var.vpc_id<br>  <br>  lifecycle {<br>    ignore_changes = [description, tags]<br>  }<br>  tags = {<br>    Name        = &quot;db-sg&quot;<br>    Environment = &quot;production&quot;<br>  }<br>}</pre><p>This configuration allows manual updates to descriptions and tags while preventing resource destruction.</p><h3>Best Practices</h3><p><strong>Recommended use cases for ignore_changes:</strong></p><ul><li>Security groups in production environments</li><li>Launch templates with frequently changing user data</li><li>IAM role tags managed externally</li><li>Auto Scaling group settings with dynamic scaling</li><li>Load balancer attributes that change based on traffic patterns</li></ul><p><strong>Implementation guidelines:</strong></p><ul><li>Document why specific changes are ignored using code comments</li><li>Combine with external monitoring for configuration drift detection</li><li>Avoid masking legitimate configuration errors</li><li>Regularly review ignored changes to ensure they remain appropriate</li></ul><p><strong>What to avoid:</strong></p><ul><li>Ignoring critical security or compliance-related attributes</li><li>Using ignore_changes as a solution for poor resource design</li><li>Applying ignore_changes broadly without understanding implications</li></ul><h3>Conclusion</h3><p>Terraform’s resource replacement behavior, while generally predictable, can cause unexpected disruptions for certain AWS resources. The aws_security_group description field exemplifies how provider implementation details can impact infrastructure operations.</p><p>The lifecycle.ignore_changes block provides granular control over which changes should trigger resource recreation. When used judiciously, it prevents unnecessary downtime while maintaining the benefits of infrastructure as code.</p><p>By understanding when and how to apply these lifecycle rules, you can build more resilient Terraform configurations that balance automation with operational stability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8cabdada7b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing FastAPI with AWS Cognito: A Production-Ready Authentication Guide]]></title>
            <link>https://medium.com/@roshanpoudel.me/securing-fastapi-with-aws-cognito-a-production-ready-authentication-guide-52942b673e6d?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/52942b673e6d</guid>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 10:56:24 GMT</pubDate>
            <atom:updated>2025-06-10T10:56:24.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*xH6XslFIp15SHyQvgSDmqg.png" /><figcaption>Amazon Cognito With FastAPI</figcaption></figure><p>In modern application development, a performant API is only half the battle. The true measure of a production-ready service lies in its security, scalability, and maintainability. For developers leveraging the speed of FastAPI, implementing a robust authentication layer is a critical, non-negotiable step.</p><p>This guide provides a professional walkthrough for integrating AWS Cognito, a managed identity service, into a FastAPI application to create a secure, token-based authentication system. We will dissect the architecture of a well-structured solution, based on the principles demonstrated in <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fgithub.com%2Fsoocrates%2FAWS-Cognito-with-Uvicorn.git">this reference repository</a>, to deliver a blueprint that is both secure and scalable.</p><p><strong>This Guide will cover:</strong></p><ul><li>The OAuth2 Authorization Code Grant flow in a server-side context.</li><li>Cryptographic JWT signature verification against an AWS Cognito User Pool.</li><li>Secure session management using HttpOnly cookies.</li><li>A modular code structure for clean, maintainable security logic.</li></ul><h3>The Authentication Architecture: Protocol Overview</h3><p>To secure our application, we will implement the OAuth2 Authorization Code Grant flow. This is an industry-standard protocol designed for server-side applications to obtain access tokens securely.</p><p>The process unfolds in six distinct steps:</p><ol><li><strong>User Redirection:</strong> The user initiates the login process from a client application, which redirects them to the AWS Cognito Hosted UI.</li><li><strong>Credential Validation:</strong> The user authenticates directly with Cognito’s secure interface. This offloads password handling and multi-factor authentication from our application.</li><li><strong>Authorization Code Issuance:</strong> Upon successful authentication, Cognito redirects the user back to a pre-configured REDIRECT_URI in our FastAPI application, providing a temporary, single-use authorization_code.</li><li><strong>Server-to-Server Token Exchange:</strong> Our FastAPI backend receives the code and makes a secure, server-to-server request to Cognito’s token endpoint. It exchanges the code for a set of JSON Web Tokens (JWTs): id_token, access_token, and refresh_token.</li><li><strong>Secure Session Establishment:</strong> The server sets these tokens within HttpOnly, Secure cookies in the user’s browser. The HttpOnly flag is paramount, as it mitigates XSS attacks by preventing client-side scripts from accessing the tokens.</li><li><strong>Authenticated API Requests:</strong> For all subsequent requests to protected endpoints, the browser automatically includes the cookie. Our API validates the enclosed access_token to authorize the request.</li></ol><h3>Step 1: Environment and Initial Setup</h3><p>A proper foundation is essential. The following prerequisites and configuration steps are required.</p><p><strong>Prerequisites:</strong></p><ul><li>Python 3.7+</li><li>An active AWS Account with a configured <strong>AWS Cognito User Pool</strong>.</li><li>Within the User Pool, an “App client” must be created and the <strong>Hosted UI</strong> configured with a callback URL pointing to your FastAPI application (e.g., <a href="http://localhost:8000/authenticated).">http://localhost:8000/authenticated).</a></li></ul><p><strong>Project Configuration:</strong><br>First, clone the reference repository and install the dependencies.</p><pre>git clone https://github.com/soocrates/AWS-Cognito-with-Uvicorn.git<br>cd AWS-Cognito-with-Uvicorn<br>pip install -r requirements.txt</pre><p>Next, create a .env file in the project root to store your AWS Cognito credentials. This practice separates configuration from code, which is a security best practice.</p><pre># .env: Application Environment Configuration<br>CLIENT_ID=your_cognito_app_client_id<br>USERPOOL_ID=your_cognito_userpool_id<br>REGION=your_aws_region<br>HOSTED_UI_COGNITO_DOMAIN=your-domain.auth.region.amazoncognito.com<br>REDIRECT_URI=http://localhost:8000/authenticated</pre><h3>Step 2: Core Implementation Walkthrough</h3><p>The repository’s strength lies in its modular design, which separates distinct security concerns into dedicated files.</p><h4>server.py: The Application’s Entry Point</h4><p>This module defines the FastAPI application instance and its API endpoints. The /authenticated endpoint is the cornerstone of the login flow, responsible for executing the token exchange (Step 4).</p><pre># server.py (snippet)<br>@app.get(&quot;/authenticated&quot;)<br>def read_authenticated(response: Response, code: Optional[str] = None):<br>    # ... logic to prepare the token exchange request ...<br>    response_token = requests.post(token_endpoint, data=data, headers=headers)    if response_token.status_code == 200:<br>        response_data = response_token.json()<br>        response = RedirectResponse(url=&quot;/whoami/&quot;, status_code=303)<br>        # Set the access token in a secure, HttpOnly cookie<br>        response.set_cookie(<br>            key=&quot;access_token&quot;, <br>            value=response_data[&quot;access_token&quot;], <br>            httponly=True, <br>            secure=True, <br>            samesite=&#39;Lax&#39;<br>        )<br>        return response</pre><p>Protected routes leverage FastAPI’s dependency injection system, creating a clean and declarative security requirement.</p><pre># server.py (snippet)<br>@app.get(&quot;/protected-route&quot;)<br>async def protected_route(auth: bool = Depends(is_authenticated)):<br>    # This code only executes if is_authenticated succeeds<br>    return {&quot;message&quot;: &quot;Access granted to protected resource.&quot;}</pre><h4>auth.py: The Authentication Dependency</h4><p>This module provides the is_authenticated function, which serves as the gatekeeper for protected endpoints. It extracts the access_token from the request cookie and orchestrates its validation.</p><pre># auth.py (snippet)<br>async def is_authenticated(request: Request) -&gt; tuple[bool, dict]:<br>    access_token = request.cookies.get(&quot;access_token&quot;)<br>    if not access_token:<br>        raise HTTPException(status_code=401, detail=&quot;Authentication token is missing&quot;)# Delegate to the signature verification module<br>    verification_result = await signature_verification(access_token)<br>    if &quot;error&quot; in verification_result:<br>        raise HTTPException(status_code=401, detail=verification_result[&quot;error&quot;])<br>    <br>    # On success, retrieve and return user information<br>    user_info = retrive_user_information(access_token)<br>    return (True, user_info)</pre><h4>signature.py: The Vanguard of Verification</h4><p>This module handles the most critical security task: <strong>cryptographic signature verification</strong>. A JWT’s payload is readable, but its signature guarantees its authenticity and integrity. This function performs the standard verification process:</p><ol><li><strong>Fetch JWKS:</strong> It retrieves the JSON Web Key Set (JWKS) from your Cognito User Pool’s public .well-known/jwks.json endpoint. This file contains the public keys Cognito uses to sign its tokens.</li><li><strong>Key Matching:</strong> It identifies the correct public key by matching the kid (Key ID) from the incoming JWT’s header with a key in the JWKS.</li><li><strong>Decode and Verify:</strong> It uses the matched public key to decode the JWT. The decoding process cryptographically verifies the token’s signature, issuer (iss), and expiration time (exp).</li></ol><p>Any failure in this process, such as an expired token or an invalid signature, immediately invalidates the request.</p><h3>Step 3: Running the Application</h3><p>With the environment configured, execute the following command to start the Uvicorn server:</p><pre>uvicorn server:app --reload</pre><p>You can now initiate the authentication flow from your Cognito Hosted UI. Upon successful login, you will be redirected back to the application and can access protected endpoints like /whoami/ and /protected-route.</p><h3>Endpoints Overview</h3><ul><li>GET /: The root route returns a simple hello world message.</li><li>GET /authenticated: Handles the OAuth2 callback, exchanges the code for tokens, and sets up session cookies.</li><li>GET /whoami/: A protected route that displays the authenticated user&#39;s username and email.</li><li>GET /protected-route: Another example of a protected route, accessible only to authenticated users .</li><li>GET /logout: Clears the session cookies, effectively logging the user out</li></ul><h3>Conclusion:</h3><p>By integrating AWS Cognito with FastAPI using this modular, principled approach, you achieve more than just authentication. You build a foundation of trust. This architecture successfully offloads complex user management to a dedicated service, enforces a zero-trust policy by verifying every request, and protects user sessions with established security patterns like HttpOnly cookies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52942b673e6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Tagging Strategy: Best Practices, Policy Enforcement, and Automated Implementation]]></title>
            <link>https://medium.com/@roshanpoudel.me/aws-tagging-strategy-best-practices-policy-enforcement-and-automated-implementation-95071baf1bbb?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/95071baf1bbb</guid>
            <category><![CDATA[tagging-tactics]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-tagging]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Thu, 22 May 2025 03:19:13 GMT</pubDate>
            <atom:updated>2025-05-22T03:19:13.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd4fZFDP7QsDMULsTvLvSg.png" /></figure><p>Effective resource management and governance in cloud environments are crucial for ensuring smooth operations, cost optimization, and compliance. By adhering to this tagging convention, teams can improve visibility, track resource usage, and streamline automation processes.</p><p>This article outlines a structured tagging policy and introduces a Service Control Policy (SCP) designed to enforce mandatory tagging on AWS resources. By implementing this policy, organizations can improve visibility, support automation, and enhance accountability across their cloud infrastructure. Standardized tagging not only simplifies resource tracking and reporting but also strengthens security, cost allocation, and governance controls.</p><h3>Tag Discovery &amp; Implementation Directive</h3><p><strong>Discovery Phase</strong>:</p><ul><li>Conduct workshops with finance, governance, operations, and security teams to identify tagging requirements.</li><li>Document use cases (e.g., cost tracking, compliance, automation).</li></ul><p><strong>Design Phase</strong>:</p><ul><li>Develop the tagging schema and tag dictionary, incorporating mandatory, default, and service-specific tags.</li><li>Align with AWS Well-Architected Framework and Tagging Best Practices.</li></ul><p><strong>Implementation Phase</strong>:</p><ul><li>Apply tags via AWS Management Console, CLI, or IaC (e.g., Terraform, CloudFormation).</li><li>Integrate tagging into CI/CD pipelines for automated application.</li></ul><p><strong>Enforcement Phase</strong>:</p><ul><li>Deploy AWS Tag Policies and Service Control Policies (SCPs) to enforce tagging standards.</li><li>Automate tag validation and remediation using AWS Lambda and AWS Config.</li></ul><p><strong>Monitoring and Iteration</strong>:</p><ul><li>Monitor tagging compliance using AWS Resource Groups, AWS Cost Explorer, and custom reports.</li><li>Conduct quarterly reviews to update the schema based on business changes.</li></ul><h3>Teams Responsibility in Tagging Strategy</h3><ul><li><strong>Finance Team</strong>: Defines cost allocation tags (e.g., CostCenter, project) for budget tracking and cost optimization.</li><li><strong>Governance Team</strong>: Specifies compliance tags (e.g., compliance, data) to meet regulatory requirements.</li><li><strong>Operations Team</strong>: Implements tagging via Infrastructure as Code (IaC), CI/CD pipelines, and automation tools to ensure operational consistency.</li><li><strong>Security Team</strong>: Identifies security-related tags (e.g., owner, data) to enforce access controls and monitor sensitive resources.</li><li><strong>Stakeholders</strong>: Participate <strong>Stakeholders</strong> in quarterly reviews to refine the tagging strategy based on evolving business needs, ensuring the schema remains relevant.</li></ul><h3>SCP for Mandatory Tags</h3><p>This Service Control Policy (SCP) enforces mandatory tagging by denying the creation of AWS resources unless the required tags (environment, owner, and terraform) are present and meet specific value constraints. It helps ensure consistent resource tagging for cost allocation, compliance, and governance.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;DenyCreateWithoutMandatoryTags&quot;,<br>      &quot;Effect&quot;: &quot;Deny&quot;,<br>      &quot;Action&quot;: &quot;*&quot;,<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringNotEqualsIfExists&quot;: {<br>          &quot;aws:RequestTag/environment&quot;: [&quot;dev&quot;, &quot;stage&quot;, &quot;prod&quot;, &quot;test&quot;],<br>          &quot;aws:RequestTag/owner&quot;: &quot;*&quot;,<br>          &quot;aws:RequestTag/terraform&quot;: [&quot;true&quot;, &quot;false&quot;]<br>        },<br>        &quot;Null&quot;: {<br>          &quot;aws:RequestTag/environment&quot;: &quot;true&quot;,<br>          &quot;aws:RequestTag/owner&quot;: &quot;true&quot;,<br>          &quot;aws:RequestTag/terraform&quot;: &quot;true&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><ul><li>A <strong>deny list</strong> — actions are allowed by default, and you specify what services and actions are prohibited.</li><li>An <strong>allow list</strong> — actions are prohibited by default, and you specify what services and actions are allowed.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8532c587445f737a08702732688f9a/href">https://medium.com/media/6e8532c587445f737a08702732688f9a/href</a></iframe><h3>Mandatory Tags via Terraform</h3><p>The tagging strategy is implemented using the default_tags feature within the Terraform AWS provider. This ensures that every resource created through this provider automatically inherits a standardized set of tags, promoting consistency across the environment. The tags are defined centrally in a locals block and include business-critical metadata such as environment, project, createdby, compliance, and more. This approach aligns with AWS tagging best practices and enables automation, traceability, and cost management through infrastructure-as-code.</p><pre>provider &quot;aws&quot; {<br>  region = var.region<br><br>  default_tags {<br>    tags = local.common.tags<br>  }<br>}<br><br>locals {<br>  project     = &quot;project_name&quot;<br>  name_prefix = module.naming.resources.prefix.name<br>  region      = var.region<br><br>  # Common tags applied automatically at the provider level<br>  common = {<br>    tags = {<br>      environment = var.environment<br>      terraform   = true<br>      project     = &quot;modelpeeps&quot;<br>      createdby   = &quot;Github OIDC&quot;<br>      compliance  = &quot;SOC2&quot;<br>    }<br>  }<br>}</pre><h3>Notes:</h3><ol><li><strong>Consistency:</strong> Always ensure that tag values are consistent across resources for effective management and reporting.</li><li><strong>Enforcement:</strong> Tagging policies should be enforced at the organizational level to ensure standardization across environments.</li><li><strong>Automation:</strong> Consider automating the tagging process within your CI/CD pipeline to reduce manual errors and ensure consistent application of tags.</li></ol><h3>Conclusion</h3><p>Establishing and enforcing a consistent tagging strategy is vital for achieving transparency, operational control, and compliance in a cloud environment. The mandatory tagging SCP presented in this document ensures that all newly created resources include critical metadata such as environment, ownership, and provisioning details thereby supporting better governance and decision-making.</p><p>Adopting these tagging conventions and integrating them into organizational workflows and CI/CD pipelines will drive efficiency, reduce manual overhead, and maintain alignment with security and compliance standards.</p><p>In the long term, this structured approach will enhance resource lifecycle management, simplify audits, and support scalable cloud operations across teams and environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95071baf1bbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Docker: From Containerization Basics to Node.js Deployment]]></title>
            <link>https://medium.com/@roshanpoudel.me/master-docker-from-containerization-basics-to-node-js-deployment-c3711572d5f8?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3711572d5f8</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-best-practices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 08:22:58 GMT</pubDate>
            <atom:updated>2025-04-28T08:22:58.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2sD-HkC7uzfdIbIi" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s fast-paced tech landscape, understanding containerization is crucial. Docker, a leading containerization platform, empowers developers to package applications with all their dependencies, ensuring consistent performance across various environments. Whether you’re a student embarking on your tech journey or an intermediate professional aiming to enhance your skills, this guide will walk you through Docker’s essentials, from basic commands to deploying a Node.js application.</p><h3>Understanding Docker: The Basics</h3><p>Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization. Containers are lightweight, standalone, and executable packages that include everything needed to run a piece of software, including code, runtime, system tools, libraries, and settings.</p><p><strong>Key Advantages of Docker:</strong></p><ul><li><strong>Portability:</strong> Run applications seamlessly across different environments.</li><li><strong>Efficiency:</strong> Containers share the host system’s kernel, making them more efficient than traditional virtual machines.</li><li><strong>Scalability:</strong> Easily scale applications horizontally by adding more containers.</li></ul><h3>Essential Docker Commands</h3><p>Familiarizing yourself with Docker’s command-line interface (CLI) is fundamental. Here’s a breakdown of essential commands:</p><p><strong>1. Listing Containers and Images</strong></p><ul><li>docker ps: Lists all running containers.</li><li>docker ps -a: Lists all containers, including those that are stopped.</li><li>docker images: Displays all images stored locally.</li></ul><p><strong>2. Managing Containers</strong></p><ul><li>docker rm &lt;container_id&gt;: Removes a specific container.</li><li>docker start &lt;container_name&gt;: Starts a stopped container.</li><li>docker stop &lt;container_name&gt;: Stops a running container.</li></ul><p><strong>3. Managing Images</strong></p><ul><li>docker rmi &lt;image_id&gt;: Removes a specific image from the local storage.</li></ul><p><strong>4. Running Containers</strong></p><ul><li>docker run -it &lt;image_name&gt;: Runs a container in interactive mode.</li><li>docker run -it -p &lt;host_port&gt;:&lt;container_port&gt; &lt;image_name&gt;: Runs a container with port mapping.</li><li>docker run -it -p 8080:8080 -e KEY=VALUE &lt;image_name&gt;: Runs a container with environment variables.</li></ul><p><strong>5. Executing Commands Inside Containers</strong></p><ul><li>docker exec &lt;container_name&gt; ls: Executes the ls command inside the container.</li><li>docker exec -it &lt;container_name&gt; bash: Opens an interactive bash shell inside the container.</li></ul><p><strong>6. Monitoring Containers</strong></p><ul><li>docker container stats: Displays real-time statistics of container resource usage.</li></ul><h3>Building Custom Docker Images</h3><p>Creating custom Docker images allows you to define your application’s environment precisely. This is particularly useful when working in teams to ensure consistency across development and production environments.</p><p><strong>Steps to Build a Custom Image:</strong></p><ol><li><strong>Create a Dockerfile:</strong> This file contains instructions to assemble the image.</li><li><strong>Choose a Base Image:</strong> Start with a minimal base, such as ubuntu or node.</li><li><strong>Install Dependencies:</strong> Use RUN commands to install necessary packages.</li><li><strong>Copy Application Files:</strong> Use COPY to add your application code to the image.</li><li><strong>Set Environment Variables:</strong> Use ENV to define environment-specific variables.</li><li><strong>Define Entry Point:</strong> Use ENTRYPOINT or CMD to specify the default command.</li></ol><p><strong>Example Scenario: </strong>Imagine working with a team where developers have different roles. To streamline development, you can create a custom image that includes Ubuntu, Node.js, MongoDB, Redis, and other necessary binaries. This image can be pushed to Docker Hub and used across various environments, ensuring consistency and reducing setup time.</p><h3>Deploying a Node.js Application with Docker</h3><p>Let’s walk through deploying a simple Node.js application using Docker.</p><p><strong>1. Create the Application Files </strong>main.js.</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = process.env.PORT || 8000;<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>    res.json({ message: &quot;Hello World from container&quot; });<br>});<br><br>app.listen(PORT, () =&gt; {<br>    console.log(`Server is running on port ${PORT}`);<br>});</pre><p>package.json:</p><pre>{<br>  &quot;name&quot;: &quot;docker-node&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;main.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node main.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^5.1.0&quot;<br>  }<br>}</pre><p><strong>2. Create the Dockerfile</strong></p><pre># Base image<br>FROM ubuntu# Install Node.js<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y curl &amp;&amp; \<br>    curl -sL https://deb.nodesource.com/setup_18.x | bash - &amp;&amp; \<br>    apt-get install -y nodejs<br><br># Set working directory<br>WORKDIR /app<br><br># Copy application files<br>COPY package.json .<br>COPY main.js .<br><br># Install dependencies<br>RUN npm install<br><br># Expose port<br>EXPOSE 8000<br><br># Define entry point<br>ENTRYPOINT [&quot;node&quot;, &quot;main.js&quot;]</pre><p><strong>3. Build and Run the Docker Image</strong></p><ul><li>Build the image: docker build -t node_app .</li><li>Run the container: docker run -d -p 8000:8000 node_app</li></ul><p>Access the application by navigating to http://localhost:8000 in your browser.</p><h4>CMD vs. ENTRYPOINT in Docker</h4><p>Understanding the difference between CMD and ENTRYPOINT is crucial when defining the behavior of your Docker containers.</p><ul><li><strong>CMD:</strong> Provides default arguments for the ENTRYPOINT instruction. It can be overridden at runtime.</li><li><strong>ENTRYPOINT:</strong> Sets the main command to run when the container starts. It’s not easily overridden.</li></ul><p><strong>Best Practice:</strong> Use ENTRYPOINT to define the executable and CMD to provide default parameters.</p><h3>Monitoring and Managing Containers</h3><p>Efficiently managing and monitoring your containers ensures optimal performance.</p><ul><li><strong>View Running Container: </strong>docker ps</li><li><strong>View All Containers: </strong>docker ps -a</li><li><strong>Inspect a Container: </strong>docker inspect &lt;container_name&gt;</li><li><strong>View Logs: </strong>docker logs &lt;container_name&gt;</li><li><strong>Monitor Resource Usage: </strong>docker container stats</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*m_ykWbZvImdgCwmkMhMhvA.png" /></figure><p>Learning Docker might feel overwhelming at first, but with a little practice, it quickly becomes second nature. By mastering a few key commands and building your own custom images, you’ll open up a world of possibilities for your projects. Whether you’re just starting out or leveling up your tech skills, Docker can make your development journey smoother and way more fun. Keep experimenting, stay curious, and soon you’ll be deploying apps like a pro!</p><p>Looking for your comments, suggestions and improvements and let’s connect on <a href="https://www.linkedin.com/in/roshan-poudel832/"><strong>LinkedIn </strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3711572d5f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS EC2 Best Practices]]></title>
            <link>https://medium.com/@roshanpoudel.me/aws-ec2-best-practices-c8c5a73ce08d?source=rss-1998c448e05c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c5a73ce08d</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rightsizing]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Roshan Poudel]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 11:22:12 GMT</pubDate>
            <atom:updated>2025-04-23T11:22:12.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*d0VJkz5XSw-ZLkyfxRzaew.png" /></figure><p>Amazon EC2 (Elastic Compute Cloud) is one of the most powerful and flexible services AWS offers. It allows you to run virtual machines in the cloud, scaling your infrastructure as your application grows. But with great power comes great responsibility. Poor EC2 management can lead to unexpected costs, performance bottlenecks, and security vulnerabilities. In this guide, we dive deep into the best practices for EC2, helping you run more secure, scalable, and cost-effective workloads.</p><h4>1. Choose the Right Instance Type and Size</h4><p>AWS provides a wide variety of EC2 instance types optimized for different use cases: general purpose, compute-optimized, memory-optimized, storage-optimized, and accelerated computing. Start by analyzing your workload requirements — do you need high CPU, large RAM, or fast storage?</p><ul><li>Use the <a href="https://instance-selector.aws/">AWS Instance Selector</a> or performance testing to match your application with the ideal instance type.</li><li>Leverage instance families like <strong>M6i</strong> for general-purpose, <strong>C7g</strong> for compute-intensive, and <strong>R6i</strong> for memory-bound workloads.</li><li>Always test your workload on different instance types before settling.</li></ul><h4>2. Use Auto Scaling for High Availability and Cost Control</h4><p>Auto Scaling helps you maintain application availability and scale your EC2 fleet up or down according to conditions you define.</p><ul><li>Create launch templates or configurations for consistent instance setup.</li><li>Define scaling policies based on metrics such as CPU usage or application load.</li><li>Combine Auto Scaling with Elastic Load Balancing to distribute traffic efficiently.</li></ul><h4>3. Right-Size and Optimize Costs</h4><p>Underutilized instances can burn a hole in your budget.</p><ul><li>Regularly analyze usage using <strong>AWS Cost Explorer</strong> or <strong>Compute Optimizer</strong>.</li><li>Use <strong>Reserved Instances (RI)</strong> or <strong>Savings Plans</strong> for predictable workloads.</li><li>For fault-tolerant and flexible workloads, use <strong>Spot Instances</strong> — they offer up to 90% savings.</li></ul><h4>4. Secure Your EC2 Instances</h4><p>Security should be top priority when working with EC2.</p><ul><li><strong>Security Groups</strong> act as virtual firewalls — apply the principle of least privilege.</li><li><strong>Use SSH key pairs</strong> instead of passwords and disable root login where possible.</li><li><strong>Patch your OS and software</strong> regularly or use AWS Systems Manager Patch Manager.</li><li>Avoid hardcoding credentials — use <strong>IAM roles</strong> to grant temporary, least-privilege access to AWS services.</li></ul><h4>5. Implement Robust Monitoring and Logging</h4><p>Monitoring helps you detect issues before they impact your application.</p><ul><li>Use <strong>Amazon CloudWatch</strong> to monitor metrics like CPU utilization, disk I/O, and network traffic.</li><li>Set up <strong>CloudWatch Alarms</strong> for threshold-based notifications.</li><li>Enable <strong>CloudTrail</strong> to log all API activity and <strong>VPC Flow Logs</strong> for network traffic analysis.</li></ul><h4>6. Automate Configuration and Management</h4><p>Manual processes can introduce inconsistency and human error.</p><ul><li>Use <strong>EC2 User Data</strong> to automate boot-time configuration.</li><li>Manage instances at scale with <strong>AWS Systems Manager</strong> — run commands, collect inventory, and patch.</li><li>Use <strong>Infrastructure as Code (IaC)</strong> tools like CloudFormation or Terraform for repeatable deployments.</li></ul><h4>7. Manage Storage Wisely</h4><p>Storage choices directly impact performance and cost.</p><ul><li>Select the right <strong>EBS volume type</strong> (e.g., gp3 for general purpose, io2 for high IOPS).</li><li>Take regular <strong>EBS snapshots</strong> for backup and recovery.</li><li>Monitor storage usage and delete unattached volumes.</li></ul><h4>8. Tag Resources for Management and Cost Allocation</h4><p>Tagging is essential for visibility and organization.</p><ul><li>Apply consistent tags for environment, project, owner, and cost center.</li><li>Use <strong>AWS Resource Groups</strong> and <strong>Cost Allocation Reports</strong> to track and manage EC2 resources effectively.</li></ul><h3>Conclusion</h3><p>Managing EC2 effectively is a balance of performance, cost, security, and automation. By applying these best practices, you can ensure your workloads are reliable, secure, and efficient. Whether you’re running a single server or managing a large fleet, these principles form the foundation for successful cloud operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c5a73ce08d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>