<?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 Aladejana, Emmanuel Abiodun on Medium]]></title>
        <description><![CDATA[Stories by Aladejana, Emmanuel Abiodun on Medium]]></description>
        <link>https://medium.com/@eaaladejana?source=rss-fb0a020ee2c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qaIDypnYEqE0bhPHDwjH0w.jpeg</url>
            <title>Stories by Aladejana, Emmanuel Abiodun on Medium</title>
            <link>https://medium.com/@eaaladejana?source=rss-fb0a020ee2c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:11:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eaaladejana/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[Stop Babysitting Your Storage: My 15-Minute AWS Auto-Scaling Solution]]></title>
            <link>https://medium.com/@eaaladejana/stop-babysitting-your-storage-my-15-minute-aws-auto-scaling-solution-51708dc6dac7?source=rss-fb0a020ee2c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/51708dc6dac7</guid>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aladejana, Emmanuel Abiodun]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 15:55:11 GMT</pubDate>
            <atom:updated>2024-11-03T15:55:11.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEFC1cibTPD52AFbF1wM4w.jpeg" /></figure><p>Hey there! 👋 Let me walk you through something incredibly cool — automatic EBS volume resizing for your AWS Auto Scaling Groups. You know that panic when your disk space starts running low? We’re going to make that a thing of the past by building a completely automated solution.</p><p>Think of this as giving your AWS infrastructure a smart brain that:</p><ol><li>Watches your disk space like a hawk 🦅</li><li>Spots when things are getting tight</li><li>Automatically grows your storage before it becomes a problem</li></ol><p>The best part? Once we set this up, it just works. Forever. Let’s dive in!</p><h3>Step 1: Setting Up Our Disk Space Monitor 🔍</h3><p>First, we need to give our EC2 instances the power to report their disk usage. It’s like installing a smart meter in your house — it needs to be there before we can do anything clever with the readings.</p><p>SSH into one of your ASG instances:</p><pre>ssh -i &lt;your-key&gt; user@address</pre><p>Now, let’s install our monitoring agent. Copy these commands exactly:</p><pre>wget https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb<br>sudo dpkg -i -E ./amazon-cloudwatch-agent.deb<br>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard<br>sudo systemctl start amazon-cloudwatch-agent</pre><p>Next, you can create a new image from the ec2 instance and add to your ASG Launch Template as a new version, or you setup SSM Manager to install and setup the CloudWatch Agent on your entire ASG!</p><p>🚨 Pro Tip: Don’t forget to attach the CloudWatchAgentServerPolicy to your instance! This is giving permission to send readings back to AWS.</p><p>Here’s a gotcha that could save you time of debugging: If you’re in a corporate environment and get permission errors while creating IAM roles, start fresh with a new role. Even if an error-prone role appears to work in the console, it might be secretly broken.</p><h3>Step 2: Creating Our Data Collector Function 🤖</h3><p>Let’s create a Lambda function that will be our central data collector. Think of it as the brain that:</p><ol><li>Keeps track of all your EC2 instances</li><li>Gathers their disk usage data</li><li>Calculates averages to make smart decisions</li></ol><p>Here’s where we create listFetchCalAvgPub — a Lambda function that’s way smarter than its somewhat awkward name suggests. This is essentially your disk space surveillance system.</p><p>Head to AWS Lambda and create a new function with Python 3.9. Here’s the code that makes the magic happen:</p><pre>import boto3<br>from datetime import datetime, timedelta<br>import logging<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br>def lambda_handler(event, context):<br> # Initialize our AWS toolset<br> ec2 = boto3.client(&#39;ec2&#39;)<br> asg = boto3.client(&#39;autoscaling&#39;)<br> cw = boto3.client(&#39;cloudwatch&#39;)<br> <br> # Replace this with your ASG name<br> asg_name = &#39;EndowdAutoScalingGroup&#39;</pre><p>This initializes our AWS toolset and ASG name.</p><pre>response = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])<br> <br> if not response[‘AutoScalingGroups’]:<br> logger.warning(f”No ASG found with name: {asg_name}”)<br> return {<br> ‘statusCode’: 404,<br> ‘body’: f’ASG {asg_name} not found’<br> }</pre><p>This code is like a safety net — it makes sure your ASG actually exists before trying to do anything fancy.</p><p>Here’s where it gets interesting:</p><pre>metrics = []<br> for instance_id, private_ip in instance_ips.items():<br> response = cw.get_metric_statistics(<br> Namespace=’CWAgent’,<br> MetricName=’disk_used_percent’,<br> Dimensions=[<br> {‘Name’: ‘host’, ‘Value’: f’ip-{private_ip.replace(“.”, “-”)}’},<br> {‘Name’: ‘path’, ‘Value’: ‘/’},<br> {‘Name’: ‘device’, ‘Value’: ‘nvme0n1p1’},<br> {‘Name’: ‘fstype’, ‘Value’: ‘ext4’}<br> ],<br> StartTime=start_time,<br> EndTime=end_time,<br> Period=300,<br> Statistics=[‘Average’]<br> )</pre><p>This part is crucial — it’s checking each instance’s disk usage with incredible precision. It’s like having a microscope for your storage usage! 🔬</p><p>And finally, we calculate the average disk usage metric for the whole ASG! But wait! There’s more — we also publish these as custom metrics to CloudWatch</p><pre>if metrics:<br> avg_disk_usage = round(sum(metrics) / len(metrics), 2)<br> logger.info(f”Average disk usage calculated: {avg_disk_usage}%”)<br> <br> cw.put_metric_data(<br> Namespace=’CustomASGMetrics’,<br> MetricData=[<br> {<br> ‘MetricName’: ‘AverageDiskUsagePercent’,<br> ‘Dimensions’: [<br> {‘Name’: ‘AutoScalingGroupName’, ‘Value’: asg_name},<br> ],<br> ‘Value’: avg_disk_usage,<br> ‘Unit’: ‘Percent’<br> },<br> ]<br> )</pre><p>This function is like having a super-smart assistant that:</p><ol><li>Knows about every instance in your ASG</li><li>Checks their disk usage</li><li>Does the math to figure out if you’re heading for trouble</li></ol><p>Full code:</p><pre>import boto3<br>from datetime import datetime, timedelta<br>import logging<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br>def lambda_handler(event, context):<br>   ec2 = boto3.client(&#39;ec2&#39;)<br>   asg = boto3.client(&#39;autoscaling&#39;)<br>   cw = boto3.client(&#39;cloudwatch&#39;)<br> <br>   asg_name = &#39;EndowdAutoScalingGroup&#39;<br>   response = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])<br> <br>   if not response[&#39;AutoScalingGroups&#39;]:<br>       logger.warning(f&quot;No ASG found with name: {asg_name}&quot;)<br>       return {<br>           &#39;statusCode&#39;: 404,<br>           &#39;body&#39;: f&#39;ASG {asg_name} not found&#39;<br>       }<br>       <br>   instances = response[&#39;AutoScalingGroups&#39;][0][&#39;Instances&#39;]<br>   if not instances:<br>       logger.info(f&quot;ASG {asg_name} exists but has no instances&quot;)<br>       return {<br>           &#39;statusCode&#39;: 200,<br>           &#39;body&#39;: f&#39;ASG {asg_name} has no instances&#39;<br>       }<br> <br>   instance_ids = [i[&#39;InstanceId&#39;] for i in instances]<br>   logger.info(f&quot;Found {len(instance_ids)} instances in ASG {asg_name}&quot;)<br> <br>   ec2_info = ec2.describe_instances(InstanceIds=instance_ids)<br>   instance_ips = {instance[&#39;InstanceId&#39;]: instance[&#39;PrivateIpAddress&#39;] <br>               for reservation in ec2_info[&#39;Reservations&#39;] <br>               for instance in reservation[&#39;Instances&#39;]}<br> <br>   end_time = datetime.utcnow()<br>   start_time = end_time - timedelta(minutes=10)<br><br>   metrics = []<br>   for instance_id, private_ip in instance_ips.items():<br>       response = cw.get_metric_statistics(<br>           Namespace=&#39;CWAgent&#39;,<br>           MetricName=&#39;disk_used_percent&#39;,<br>           Dimensions=[<br>               {&#39;Name&#39;: &#39;host&#39;, &#39;Value&#39;: f&#39;ip-{private_ip.replace(&quot;.&quot;, &quot;-&quot;)}&#39;},<br>               {&#39;Name&#39;: &#39;path&#39;, &#39;Value&#39;: &#39;/&#39;},<br>               {&#39;Name&#39;: &#39;device&#39;, &#39;Value&#39;: &#39;nvme0n1p1&#39;},<br>               {&#39;Name&#39;: &#39;fstype&#39;, &#39;Value&#39;: &#39;ext4&#39;}<br>               ],<br>               StartTime=start_time,<br>               EndTime=end_time,<br>               Period=300,<br>               Statistics=[&#39;Average&#39;]<br>           )<br>           logger.info(f&quot;Metric response for instance {instance_id} (IP: {private_ip}): {response}&quot;)<br>           if response[&#39;Datapoints&#39;]:<br>               metrics.append(response[&#39;Datapoints&#39;][0][&#39;Average&#39;])<br>           else:<br>               logger.warning(f&quot;No datapoints found for instance {instance_id} (IP: {private_ip})&quot;)<br>               <br>   if metrics:<br>       avg_disk_usage = round(sum(metrics) / len(metrics), 2)<br>       logger.info(f&quot;Average disk usage calculated: {avg_disk_usage}%&quot;)<br>     <br>       cw.put_metric_data(<br>           Namespace=&#39;CustomASGMetrics&#39;,<br>           MetricData=[<br>               {<br>                   &#39;MetricName&#39;: &#39;AverageDiskUsagePercent&#39;,<br>                   &#39;Dimensions&#39;: [<br>                   {&#39;Name&#39;: &#39;AutoScalingGroupName&#39;, &#39;Value&#39;: asg_name},<br>                   ],<br>                   &#39;Value&#39;: avg_disk_usage,<br>                   &#39;Unit&#39;: &#39;Percent&#39;<br>               },<br>           ]<br>       )<br>       return {<br>           &#39;statusCode&#39;: 200,<br>           &#39;body&#39;: f&#39;Published average disk usage: {avg_disk_usage}%&#39;<br>       }<br>   else:<br>       logger.warning(&quot;No metrics data found for any instances&quot;)<br>       return {<br>           &#39;statusCode&#39;: 200,<br>           &#39;body&#39;: &#39;No disk usage data available for any instances&#39;<br>       }</pre><p>After we’ve created the function, we need to give it the right permissions. Think of this as giving your assistant the right security badges:</p><ol><li>Go to IAM</li><li>Find your listFetchCalcAvgPub-xxxxxx role</li><li>Add these crucial permissions:</li></ol><ul><li>AmazonEC2ReadOnlyAccess</li><li>AutoScalingReadOnlyAccess</li><li>CloudWatchFullAccessV2</li></ul><h3>Step 3: Setting Up Our Schedule ⏰</h3><p>Now we need to make sure our function runs regularly. We’ll use EventBridge (formerly CloudWatch Events) to run our function every 5 minutes. It’s like setting up an extremely reliable alarm clock.</p><p>Ready to set up the schedule? I’ll walk you through creating the EventBridge trigger next</p><p><strong>Pro tip: </strong>The 5-minute interval is a sweet spot between getting timely data and not overwhelming your CloudWatch metrics. In production, you might want to adjust this based on how quickly your disk space typically fills up.</p><p>Okay, let’s set up that reliable scheduling system and then move on to the really exciting part — the automatic scaling trigger!</p><p>Here’s how to set up your schedule (it’s actually pretty straightforward):</p><ol><li>Go to EventBridge console</li><li>Find Scheduler: Schedules in the navigation</li><li>Click Create schedule and follow this exact setup:</li></ol><ul><li>Name: “trigger-disk-usage-lambda” (or something equally descriptive)</li><li>Schedule pattern: “Recurring schedule”</li><li>Schedule type: “Rate-based schedule”</li><li>Rate: 5 minutes</li><li>Flexible time window: OFF (we want precision!)</li><li>Start time: Set it 1 minute in the future</li></ul><p>🎯 Target setup:</p><ul><li>Choose “AWS Lambda Invoke”</li><li>Select your listFetchCalAvgPub function</li><li>Leave payload empty</li><li>Let it create a new execution role</li></ul><h3>Step 4: Building Our Scaling Trigger 🚀</h3><p>Now for the exciting part — the ebs-scaling-trigger-asg Lambda function. This is like the commander that orders your EBS volumes to grow when needed. Here’s the intelligent code that makes it happen:</p><p>This function is super smart — it does several critical things:</p><ol><li>Identifies instances that are running out of space</li><li>Makes intelligent decisions about when to scale</li><li>Triggers the actual scaling process through Step Functions</li></ol><pre>import json<br>import boto3<br>from datetime import datetime, timedelta<br><br>def json_serial(obj):<br>     &quot;&quot;&quot;JSON serializer for objects not serializable by default json code&quot;&quot;&quot;<br>     if isinstance(obj, (datetime, timedelta)):<br>         return obj.isoformat()<br>     raise TypeError(f&quot;Type {type(obj)} not serializable&quot;)<br><br>def get_instances_exceeding_threshold(asg_name, threshold):<br>     ec2 = boto3.client(&#39;ec2&#39;)<br>     asg = boto3.client(&#39;autoscaling&#39;)<br>     cw = boto3.client(&#39;cloudwatch&#39;)</pre><p>This initializes our AWS toolset.</p><p>Here’s where it gets really clever:</p><pre>high_usage_instances = []<br> #####<br>       response = cw.get_metric_statistics(**query_params)<br>       print(f”Metric response for {instance_id}: {json.dumps(response, default=json_serial)}”)<br>       <br>       if response[‘Datapoints’]:<br>           latest_datapoint = max(response[‘Datapoints’], key=lambda x: x[‘Timestamp’])<br>           if latest_datapoint[‘Average’] &gt;= threshold:<br>               high_usage_instances.append(instance_id)<br>               print(f”Instance {instance_id} exceeds threshold: {latest_datapoint[‘Average’]}%”)<br>           else:<br>               print(f”Instance {instance_id} below threshold: {latest_datapoint[‘Average’]}%”)<br>       else:<br>           print(f”No datapoints found for instance {instance_id}”)<br> <br> return high_usage_instances<br><br>def lambda_handler(event, context):<br>     print(&quot;Received event:&quot;, json.dumps(event))<br>     <br>     asg_name = &#39;EndowdAutoScalingGroup&#39;<br>     threshold = 80<br>     <br>     high_usage_instances = get_instances_exceeding_threshold(asg_name, threshold)<br>     <br>     sf_client = boto3.client(&#39;stepfunctions&#39;)<br>     sf_arn = &#39;arn:aws:states:us-east-1:&lt;account-id&gt;:stateMachine:ebs-auto-scaling-asg&#39;<br>     <br>     for instance_id in high_usage_instances:<br>         try:<br>             response = sf_client.start_execution(<br>                 stateMachineArn=sf_arn,<br>                 input=json.dumps({&#39;instance_id&#39;: instance_id})<br>         )<br>         print(f&quot;Started scaling process for instance {instance_id}: {json.dumps(response, default=json_serial)}&quot;)</pre><p>This code is like having a smart assistant (lots of assistants, right! 😅) that:</p><ul><li>Checks each instance individually</li><li>Gets detailed information about its current state</li><li>Decides if it needs attention</li><li>Runs step function for each instance exceeding threshold</li></ul><p>Full code:</p><pre>import json<br>import boto3<br>from datetime import datetime, timedelta<br><br>def json_serial(obj):<br>     &quot;&quot;&quot;JSON serializer for objects not serializable by default json code&quot;&quot;&quot;<br>     if isinstance(obj, (datetime, timedelta)):<br>     return obj.isoformat()<br>     raise TypeError(f&quot;Type {type(obj)} not serializable&quot;)<br><br>def get_instances_exceeding_threshold(asg_name, threshold):<br>     ec2 = boto3.client(&#39;ec2&#39;)<br>     asg = boto3.client(&#39;autoscaling&#39;)<br>     cw = boto3.client(&#39;cloudwatch&#39;)<br> <br>     print(f&quot;Checking ASG: {asg_name} for instances exceeding {threshold}%&quot;)<br>     <br>     try:<br>         response = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])<br>         instances = response[&#39;AutoScalingGroups&#39;][0][&#39;Instances&#39;]<br>         print(f&quot;Found {len(instances)} instances in the ASG&quot;)<br>     except Exception as e:<br>         print(f&quot;Error getting ASG instances: {str(e)}&quot;)<br>         return []<br> <br>     high_usage_instances = []<br>     for instance in instances:<br>         instance_id = instance[&#39;InstanceId&#39;]<br>         try:<br>             ec2_info = ec2.describe_instances(InstanceIds=[instance_id])<br>             private_ip = ec2_info[&#39;Reservations&#39;][0][&#39;Instances&#39;][0][&#39;PrivateIpAddress&#39;]<br>             print(f&quot;Checking instance {instance_id} with IP {private_ip}&quot;)<br>     <br>             query_params = {<br>                 &#39;Namespace&#39;: &#39;CWAgent&#39;,<br>                 &#39;MetricName&#39;: &#39;disk_used_percent&#39;,<br>                 &#39;Dimensions&#39;: [<br>                     {&#39;Name&#39;: &#39;host&#39;, &#39;Value&#39;: f&quot;ip-{private_ip.replace(&#39;.&#39;, &#39;-&#39;)}&quot;},<br>                     {&#39;Name&#39;: &#39;path&#39;, &#39;Value&#39;: &#39;/&#39;},<br>                     {&#39;Name&#39;: &#39;device&#39;, &#39;Value&#39;: &#39;nvme0n1p1&#39;},<br>                     {&#39;Name&#39;: &#39;fstype&#39;, &#39;Value&#39;: &#39;ext4&#39;}<br>                 ],<br>                 &#39;StartTime&#39;: datetime.utcnow() - timedelta(minutes=30),<br>                 &#39;EndTime&#39;: datetime.utcnow(),<br>                 &#39;Period&#39;: 300,<br>                 &#39;Statistics&#39;: [&#39;Average&#39;]<br>             }<br>             print(f&quot;CloudWatch query params: {json.dumps(query_params, default=json_serial)}&quot;)<br> <br>             response = cw.get_metric_statistics(**query_params)<br>             print(f&quot;Metric response for {instance_id}: {json.dumps(response, default=json_serial)}&quot;)<br> <br>             if response[&#39;Datapoints&#39;]:<br>                 latest_datapoint = max(response[&#39;Datapoints&#39;], key=lambda x: x[&#39;Timestamp&#39;])<br>                 if latest_datapoint[&#39;Average&#39;] &gt;= threshold:<br>                     high_usage_instances.append(instance_id)<br>                     print(f&quot;Instance {instance_id} exceeds threshold: {latest_datapoint[&#39;Average&#39;]}%&quot;)<br>                 else:<br>                 print(f&quot;Instance {instance_id} below threshold: {latest_datapoint[&#39;Average&#39;]}%&quot;)<br>             else:<br>                 print(f&quot;No datapoints found for instance {instance_id}&quot;)<br>         except Exception as e:<br>             print(f&quot;Error processing instance {instance_id}: {str(e)}&quot;)<br>             import traceback<br>             print(traceback.format_exc())<br> <br>     return high_usage_instances<br><br>def lambda_handler(event, context):<br>     print(&quot;Received event:&quot;, json.dumps(event))<br>     <br>     asg_name = &#39;EndowdAutoScalingGroup&#39;<br>     threshold = 80<br>     <br>     high_usage_instances = get_instances_exceeding_threshold(asg_name, threshold)<br>     <br>     sf_client = boto3.client(&#39;stepfunctions&#39;)<br>     sf_arn = &#39;arn:aws:states:us-east-1:821675588512:stateMachine:ebs-auto-scaling-asg&#39;<br> <br>     for instance_id in high_usage_instances:<br>         try:<br>             response = sf_client.start_execution(<br>               stateMachineArn=sf_arn,<br>               input=json.dumps({&#39;instance_id&#39;: instance_id})<br>         )<br>         print(f&quot;Started scaling process for instance {instance_id}: {json.dumps(response, default=json_serial)}&quot;)<br>     except Exception as e:<br>         print(f&quot;Error starting step function for instance {instance_id}: {str(e)}&quot;)<br>         import traceback<br>         print(traceback.format_exc())<br> <br>     return {<br>     &#39;statusCode&#39;: 200,<br>     &#39;body&#39;: json.dumps(f&#39;Started scaling process for {len(high_usage_instances)} instances&#39;)<br> }</pre><p>🔑 Don’t forget the permissions! Add these to your function’s IAM role:</p><ul><li>AmazonEC2ReadOnlyAccess</li><li>AutoScalingReadOnlyAccess</li><li>AWSStepFunctionsFullAccess</li></ul><h3>Step 5: Setting Up the Alarm System 🚨</h3><p>Now we need to create a CloudWatch Alarm that will be our early warning system. This is crucial — it’s what triggers our scaling function before things get critical.</p><p>Let me guide you through the CloudWatch Alarm configuration and then move on to the final step — the Step Function that orchestrates the actual volume resizing!</p><p>This CloudWatch Alarm is like having a super-attentive assistant that never sleeps. Here’s how to set it up:</p><ol><li>Head to CloudWatch -&gt; All alarms</li><li>Click “Create alarm” and follow these crucial steps:</li></ol><ul><li>Select CustomASGMetrics namespace</li><li>Drill down to AutoScalingGroupName</li><li>Pick your ASG name</li></ul><p>3. Now for the smart part — configure these settings:</p><ul><li>Statistics: average (smooths out spikes)</li><li>Period: 1 minute (quick reaction time)</li><li>Threshold type: static</li><li>Condition: greater than/equal to</li><li>Threshold: Pick between 50–90% (I recommend 80% — gives you breathing room while avoiding false alarms)</li></ul><p>🧠 <strong>Pro tip:</strong> The threshold choice is crucial. Too low (50%) triggers unnecessary scaling, too high (90%) might not give you enough reaction time. 80% is usually the sweet spot.</p><h3>Step 6: The Grand Finale — Step Functions 🎭</h3><p>This is where everything comes together! The Step Function is like an automation orchestra conductor, ensuring each scaling operation happens in perfect sequence.</p><p>Your Step Function will:</p><ol><li>Take the instance ID from our trigger</li><li>Execute a series of precise steps to grow the EBS volume</li><li>Ensure the filesystem is properly extended</li><li>Verify everything worked correctly</li></ol><p><strong>Remember:</strong> <strong>The Step Function from the </strong><a href="https://medium.com/@eaaladejana/how-i-never-worry-about-aws-storage-my-ebs-automation-secrets-40b83c5a280c"><strong>previous article</strong></a><strong> is crucial here — it’s the actual engine that performs the resizing operations.</strong></p><p>So now we have a complete, intelligent system that:</p><ul><li>Constantly monitors disk usage across your entire ASG</li><li>Automatically detects when any instance needs more space</li><li>Triggers a precise, automated scaling operation</li><li>Handles all the complex volume and filesystem operations without human intervention</li></ul><p>🎯 The end result? Your EBS volumes now scale themselves automatically, exactly when needed, without any manual intervention. It’s like having a self-healing infrastructure!</p><p><strong>A few quick pro tips before we wrap up:</strong></p><ol><li>Always test this in a non-production environment first</li><li>Monitor the CloudWatch logs initially to ensure everything’s working as expected</li><li>Consider setting up SNS notifications for successful scaling operations</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51708dc6dac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Never Worry About AWS Storage (My EBS Automation Secrets)]]></title>
            <link>https://medium.com/@eaaladejana/how-i-never-worry-about-aws-storage-my-ebs-automation-secrets-40b83c5a280c?source=rss-fb0a020ee2c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b83c5a280c</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[ebs-volume]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[step-functions]]></category>
            <dc:creator><![CDATA[Aladejana, Emmanuel Abiodun]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 18:36:03 GMT</pubDate>
            <atom:updated>2024-10-27T18:37:04.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Smart Way to Grow Your Cloud Space</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*38W9Bxa8m78mkRh1" /></figure><p>Imagine your cloud storage like a smart backpack that grows exactly when you need it. We’re starting with a 25GB backpack that’s already holding 21GB — pretty full, right? Instead of buying a massive backpack upfront (expensive!) or frantically running out of space (stressful!), we’re building a system that automatically expands when needed. It’s like having a magic backpack that grows just enough, exactly when you need it.</p><h3>The Key Ingredient 🧪</h3><p>Remember how your phone notifies you when it’s running out of storage? We’re doing something way cooler. We’re teaching AWS to:</p><ol><li>Watch your storage like a hawk (CloudWatch)</li><li>Call for backup when needed (Triggers)</li><li>Smoothly expand your space (EBS magic)</li></ol><p>Think of it as having a super-efficient assistant who:</p><ul><li>Keeps an eye on your storage (89% full? Time to act!)</li><li>Handles all the paperwork (Step Functions orchestration)</li><li>Makes sure everything goes smoothly (checks and balances</li></ul><h3>Building Our Smart System 🔧</h3><h4>The Foundation</h4><p>Remember the last time your phone automatically updated overnight? We’re setting up something similar, but for storage. AWS introduced this cool feature called EBS Elastic Volumes back in 2017 (yes, it’s been quietly making life easier for years!).</p><p>Here’s our plan:</p><ol><li>Set up alerts (like your phone’s low storage warning)</li><li>Create a chain of smart helpers (Step Functions)</li><li>Make everything work together smoothly</li></ol><h4><strong>The Smart Parts</strong></h4><p>Think of this like assembling a high-tech LEGO set:</p><ol><li><strong>CloudWatch</strong> (our vigilant guardian)</li><li><strong>Lambda Functions</strong> (our smart workers)</li><li><strong>Step Functions</strong> (our master coordinator)</li></ol><h4>The Behind the Scenes</h4><p>The real beauty lies in how everything works together:</p><ol><li>CloudWatch is like a smart sensor</li><li>Step Functions are like a well-orchestrated dance</li><li>Lambda functions are like specialized workers, each with their own expertise</li></ol><h4>The Automation Ballet</h4><p>When storage gets tight:</p><ol><li>CloudWatch raises the alarm</li><li>Our trigger Lambda springs into action</li><li>Step Functions coordinate the expansion</li><li>The system verifies everything worked perfectly</li></ol><h3>Making It All Dance Together</h3><h4>The Control Room Setup (CloudWatch Magic)</h4><p>Let’s set up our smart monitoring system — think of it like installing the world’s most sophisticated smoke detector, but for storage space.</p><p>If you’re starting fresh (no CWAgent yet), here’s our setup ceremony:</p><pre><br>wget https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb<br>sudo dpkg -i -E ./amazon-cloudwatch-agent.deb</pre><p><strong>Pro tip:</strong> If AWS roles start acting funky during creation (throwing those sneaky permission errors), here’s a secret of the trade — just start fresh with a new role. It’s like when your phone acts up — sometimes a clean restart works better than debugging for hours!</p><p>Want the express route? Here’s our pre-cooked CloudWatch configuration recipe:</p><pre><br>#!/bin/bash<br>cat &lt;&lt;EOF &gt; /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json{<br> &quot;agent&quot;: {<br>   &quot;metrics_collection_interval&quot;: 60,<br>   &quot;run_as_user&quot;: &quot;root&quot;<br> },<br> &quot;metrics&quot;: {<br>   &quot;metrics_collected&quot;: {<br>     &quot;disk&quot;: {<br>       &quot;measurement&quot;: [&quot;used_percent&quot;],<br>       &quot;resources&quot;: [&quot;/&quot;]<br>     },<br>     &quot;mem&quot;: {<br>       &quot;measurement&quot;: [&quot;used_percent&quot;]<br>     },<br>     &quot;cpu&quot;: {<br>       &quot;measurement&quot;: [&quot;usage_active&quot;],<br>       &quot;totalcpu&quot;: true<br>     }<br>   }<br> }<br>}<br>EOF<br>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json<br>sudo systemctl start amazon-cloudwatch-agent</pre><p>Here’s where things get interesting — this configuration is like setting up multiple vital signs monitors in a hospital. It’s tracking your server’s pulse, blood pressure, and temperature all at once, and I’ll show you exactly how each piece works.</p><p>The CloudWatch agent configuration collects specifically:</p><ul><li>disk_used_percent: Reports percentage of disk space utilized, sampled every minute with ‘collect_interval’</li><li>mem_used_percent: Tracks RAM utilization with same sampling frequency</li><li>cpu_active: Monitors CPU utilization across all cores Critical note: Configure ‘aggregation_dimensions’ to include [“InstanceId”] for proper metric isolation per instance.</li></ul><p>Keep your eyes locked on that disk usage percent — it’s our canary in the coal mine. After countless 3AM pages, I’ve learned it’s the silent killer you want to catch early. The memory and CPU metrics are bonus insights, but disk usage is what triggers our automation symphony.</p><h3>The Brain of the Operation (Step Functions) 🧠</h3><p>Now, here’s where it gets really interesting. We’re building what I like to call a “digital choreographer” — it’s going to direct all our AWS services in a perfectly synchronized dance.</p><p>Consider our Step Function as an intelligent assistant that:</p><ol><li>Checks what’s going on (“Get Instance Details”)</li><li>Makes the right calls (“Increase Volume Size”)</li><li>Waits patiently when needed (that 900-second pause isn’t random — it’s like letting the dough rise when baking)</li><li>Double-checks everything (“Check Volume Modification”)</li></ol><p>Here’s what this genius looks like in code:</p><pre><br>{<br>  &quot;Comment&quot;: &quot;EBS Auto Scaling Workflow&quot;,<br>  &quot;StartAt&quot;: &quot;Get Instance Details&quot;,<br>  &quot;States&quot;: {<br>    &quot;Get Instance Details&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;FunctionName&quot;: &quot;get-instance-details&quot;,<br>        &quot;Payload&quot;: {<br>          &quot;instance_id.$&quot;: &quot;$.instance_id&quot;<br>        }<br>      },<br>      &quot;Next&quot;: &quot;Increase Volume Size&quot;,<br>      &quot;ResultPath&quot;: &quot;$.instanceDetails&quot;<br>    },<br>    &quot;Increase Volume Size&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;FunctionName&quot;: &quot;increase-volume-size&quot;,<br>        &quot;Payload&quot;: {<br>          &quot;instance_id.$&quot;: &quot;$.instanceDetails.Payload.instance_id&quot;,<br>          &quot;volume_id.$&quot;: &quot;$.instanceDetails.Payload.volume_id&quot;,<br>          &quot;current_size.$&quot;: &quot;$.instanceDetails.Payload.current_size&quot;<br>        }<br>      },<br>      &quot;ResultPath&quot;: &quot;$.instanceDetails&quot;,<br>      &quot;Next&quot;: &quot;Extract VolumeID to Parameters&quot;<br>    },<br>    &quot;Extract VolumeID to Parameters&quot;: {<br>      &quot;Type&quot;: &quot;Pass&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;instance_id.$&quot;: &quot;$.instance_id&quot;,<br>        &quot;volume_id.$&quot;: &quot;$.instanceDetails.Payload.volume_id&quot;<br>      },<br>      &quot;Next&quot;: &quot;Wait Before Check&quot;<br>    },<br>    &quot;Wait Before Check&quot;: {<br>      &quot;Type&quot;: &quot;Wait&quot;,<br>      &quot;Seconds&quot;: 900,<br>      &quot;Next&quot;: &quot;Check Volume Modification&quot;<br>    },<br>    &quot;Check Volume Modification&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;FunctionName&quot;: &quot;check-volume-modification&quot;,<br>        &quot;Payload&quot;: {<br>          &quot;volume_id.$&quot;: &quot;$.volume_id&quot;<br>        }<br>      },<br>      &quot;ResultPath&quot;: &quot;$.modificationCheck&quot;,<br>      &quot;Next&quot;: &quot;Is Modification Complete&quot;<br>    },<br>    &quot;Is Modification Complete&quot;: {<br>      &quot;Type&quot;: &quot;Choice&quot;,<br>      &quot;Choices&quot;: [<br>        {<br>          &quot;Variable&quot;: &quot;$.modificationCheck.Payload.modificationComplete&quot;,<br>          &quot;BooleanEquals&quot;: true,<br>          &quot;Next&quot;: &quot;Extend File System&quot;<br>        }<br>      ],<br>      &quot;Default&quot;: &quot;Wait Before Check&quot;<br>    },<br>    &quot;Extend File System&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;FunctionName&quot;: &quot;extend-file-system&quot;,<br>        &quot;Payload&quot;: {<br>          &quot;instance_id.$&quot;: &quot;$.instance_id&quot;,<br>          &quot;volume_id.$&quot;: &quot;$.volume_id&quot;<br>        }<br>      },<br>      &quot;End&quot;: true<br>    }<br>  }<br>}<br></pre><p>Let me walk you through our automated lifesaver — this Step Function is the orchestrator that turns chaos into clockwork. Think of it as your most reliable DevOps engineer who never sleeps.</p><p>Key Technical Points:</p><ol><li>State machine implements error handling through ResultPath</li><li>Uses Parameter pass-through to maintain instance context</li><li>Critical 900-second wait implements exponential backoff pattern</li><li>Implements state branching for modification verification</li><li>Uses JSON path notation for dynamic value extraction</li></ol><p>This whole orchestration means you’ll never have to manually resize volumes at 3AM again. Each step is meticulously checked, verified, and logged — because there’s nothing worse than a half-complete volume resize when production is on the line.</p><h3>The Worker Bees (Lambda Functions) 🐝</h3><p>Each Lambda function is like a highly specialized expert. Let’s meet our team:</p><h4>The First Responder Lambda (ebs-scaling-trigger) 🎯</h4><p>Think of this function as our emergency dispatcher who gets the “storage almost full!” alert and knows exactly who to call (the Step Function):</p><pre><br>import json<br>import boto3<br><br>def get_instance_id_from_ip(ip_address):<br>    ec2 = boto3.client(&#39;ec2&#39;)<br>    response = ec2.describe_instances(<br>        Filters=[<br>            {<br>                &#39;Name&#39;: &#39;private-ip-address&#39;,<br>                &#39;Values&#39;: [ip_address]<br>            }<br>        ]<br>    )<br>    print(f&quot;EC2 response: {json.dumps(response, default=str)}&quot;) <br>    if response[&#39;Reservations&#39;]:<br>        return response[&#39;Reservations&#39;][0][&#39;Instances&#39;][0][&#39;InstanceId&#39;]<br>    return None<br><br>def lambda_handler(event, context):<br>    print(&quot;received alarm:&quot;, json.dumps(event))<br><br>    # extract alarm info<br>    alarm_name = event[&#39;alarmData&#39;][&#39;alarmName&#39;]<br><br>    # extract hostname from dimension<br>    dimensions = event[&#39;alarmData&#39;][&#39;configuration&#39;][&#39;metrics&#39;][0][&#39;metricStat&#39;][&#39;metric&#39;][&#39;dimensions&#39;]<br>    hostname = dimensions.get(&#39;host&#39;)<br>    ip_address = hostname.split(&#39;-&#39;)[1:]<br>    ip_address = &#39;.&#39;.join(ip_address)<br><br>    if not ip_address:<br>        raise ValueError(&quot;Could not extract IP address from alarm data&quot;)<br><br>    # get instance ID from IP<br>    instance_id = get_instance_id_from_ip(ip_address)<br><br>    if not instance_id:<br>        raise ValueError(f&quot;Could not find instance ID for IP: {ip_address}&quot;)<br><br>    # start step function<br>    sf_client = boto3.client(&#39;stepfunctions&#39;)<br>    sf_arn = &#39;arn:aws:states:us-east-1:&lt;acount-id&gt;:stateMachine:ebs-auto-scaling&#39;  <br><br>    response = sf_client.start_execution(<br>        stateMachineArn=sf_arn,<br>        input=json.dumps({&#39;instance_id&#39;: instance_id})<br>    )<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(f&#39;started scaling process for instance {instance_id}&#39;)<br>    }</pre><p>The code breaks down into three critical components:</p><ol><li>Instance ID Resolution Function:</li></ol><pre><br>def get_instance_id_from_ip(ip_address):<br>   ec2 = boto3.client(‘ec2’)<br>   response = ec2.describe_instances(<br>     Filters=[{‘Name’: ‘private-ip-address’, ‘Values’: [ip_address]}]<br> )</pre><p>Critical Points:</p><ul><li>Uses EC2 API’s describe_instances with a filtered query</li><li>Filter specifically targets private-ip-address to minimize API response size</li><li>Returns first instance match from reservations array</li><li>Implements null safety with empty response handling</li></ul><p>2. Alarm Data Extraction:</p><pre>alarm_name = event[‘alarmData’][‘alarmName’]<br>   dimensions = event[‘alarmData’][‘configuration’][‘metrics’][0][‘metricStat’][‘metric’][‘dimensions’]<br>   hostname = dimensions.get(‘host’)<br>   ip_address = hostname.split(‘-’)[1:]<br>   ip_address = ‘.’.join(ip_address)</pre><p>Key Implementation Details:</p><ul><li>Navigates nested JSON structure of CloudWatch alarm data</li><li>Extracts hostname from metric dimensions</li><li>Parses IP address from CloudWatch’s hostname format (ip-10–0–0–1 → 10.0.0.1)</li><li>Uses defensive programming with .get() method</li></ul><p>3. Step Function Trigger:</p><pre>sf_client = boto3.client(‘stepfunctions’)<br>   response = sf_client.start_execution(<br>     stateMachineArn=sf_arn,<br>     input=json.dumps({‘instance_id’: instance_id})<br> )</pre><p>Critical Implementation Notes:</p><ul><li>Initiates Step Functions client with boto3</li><li>Constructs minimal JSON payload with instance_id</li><li>Handles state machine execution with error propagation</li></ul><h4>The Detective (get-instance-details)</h4><p>This one’s our investigator — it figures out exactly what we’re dealing with:</p><pre>import json<br>import boto3<br>from botocore.exceptions import ClientError<br><br>def lambda_handler(event, context):<br>    print(f&quot;Received event: {json.dumps(event)}&quot;)<br><br>    ec2 = boto3.client(&#39;ec2&#39;)<br>    instance_id = event.get(&#39;instance_id&#39;)<br><br>    if not instance_id:<br>        print(&quot;Error: No instance_id provided in the event&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps(&#39;Error: instance_id is required&#39;)<br>        }<br><br>    try:<br>        print(f&quot;Describing instance: {instance_id}&quot;)<br>        response = ec2.describe_instances(InstanceIds=[instance_id])<br>        instance = response[&#39;Reservations&#39;][0][&#39;Instances&#39;][0]<br><br>        volume_id = instance[&#39;BlockDeviceMappings&#39;][0][&#39;Ebs&#39;][&#39;VolumeId&#39;]<br><br>        print(f&quot;Describing volume: {volume_id}&quot;)<br>        volume_response = ec2.describe_volumes(VolumeIds=[volume_id])<br>        current_size = volume_response[&#39;Volumes&#39;][0][&#39;Size&#39;]<br><br>        result = {<br>            &#39;instance_id&#39;: instance_id,<br>            &#39;volume_id&#39;: volume_id,<br>            &#39;current_size&#39;: current_size<br>        }<br>        print(f&quot;Result: {json.dumps(result)}&quot;)<br>        return result<br><br>    except ClientError as e:</pre><p>The code breaks down into four critical components:</p><ol><li>Input Validation &amp; Error Handling:</li></ol><pre>def lambda_handler(event, context):<br>    print(f&quot;Received event: {json.dumps(event)}&quot;)<br><br>    instance_id = event.get(&#39;instance_id&#39;)<br>    if not instance_id:<br>        print(&quot;Error: No instance_id provided in the event&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps(&#39;Error: instance_id is required&#39;)<br>        }</pre><p>Critical Implementation Details:</p><ul><li>Uses .get() for safe dictionary access</li><li>Implements early return pattern for invalid inputs</li><li>Maintains audit trail with structured logging</li><li>Returns HTTP-like response structure for API consistency</li></ul><p>2. Instance Information Retrieval:</p><pre><br>response = ec2.describe_instances(InstanceIds=[instance_id])<br>   instance = response[‘Reservations’][0][‘Instances’][0]<br>   volume_id = instance[‘BlockDeviceMappings’][0][‘Ebs’][‘VolumeId’]<br></pre><p>Key Technical Points:</p><ul><li>Direct EC2 API call with instance filtering</li><li>Navigates AWS’s nested response structure</li><li>Extracts EBS volume information from block device mappings</li><li>Assumes first block device (typically root volume)</li></ul><p>3. Volume Size Detection:</p><pre><br>volume_response = ec2.describe_volumes(VolumeIds=[volume_id])<br>   current_size = volume_response[‘Volumes’][0][‘Size’]<br>   result = {<br>       &#39;instance_id&#39;: instance_id,<br>       &#39;volume_id&#39;: volume_id,<br>       &#39;current_size&#39;: current_size<br>   }</pre><p>Implementation Specifics:</p><ul><li>Secondary API call to describe_volumes for detailed volume info</li><li>Extracts current size in GiB</li><li>Constructs normalized response object</li><li>Maintains data continuity for step function state</li></ul><p>4. Error Boundary:</p><pre>except ClientError as e:<br></pre><p>Error Handling Strategy:</p><ul><li>Catches AWS-specific exceptions</li><li>Implements botocore error handling</li><li>Preserves error context for debugging</li></ul><h4>The Expander (increase-volume-size)</h4><p>Our space wizard — it does the actual growing magic, but with style:</p><pre>import boto3<br>import math<br><br>def lambda_handler(event, context):<br>    ec2 = boto3.client(&#39;ec2&#39;)<br>    volume_id = event[&#39;volume_id&#39;]<br>    current_size = event[&#39;current_size&#39;]<br><br>    # Calculate new size (20% increase)<br>    increase_factor = 1.2<br>    new_size = math.ceil(current_size * increase_factor)<br><br>    # Ensure the new size is different from the current size<br>    if new_size == current_size:<br>        new_size += 1<br><br>    print(f&quot;Increasing volume {volume_id} from {current_size} GB to {new_size} GB&quot;)<br><br>    try:<br>        response = ec2.modify_volume(<br>            VolumeId=volume_id,<br>            Size=new_size<br>        )<br><br>        print(f&quot;Volume modification initiated: {response[&#39;VolumeModification&#39;]}&quot;)<br><br>        result = {<br>            &#39;volume_id&#39;: volume_id,<br>            &#39;original_size&#39;: current_size,<br>            &#39;new_size&#39;: new_size<br>        }<br>        return result<br><br>    except Exception as e:<br>        print(f&quot;Error modifying volume: {str(e)}&quot;)<br>        raise</pre><p>Now we’re getting to the heart of the operation — this is our surgical suite where we actually perform the volume expansion. It’s the difference between diagnostics and treatment.</p><p>The code breaks down into four critical components:</p><ol><li>Size Calculation Logic:</li></ol><pre>    increase_factor = 1.2<br>    new_size = math.ceil(current_size * increase_factor)<br><br>    # Ensure the new size is different from the current size<br>    if new_size == current_size:<br>        new_size += 1</pre><p>Critical Implementation Details:</p><ul><li>Implements 20% growth factor (1.2 multiplier)</li><li>Uses math.ceil() to round up to nearest GB</li><li>Contains edge case handling for small volumes</li><li>Ensures minimum 1 GB increase even in edge cases</li></ul><p>2. Volume Modification Execution:</p><pre>response = ec2.modify_volume(<br>   VolumeId=volume_id,<br>   Size=new_size<br> )</pre><p>Key Technical Points:</p><ul><li>Direct EBS API interaction</li><li>Synchronous modification request</li><li>No size validation against instance limits</li><li>Returns VolumeModification object for tracking</li></ul><p>3. Result Structure Formation:</p><pre>result = {<br>   ‘volume_id’: volume_id,<br>   ‘original_size’: current_size,<br>   ‘new_size’: new_size<br> }</pre><p>Implementation Specifics:</p><ul><li>Maintains operation audit trail</li><li>Preserves size delta information</li><li>Structured for Step Function state management</li><li>Enables downstream size verification</li></ul><p>4. Error Management:</p><pre>except Exception as e:<br> print(f”Error modifying volume: {str(e)}”)<br> raise</pre><p>Error Handling Strategy:</p><ul><li>Catches all exceptions for logging</li><li>Preserves stack trace with re-throw</li><li>Maintains Step Function error handling chain</li><li>Logs before raising for debugging context</li></ul><h4>The Quality Inspector (check-volume-modification)</h4><p>Like a building inspector, but for cloud storage: It checks if our volume modification is complete (on AWS the modification status could take some time to change to complete)</p><pre><br>import boto3<br><br>def lambda_handler(event, context):<br>    ec2 = boto3.client(&#39;ec2&#39;)<br>    volume_id = event[&#39;volume_id&#39;]<br><br><br>    response = ec2.describe_volumes_modifications(VolumeIds=[volume_id])<br><br>    if response[&#39;VolumesModifications&#39;]:<br>        modification = response[&#39;VolumesModifications&#39;][0]<br>        modification_state = modification[&#39;ModificationState&#39;]<br><br>        if modification_state == &#39;optimizing&#39;:<br>            return {<br>                &#39;modificationComplete&#39;: False,<br>                &#39;state&#39;: modification_state<br>            }<br>        elif modification_state == &#39;completed&#39;:<br>            return {<br>                &#39;modificationComplete&#39;: True,<br>                &#39;state&#39;: modification_state,<br>                &#39;volume_id&#39;: volume_id<br>            }<br>        else:<br>            return {<br>                &#39;modificationComplete&#39;: False,<br>                &#39;state&#39;: modification_state<br>            }<br>    else:<br>        return {<br>            &#39;modificationComplete&#39;: False,<br>            &#39;state&#39;: &#39;unknown&#39;<br>        }</pre><p>This is our monitoring nurse in the recovery room — the code that patiently checks if AWS has finished expanding your volume. Like any good medical professional, it knows the difference between ‘recovering well’ and ‘ready to go.</p><ol><li>Volume Modification Status Check:</li></ol><pre><br> response = ec2.describe_volumes_modifications(VolumeIds=[volume_id])</pre><p>Critical Implementation Details:</p><ul><li>Direct EBS modification API query</li><li>Single-volume focused check</li><li>No pagination handling (assumes single modification)</li><li>Synchronous API operation</li></ul><p>2. State Evaluation Logic:</p><pre><br> if response[‘VolumesModifications’]:<br>   modification = response[‘VolumesModifications’][0]<br>   modification_state = modification[‘ModificationState’]</pre><p>Key Technical Points:</p><ul><li>Handles empty modification list case</li><li>Takes most recent modification (index 0)</li><li>Extracts raw state string</li><li>No historical modification tracking</li></ul><p>3. State Response Mapping:</p><pre><br> if modification_state == ‘optimizing’:<br>   return {<br>     ‘modificationComplete’: False,<br>     ‘state’: modification_state<br>   }<br> elif modification_state == ‘completed’:<br>   return {<br>     ‘modificationComplete’: True,<br>     ‘state’: modification_state,<br>     ‘volume_id’: volume_id<br> }</pre><p>Implementation Specifics:</p><ul><li>Boolean flag for Step Function decision making</li><li>Preserves raw state for logging</li><li>Additional volume_id in completion state</li><li>Normalized response structure</li></ul><p>4. Edge Case Handling:</p><pre>else:<br>   return {<br>     ‘modificationComplete’: False,<br>     ‘state’: ‘unknown’<br>   }</pre><p>Error Handling Strategy:</p><ul><li>Graceful handling of missing modifications</li><li>Conservative completion reporting</li><li>Consistent response structure</li><li>Enables retry logic in Step Function</li></ul><h3>The Finisher (extend-file-system)</h3><p>The one that makes sure everything’s properly tied together: We extend our filesystem partition to extend the filesystem, completing the resizing.</p><pre>import boto3<br><br>def lambda_handler(event, context):<br>    ssm = boto3.client(&#39;ssm&#39;)<br><br>    instance_id = event[&#39;instance_id&#39;]<br><br>    # command for ubuntu 22.04 with lvm<br>    command = &quot;sudo growpart /dev/nvme0n1 1 &amp;&amp; sudo resize2fs /dev/nvme0n1p1&quot;<br><br>    response = ssm.send_command(<br>        InstanceIds=[instance_id],<br>        DocumentName=&quot;AWS-RunShellScript&quot;,<br>        Parameters={&#39;commands&#39;: [command]}<br>    )<br><br>    return {<br>        &#39;instance_id&#39;: instance_id,<br>        &#39;command_id&#39;: response[&#39;Command&#39;][&#39;CommandId&#39;]<br>    }</pre><ol><li>Systems Manager Client Setup:</li></ol><pre><br> ssm = boto3.client(‘ssm’)<br> instance_id = event[‘instance_id’]</pre><p>Critical Implementation Details:</p><ul><li>Uses AWS Systems Manager (SSM) for remote execution</li><li>Requires SSM agent on target instance</li><li>Assumes instance has SSM permissions</li><li>Single instance targeting</li></ul><p>2. Command Construction:</p><pre><br> command = “sudo growpart /dev/nvme0n1 1 &amp;&amp; sudo resize2fs /dev/nvme0n1p1”</pre><p>Key Technical Points:</p><ul><li>Targets NVMe device path specifically</li><li>Uses growpart for partition expansion</li><li>Uses resize2fs for ext4 filesystem resize</li><li>Combines commands with &amp;&amp; for fail-fast execution</li><li>Assumes Ubuntu 22.04 with specific disk layout</li></ul><p>3. Remote Command Execution:</p><pre><br> response = ssm.send_command(<br>   InstanceIds=[instance_id],<br>   DocumentName=”AWS-RunShellScript”,<br>   Parameters={‘commands’: [command]}<br> )</pre><p>Implementation Specifics:</p><ul><li>Leverages AWS-RunShellScript SSM document</li><li>Asynchronous command execution</li><li>No timeout specification (uses default)</li><li>No command output capture</li></ul><p>4. Response Handling:</p><pre><br> return {<br>   ‘instance_id’: instance_id,<br>   ‘command_id’: response[‘Command’][‘CommandId’]<br> }</pre><p>Execution Strategy:</p><ul><li>Returns command tracking information</li><li>No direct success/failure confirmation</li><li>Enables external command status tracking</li><li>Maintains audit trail</li></ul><p>Back to English: This is where the rubber meets the road — we’re actually telling the Linux operating system to recognize and use the new space we’ve given it. There’s some serious systems knowledge baked into that simple-looking command:</p><ul><li>growpart expands the partition to use the new space</li><li>resize2fs tells the filesystem to actually use that expanded partition</li></ul><p>The really clever bit? We’re doing this remotely through AWS Systems Manager, so we don’t need to SSH in or maintain any special access. It’s like having a universal remote control for all your servers.</p><h4>Security Passes (IAM Roles and Policies) 🎫</h4><p>Think of IAM roles like VIP passes at a high-security concert. Each service needs exactly the right badge to do its job:</p><ol><li><strong>The Orchestrator’s Badge</strong> (Step function):</li></ol><ul><li>LambdaInvokeAllServices</li><li>LambdaInvokeScopedAccessPolicy-x</li><li>SnsPublishScopedAccessPolicy-x</li><li>XRayAccessPolicy-x</li></ul><p>2. <strong>The Trigger’s Credentials</strong> (ebs-scaling-trigger-role):</p><ul><li>AWSLambdaBasicExecutionRole</li><li>ebs-trigger-start-step-function-execution</li></ul><p>3. <strong>The Detective’s Badge</strong> (get-instance-details):</p><ul><li>AWSLambdaBasicExecutionRole-x (their basic uniform)</li><li>EC2DescribeRole (permission to peek into EC2 instances)</li><li>EC2DescribeVolumesForGetInstance (ability to check volume details)</li></ul><p>4. <strong>The Volume Wizard’s Pass</strong> (modifyEC2EbsVolumes-role):</p><ul><li>CloudWatchFullAccess (complete monitoring vision)</li><li>modifyEC2EbsVolumes (the actual magic wand for changing volumes)</li></ul><p>5. <strong>The Inspector’s Credentials</strong> (check-volume-modification-role):</p><ul><li>AWSLambdaBasicExecutionRole-x (standard issue gear)</li><li>EC2DescribeVolumeModificationsPolicy (special lens to see how changes are progressing)</li></ul><p>6. <strong>The System Expander’s Access</strong> (extend-file-system-role):</p><ul><li>AmazonEC2ReadOnlyAccess (permission to read the infrastructure map)</li><li>AWSLambdaBasicExecutionRole (basic operating license)</li><li>DescribeInstancesPolicy (ability to identify our targets)</li><li>ExtendFileSystemPolicy (the actual tools to grow the system)</li></ul><h3>The Grand Finale: Why This Rocks 🎸</h3><p>What we’ve built here is like having a smart butler for your cloud storage. Instead of:</p><ul><li>Paying for a massive mansion upfront (overprovisioning)</li><li>Frantically adding rooms when guests arrive (reactive scaling)</li><li>Manually checking every closet for space (manual monitoring)</li></ul><p>We have:</p><ul><li>A space that grows exactly when needed</li><li>Automatic monitoring and expansion</li><li>Zero human intervention required</li><li>Cost optimization built-in</li></ul><p>It’s like teaching your cloud infrastructure to take care of itself — pretty neat, right?</p><h4>Pro Tips for the Road 🚗</h4><ol><li>Monitor First: Let this run for a while and watch the patterns. Like a good chef tasting the soup before adding more seasoning.</li><li>Test Small: Start with non-critical systems. It’s like testing a new recipe on friends before the big dinner party.</li><li>Adjust Thresholds: That 89% trigger point? It’s not set in stone. Adjust based on your growth patterns, like tailoring a suit to fit perfectly.</li></ol><h4>Final Thoughts 💭</h4><p>This isn’t just automation — it’s peace of mind orchestrated into code. Your storage now grows like a well-tended garden: naturally, efficiently, and exactly when needed.</p><p>Remember: The best systems are those that make complex things look easy. This solution does exactly that — handling complicated infrastructure management with the smoothness of a swan gliding across a lake.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b83c5a280c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Deployed GitLab in Production in 30 Minutes (And You Can Too)]]></title>
            <link>https://medium.com/@eaaladejana/how-i-deployed-gitlab-in-production-in-30-minutes-and-you-can-too-e67411d928c9?source=rss-fb0a020ee2c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67411d928c9</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Aladejana, Emmanuel Abiodun]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 15:18:03 GMT</pubDate>
            <atom:updated>2024-10-27T15:18:03.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Achieve CI/CD Independence with GitLab in 30 Minutes</p><p>Here’s the thing: while AWS CodeCommit and Azure DevOps are solid choices, they’re like renting an apartment — you’re stuck with whatever the landlord gives you. But running your own GitLab? That’s like owning your dream house. You get to knock down walls, upgrade the security system, and squeeze every ounce of performance out of your infrastructure.</p><p>This guide walks through a production-ready setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*lC9LLnqZmTpcw31YDK6sLA.png" /></figure><h3>GitLab Server Configuration</h3><p>The implementation requires two key components:</p><ul><li>GitLab server (main application server)</li><li>GitLab runner (CI/CD execution environment)</li></ul><h4>Infrastructure requirements</h4><ul><li>Main GitLab Server</li></ul><pre>Provider: Any major cloud provider (AWS, GCP, Azure, DigitalOcean)<br>Recommended Specs:<br>- 2-4 vCPUs<br>- 8GB RAM<br>- 100GB SSD storage</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KR1cB9ZIrkbmSJyZ8yskcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kfdjm6JmgbAlVVUKYVXmcA.png" /></figure><ul><li>GitLab Runner Server</li></ul><pre>Base Configuration:<br>- 2 vCPUs<br>- 4GB RAM<br>- 50GB SSD storage</pre><p>Note: Runner specs can be adjusted based on your CI/CD workload intensity. This baseline works for most standard development workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxLR7I80PNeiNGCp7fjY3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRQ6cZUiRqqfN0ln54TcSg.png" /></figure><p>⚠️ <strong>Important Note:</strong> While a t2.medium also offers 2 vCPUs, it uses CPU credits for bursting. This burst-based model isn’t suitable for GitLab’s continuous workload. The t3.large provides consistent CPU performance which is crucial for stable GitLab operations.</p><p><em>For the runner, burst capacity is acceptable since CI/CD workloads are typically intermittent.</em></p><h4>Server Installation</h4><p>The installation process follows GitLab’s official package-based deployment method, similar to how you’d set up other enterprise SCM tools like Bitbucket Server.</p><h4><strong>Main GitLab Server</strong></h4><p>First, prepare the base system:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install -y curl openssh-server ca-certificates tzdata perl</pre><p>These dependencies align with standard enterprise Linux deployments and ensure proper system communication, SSL handling, and basic utilities.</p><pre># Repository setup and installation<br>curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash<br>sudo apt install gitlab-ce</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD2ozrD1T1J1YvOdQc-f2A.png" /></figure><p>Next, we’ll configure the core GitLab settings. This is similar to how you’d configure Jenkins’ initial setup, but focused on GitLab’s architecture:</p><pre>sudo nano /etc/gitlab/gitlab.rb<br><br># Critical configuration<br>external_url &#39;https://your-domain-or-ip&#39;</pre><p>The external_url setting is particularly important as it affects GitLab&#39;s container registry, CI/CD webhook endpoints, and repository URLs. After configuration:</p><pre>sudo gitlab-ctl reconfigure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*vBdirUHr6dnvImOsujTcCg.png" /></figure><p>For the initial security setup:</p><pre>sudo gitlab-rake &quot;gitlab:password:reset&quot;<br><br># user =  root</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*H0Nh5P9x7-tcUbhywyHgyg.png" /></figure><p><strong>SSL certification</strong></p><p>For production environments require secure access</p><p>Pause GitLab services:</p><pre>sudo gitlab-ctl stop</pre><p>Set up SSL certification:</p><pre>sudo apt install -y certbot<br>sudo certbot certonly --standalone -d your-domain.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*D5WCQt24xDlyzOtBNShuqw.png" /></figure><p>Resume GitLab services:</p><pre>sudo gitlab-ctl start</pre><p>Update GitLab’s SSL configuration:</p><pre>sudo nano /etc/gitlab/gitlab.rb<br><br>#Add these lines<br>letsencrypt[&#39;enable&#39;] = true<br>letsencrypt[&#39;contact_emails&#39;] = [&#39;your_email@example.com&#39;]<br>letsencrypt[&#39;key_type&#39;] = &#39;rsa&#39;<br>letsencrypt[&#39;key_size&#39;] = 2048</pre><p>Apply changes and set up auto-renewal:</p><pre>sudo gitlab-ctl reconfigure<br><br>sudo crontab -e<br># Add renewal schedule<br>0 12 1 * * /usr/bin/certbot renew --quiet &amp;&amp; /usr/bin/gitlab-ctl restart nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*WmwcojhYbLPpJoKiXWNh6A.png" /></figure><h4>GitLab Runner Server</h4><p>The runner setup integrates with your main GitLab instance to execute CI/CD pipelines, similar to Jenkins agents or GitHub Actions runners.</p><p>[Implementation note: The GitLab Admin UI runner token page screenshot would prove runner configuration access]</p><p>Register your runner through the GitLab UI:</p><ul><li>Navigate to Admin Area &gt; CI/CD &gt; Runners</li><li>Create a new instance runner</li><li>Note the registration token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4X983SoIRtv0IFkBX4bgw.png" /></figure><p>Install the runner package:</p><pre>curl -L &quot;https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh&quot; | sudo bash<br>sudo apt-get install gitlab-runner</pre><p>Set up Docker for the execution environment:</p><pre># Add Docker&#39;s official GPG key:<br>sudo apt-get update<br>sudo apt-get install ca-certificates curl<br>sudo install -m 0755 -d /etc/apt/keyrings<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>sudo chmod a+r /etc/apt/keyrings/docker.asc<br><br># Add repository<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br>sudo apt-get update</pre><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*-spsuGy7qognDdZyehFRUQ.png" /></figure><p>Configure the runner environment by editing /etc/gitlab-runner/config.toml</p><p>Here’s a production-ready configuration that balances performance and stability:</p><pre>concurrent = 3<br>check_interval = 0<br>shutdown_timeout = 0<br><br>[session_server]<br>  session_timeout = 1800<br><br>[[runners]]<br>  name = &quot;eaaladejana-runner-1&quot;<br>  url = &quot;https://your-domain.com&quot;   &lt;------ set your gitlab server url here<br>  token = &quot;glrt-t1_v_xxxxxxxxxxx&quot;   &lt;------ set your token here<br>  executor = &quot;docker&quot;<br>[runners.cache]<br>  Type = &quot;local&quot;<br>  Path = &quot;/var/cache/gitlab-runner&quot;<br>  Shared = true<br>[runners.docker]<br>  tls_verify = false<br>  image = &quot;ruby:3.3-slim&quot;  <br>  privileged = true<br>  disable_entrypoint_overwrite = false<br>  oom_kill_disable = true<br>  disable_cache = false<br>  volumes = [&quot;/var/cache/gitlab-runner:/cache&quot;]<br>  shm_size = 0</pre><p>[Implementation note: The GitLab CI pipeline status page showing successful job execution would demonstrate proper runner configuration]</p><p>Set up cache directory permissions:</p><pre>sudo mkdir -p /var/cache/gitlab-runner<br>sudo chown -R gitlab-runner:gitlab-runner /var/cache/gitlab-runner<br>sudo chmod -R 755 /var/cache/gitlab-runner</pre><p>Register the runner with your GitLab instance:</p><pre>sudo gitlab-runner register<br><br># press &#39;enter&#39; to accept the domain name<br># set the runner name<br># select executioner: docker<br># enter default ruby image: ruby:3.3-slim</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*cfGdaxk4g-jmgEqeSzOuEw.png" /></figure><p>Verify the runner configuration:</p><pre>sudo gitlab-runner run<br># &#39;ctrl + z&#39; to stop </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*xSTwBWud4jRywry4wNJ8sQ.png" /></figure><p>Grant Docker permissions to the default user:</p><pre>sudo usermod -aG docker ubuntu<br>newgrp docker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwNwnpR5174KoBqV9A8aaQ.png" /></figure><h3><strong>Now, you’re Done. But wait!</strong></h3><p>Building your own GitLab instance might seem like a big step from using hosted solutions like GitHub, but it’s been a game-changer for my workflow. After following this exact process for my infrastructure, I particularly appreciate having full control over my CI/CD pipelines and not worrying about third-party outages.</p><p>I test every step in this guide regularly as I rebuild my environments, so you can trust that all commands work as documented. If you encounter any roadblocks during setup, the logs in /var/log/gitlab/ are your best friend - they&#39;ve saved me countless hours of troubleshooting.</p><p>Currently running on:</p><p>GitLab CE version: 17.5.1<br>Uptime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*JFd9Z7gL8j2JFucDOvSGmQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67411d928c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Sequelize with MySQL]]></title>
            <link>https://medium.com/@eaaladejana/using-sequelize-with-mysql-23215e5854be?source=rss-fb0a020ee2c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/23215e5854be</guid>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql-workbench]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Aladejana, Emmanuel Abiodun]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 11:30:42 GMT</pubDate>
            <atom:updated>2024-06-30T13:05:22.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*ZCp9XueP-UOboMKG.png" /><figcaption>sequelize.js</figcaption></figure><h3><strong>Sequelize</strong></h3><p>A promised-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL server. it features solid transaction support, relations, eager and lazy loading, read replication and more. It helps to map nodejs objects to your MySQL database. It supports different dialect of SQL. We can use sequelize to define models and use them for CRUD operations.</p><h3><strong>How to Install Sequelize in your project</strong></h3><p>run the command: npm install — save sequelize</p><h3><strong>Things to do</strong></h3><ol><li>Start your MySQL server. Before you can connect to the MySQL database you have to start the MySQL service or server.</li><li>Connect to your MySQL server using MySQL workbench. So that we can interact and see our database and tables.</li><li>Quickly create a database bookstore in the MySQL bench. It doesn’t have tables but we’re going to do that from sequelize.</li><li>The code for the project can be found in the repository: <a href="https://github.com/Dejanor/working_with_databases">Dejanor/working_with_databases (github.com)</a></li><li>Recreate the models in express_sequelize_new create your .env file which will contain: PORT=3000<br>DB_NAME=bookstore<br>DB_USER=root //set the right user<br>DB_PASSWORD= //set the password<br>DB_DIALECT=mysql<br>DB_HOST=localhost //replace with actual host</li><li>The packages to be installed are: dotenv, body-parser, express, mysql2, nodemon, sequelize. run: npm install to install them</li><li>After everything is set, run your routes using the thunderclient extension or postman and test your models and controllers. The routes are available in the routes/book.js and routes/author.js files.</li><li>I’m lazy with writing so this is where we’re stopping with this tutorial. I hope you found it informative and are able to figure it out.</li></ol><h3>The code for the models</h3><p>books.js</p><pre>//define constraints for your data. create and export a function<br>module.exports = (sequelize, DataTypes) =&gt; {<br>    // create our book Model<br>    const BookModel = sequelize.define(&#39;Books&#39;, {<br>        id: {<br>            type: DataTypes.INTEGER,<br>            primaryKey: true,<br>            autoIncrement: true<br>        }, <br>        title: {<br>            type: DataTypes.STRING,<br>            allowNull: false<br>        },<br>        year: {<br>            type: DataTypes.INTEGER,<br>            allowNull: false<br>        },<br>        isbn: {<br>            type: DataTypes.STRING,<br>            allowNull: false<br>        },<br>    }, { <br>        tableName : &quot;books&quot;<br>    })<br><br>    return BookModel<br>}</pre><p>authors.js</p><pre>//define constraints for your data. create and export a function<br>module.exports = (sequelize, DataTypes) =&gt; {<br>    // create our book Model<br>    const AuthorModel = sequelize.define(&#39;Authors&#39;, {<br>        id: {<br>            type: DataTypes.INTEGER,<br>            primaryKey: true,<br>            autoIncrement: true<br>        }, <br>        name: {<br>            type: DataTypes.STRING,<br>            allowNull: false<br>        },<br>        dob: {<br>            type: DataTypes.INTEGER,<br>            allowNull: false<br>        },<br>        category: {<br>            type: DataTypes.STRING,<br>            allowNull: false<br>        },<br>    }, { <br>        tableName : &quot;authors&quot;<br>    })<br><br>    return AuthorModel<br>}</pre><p>index.js</p><pre>const {Sequelize, DataTypes} = require(&#39;sequelize&#39;);<br>const CONFIG = require(&#39;../config/dbConfig&#39;)<br>const dbconfig = require(&#39;../config/dbConfig&#39;)<br><br>const AuthorModel = require(&quot;./authors&quot;)<br><br>const BookModel = require(&quot;./books&quot;)<br><br>const sequelize = new Sequelize(<br>    CONFIG.DB_NAME,<br>    CONFIG.DB_USER,<br>    CONFIG.DB_PASSWORD,<br>    {<br>        host: CONFIG.DB_HOST,<br>        dialect: CONFIG.DB_DIALECT<br>    }<br>)<br><br>sequelize.authenticate()<br>    .then(() =&gt; {<br>        console.log(&quot;Connection successful&quot;)<br>    }).catch((err) =&gt; {<br>        console.log(err)<br>    })<br><br>const db = {}<br><br>db.sequelize = sequelize<br>db.Sequelize = Sequelize<br><br>//Add our models<br>db.books = BookModel(sequelize, DataTypes);<br>//if we had more models, we&#39;ll define it and add to this section<br>db.authors = AuthorModel(sequelize, DataTypes)<br><br>db.sequelize.sync({ force: false }) //anytime you restart server it doesn&#39;t replace old values<br>    .then(() =&gt; {<br>        console.log(&quot;Database &amp; Tables synced &quot;)<br>    }).catch((err) =&gt; {<br>        console.log(&#39;Unable to sync database &amp; Tables:&#39;, err)<br>    })<br><br>module.exports = db;</pre><h4>If you’re wondering where CONFIG, came from, well you’re in luck because I am getting to that as well.</h4><pre>require(&quot;dotenv&quot;).config();<br><br>const CONFIG = {<br>    DB_NAME: process.env.DB_NAME,<br>    DB_USER: process.env.DB_USER,<br>    DB_PASSWORD: process.env.DB_PASSWORD,<br>    DB_HOST: process.env.DB_HOST,<br>    DB_DIALECT: process.env.DB_DIALECT<br>}<br><br>module. Exports = CONFIG;</pre><p>The .env file created for the environment variables above are read and exported as CONFIG and that’s how we get this config</p><h4>Now, where do we use the exported models including db, we create controllers for our routes</h4><p>bookController.js</p><pre>const db = require(&#39;../models&#39;)<br><br>const BookModel = db.books<br><br>async function getAllBooks(req, res) {<br>    try {<br>        const books = await BookModel.findAll()<br>        res.status(200).json(books)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br>async function addBook(req, res) {<br>    const bookInfo = req.body<br>    try {<br>        const books = await BookModel.create(bookInfo)<br>        res.status(200).json({<br>            message: &quot;Book added successfully&quot;,<br>            data: books<br>        })<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br>async function getBookById(req, res) {<br>    try {<br>        const book = await BookModel.findByPk(req.params.id)<br>        res.status(200).json(book)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br>async function updateBook(req, res) {<br>    const bookId = req.params.id<br>    const bookUpdateInfo = req.body<br>    try {<br>        const books = await BookModel.update(bookUpdateInfo, {<br>            where: {<br>                id: bookId<br>            }<br>        })<br><br>        res.status(200).json(books)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br>async function deleteBookById(req, res) {<br>    const bookId = req.params.id<br>    <br>    try {<br>        const books = await BookModel.destroy({<br>            where: {<br>                id: bookId<br>            }<br>        })<br>        res.status(200).json({<br>            message: &quot;Book deleted successfully!&quot;<br>        })<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br><br><br><br><br>// in our routes, we import the controller<br><br>module.exports = {<br>    getAllBooks,<br>    addBook,<br>    getBookById,<br>    updateBook,<br>    deleteBookById //we&#39;ll connect this to a particular route<br>}</pre><p>authorController.js</p><pre>const db = require(&#39;../models&#39;)<br><br>const AuthorModel = db.authors<br><br>async function getAllAuthors(req, res) {<br>    try {<br>        const authors = await AuthorModel.findAll()<br>        res.status(200).json(authors)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br>async function addAuthor(req, res) {<br>    const authorInfo = req.body<br>    try {<br>        const authors = await AuthorModel.create(authorInfo)<br>        res.status(200).json({<br>            message: &quot;Author added successfully&quot;,<br>            data: authors<br>        })<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br>async function getAuthorById(req, res) {<br>    try {<br>        const authors = await AuthorModel.findByPk(req.params.id)<br>        res.status(200).json(authors)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br>async function updateAuthor(req, res) {<br>    const authorId = req.params.id<br>    const authorUpdateInfo = req.body<br>    try {<br>        const authors = await AuthorModel.update(authorUpdateInfo, {<br>            where: {<br>                id: authorId<br>            }<br>        })<br><br>        res.status(200).json(authors)<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br>async function deleteAuthorById(req, res) {<br>    const authorId = req.params.id<br>    <br>    try {<br>        const authors = await AuthorModel.destroy({<br>            where: {<br>                id: authorId<br>            }<br>        })<br>        res.status(200).json({<br>            message: &quot;Author deleted successfully!&quot;<br>        })<br>    } catch (error) {<br>        console.log(error)<br>        res.status(500).send(error)<br>    }<br>}<br><br><br><br><br><br>// in our routes, we import the controller<br><br>module.exports = {<br>    getAllAuthors,<br>    addAuthor,<br>    getAuthorById,<br>    updateAuthor,<br>    deleteAuthorById //we&#39;ll connect this to a particular route<br>}</pre><h4>Now, these controllers are reached by our routes</h4><p>/routes/book.js</p><pre>const express = require(&#39;express&#39;);<br>const bookController = require(&#39;../controllers/bookController&#39;);<br><br>const bookRouter = express.Router();<br><br>bookRouter.get(&#39;/&#39;, bookController.getAllBooks);<br>bookRouter.get(&#39;/:id&#39;, bookController.getBookById);<br>bookRouter.post(&#39;/&#39;, bookController.addBook);<br>bookRouter.put(&#39;/:id&#39;, bookController.updateBook);<br>bookRouter.delete(&#39;/:id&#39;, bookController.deleteBookById);<br><br>module.exports = bookRouter;</pre><p>/routes/author.js</p><pre>const express = require(&#39;express&#39;);<br>const authorController = require(&#39;../controllers/authorController&#39;);<br><br>const authorRouter = express.Router();<br><br>authorRouter.get(&#39;/&#39;, authorController.getAllAuthors);<br>authorRouter.get(&#39;/:id&#39;, authorController.getAuthorById);<br>authorRouter.post(&#39;/&#39;, authorController.addAuthor);<br>authorRouter.put(&#39;/:id&#39;, authorController.updateAuthor);<br>authorRouter.delete(&#39;/:id&#39;, authorController.deleteAuthorById);<br><br>module.exports = authorRouter;</pre><h4>Now, these routers are used in our app.js, which can be run with nodemon</h4><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const bookRouter = require(&#39;./routes/book&#39;);<br>const authorRouter = require(&#39;./routes/author&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const PORT = process.env.PORT || 3000;<br><br>const app = express();<br><br>app.use(bodyParser.json());<br><br>app.use(&quot;/books&quot;, bookRouter);<br><br>app.use(&quot;/authors&quot;, authorRouter)<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.send(&#39;Welcome to the book API&#39;);<br>})<br><br>app.use((err, req, res, next) =&gt; {<br>    console.log(err);<br>    res.status(500).json({<br>        error: err.message<br>    })<br>})<br><br>app.listen(PORT, () =&gt; {<br>    console.log(`Server is running on port ${PORT}`);<br>})</pre><h3><strong>About Myself</strong></h3><p>I am Emmanuel Aladejana, a computer science with math student, in my free time I like to learn new things. I am also a DevOps Engineer but a couple months of experience, I am passionate about it just like I am passionate about tech, family, life and my favorite anime which is Jojo’s Bizarre Adventure.</p><h4>Reason I’m on the Hng Backend Internship Track</h4><p>Like I mentioned earlier, I want to learn new things, and I see backend as the next thing to pick up in my journey as a DevOps Engineer as I believe that it will make me a better DevOps Engineer.</p><p><a href="https://hng.tech/premium">HNG Premium</a></p><p><a href="https://hng.tech/internship">https://hng.tech/internship</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23215e5854be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>