<?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 Rushabh Trivedi on Medium]]></title>
        <description><![CDATA[Stories by Rushabh Trivedi on Medium]]></description>
        <link>https://medium.com/@rushabh-ufo?source=rss-5a8c65a68cc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A226sjwUJ5b3tKdQXV-BcA.jpeg</url>
            <title>Stories by Rushabh Trivedi on Medium</title>
            <link>https://medium.com/@rushabh-ufo?source=rss-5a8c65a68cc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:33:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rushabh-ufo/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 Wasting Money on Lambda: Automate Right-Sizing Across Your AWS Account]]></title>
            <link>https://awstip.com/stop-wasting-money-on-lambda-automate-right-sizing-across-your-aws-account-8bce15edcda1?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bce15edcda1</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 29 May 2026 10:12:19 GMT</pubDate>
            <atom:updated>2026-08-04T10:40:23.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*fJ3XoA5bgeEBKgdt.jpg" /><figcaption>Image Courtesy: lumigo.io</figcaption></figure><h3>The Silent Cost Leak Nobody Talks About</h3><p>You know that feeling when you discover a Lambda function still running with a 1024 MB memory allocation — even though CloudWatch shows it never uses more than 80 MB? That’s not just a missed optimization. That’s a silent tax on your AWS bill that compounds with every invocation.</p><p>Here’s the hard truth: AWS Lambda pricing is shaped by two things — invocation count and GB-seconds (memory × duration). While the per-invocation cost is tiny, memory is the only dimension you can actually control. And control it, most teams do not.</p><p>I’ve seen production accounts where:</p><ul><li>A payment processor function sits at 1024 MB, running at 7% utilization</li><li>An auth validator is configured at 128 MB but hitting 63% of limit during peak traffic</li><li>Legacy report generators haven’t been touched since deployment, silently consuming budget at outdated allocations</li></ul><p>The problem? There’s no automated way to catch and fix this at scale.</p><p>Manual auditing is impractical. Spreadsheets go stale. The courage required to actually <em>change</em> production configurations without deep analysis? That’s the real barrier.</p><p>So we built Lambda Rightsizer — a tool that makes right-sizing as routine as a database index optimization, complete with safety guarantees, built-in rollback, and ready-to-apply remediation scripts.</p><h3>Why This Matters (The Business Case)</h3><p>Let’s do the math. Imagine your account has 50 Lambda functions:</p><ul><li>30% are clearly over-provisioned (avg utilization below 30%)</li><li>Average waste: 300 MB per over-provisioned function</li><li>Average invocation rate: 1,000 invocations/day per function</li></ul><p>That’s 15 functions × 300 MB × 1,000 invocations/day = 4.5 GB-seconds/day of pure waste.</p><p>At AWS Lambda’s us-east-1 pricing (~$0.0000166667 per GB-second):</p><ul><li>$2.30/day × 365 = $839.50/year — just on those 15 functions</li><li>Scale to 200 functions? You’re looking at $5,000+ in unnecessary spend</li></ul><p>And that’s before considering the compliance angle: you can’t optimize what you don’t measure. Right-sizing is also a best practice for cost governance audits.</p><h3>What Makes This Hard (And How Lambda Rightsizer Solves It)</h3><h3>The Discovery Problem</h3><p>Finding all Lambda functions across your account is trivial with ListFunctions. But figuring out how <em>much memory each one actually uses</em> is where most solutions fail.</p><p>CloudWatch Logs Insights is powerful but can be slow. Direct metric queries are imprecise. And parsing raw logs locally is error-prone.</p><p>Lambda Rightsizer uses a three-tier strategy:</p><ol><li>CloudWatch Logs Insights — server-side aggregation of REPORT log lines (fastest)</li><li>CloudWatch Logs filter — raw event parsing (when Insights returns few samples)</li><li>CloudWatch Metrics — MaxMemoryUsed metric (last resort, always available)</li></ol><p>The tool tries each in sequence, falling back gracefully. No manual CloudWatch spelunking required.</p><h3>The Analysis Problem</h3><p>Raw memory numbers don’t tell you whether a function is correctly sized. You need context:</p><ul><li>Is peak usage near the limit? (under-provisioned, risk of timeout)</li><li>Is average usage &lt; 30% of allocated? (over-provisioned, pure waste)</li><li>Are you seeing a reliable trend, or just a few outlier invocations? (signal vs. noise)</li></ul><p>Lambda Rightsizer applies a utilization band model:</p><p>UtilizationStatusAction&lt; 30%Over-provisionedReduce to safety floor30–70%OptimalKeep as-is70–80%WatchMonitor (approaching limit)&gt; 80%Under-provisionedIncrease above safety floor</p><p>But here’s the critical part: the tool never recommends below the observed peak + 20% headroom. This protects against cold-start spikes and prevents the “we reduced memory and now functions timeout” surprise.</p><h3>The Risk Problem</h3><p>Not all right-sizing recommendations are equally safe. A reduction from 1024 MB to 128 MB on a function that’s only had 3 invocations in the past month? Different risk profile than a change backed by 10,000 invocations of solid telemetry.</p><p>Lambda Rightsizer scores every recommendation on a 1–5 scale, based on:</p><ul><li>Sample count (low count = higher risk)</li><li>Data source quality (metrics fallback = less reliable)</li><li>Magnitude of change (50%+ reduction = riskier)</li><li>P95 proximity to recommended ceiling (close call = risky)</li></ul><p>High-risk recommendations (score ≥ 4) require explicit per-function confirmation. You can also skip them entirely with SKIP_HIGH_RISK=true for conservative deployments.</p><h3>The Remediation Problem</h3><p>Even with perfect analysis, <em>applying</em> changes safely requires:</p><ul><li>Pre-flight validation that AWS credentials are valid</li><li>A full change summary before any AWS calls</li><li>Confirmation prompts (with a DRY_RUN mode for preview)</li><li>Detailed per-function comments explaining the recommendation</li><li>A companion rollback script in case something goes wrong</li><li>For CI/CD: batch mode without prompts, but still with safety guards</li></ul><p>Most tools stop at reporting. Lambda Rightsizer generates production-ready bash scripts that handle all of this.</p><h3>Architecture: Built for Real-World Complexity</h3><p>Here’s what happens under the hood:</p><pre>┌─ CLI (main.py)<br>│  ├─ Parses arguments / loads .env config<br>│  └─ Validates AWS credentials<br>│<br>├─ Discovery (lambda_discovery.py)<br>│  └─ Paginates ListFunctions → FunctionRecord list<br>│<br>├─ Metrics Collection (metrics_analyzer.py) — PARALLEL<br>│  ├─ Tries Logs Insights first<br>│  ├─ Falls back to Logs filter<br>│  └─ Falls back to CloudWatch Metrics<br>│  └─ Returns peak, avg, min, P95 memory + data source<br>│<br>├─ Optimization (optimizer.py)<br>│  ├─ Calculates utilization %<br>│  ├─ Applies utilization band logic<br>│  ├─ Computes safety floor (peak × 1.20 / 64 MB steps)<br>│  ├─ Risk-scores the recommendation<br>│  └─ Returns OptimizationRecord<br>│<br>└─ Output (report_generator.py + remediation_script_generator.py)<br>   ├─ Console table (colorized, sortable by risk)<br>   ├─ CSV export (for spreadsheet analysis)<br>   ├─ JSON report (structured, machine-parseable)<br>   ├─ remediation_&lt;ts&gt;.sh (apply changes safely)<br>   ├─ rollback_&lt;ts&gt;.sh (restore on demand)<br>   └─ backup_&lt;ts&gt;.json (original config snapshot)</pre><p>Key design decisions:</p><ul><li>Parallel metrics collection — ThreadPoolExecutor fetches CloudWatch data for multiple functions concurrently (configurable worker count)</li><li>Fallback chains — tries three strategies in order; no failure == no skip</li><li>Timestamped outputs — every run creates a unique folder; nothing overwrites</li><li>Built-in rollback — every applied change can be undone with a single script</li><li>Safety-first remediation — generated bash script has multiple confirmation layers</li><li>Zero production impact by default — the analysis tool is read-only; scripts are generated but require explicit execution</li></ul><h3>Key Features You’ll Love</h3><h3>1. Console Dashboard</h3><pre>════════════════════════════════════════════════════════════════════════════════<br>                            LAMBDA RIGHTSIZER<br>Generated: 2024-03-15 14:23:01 UTC              Region: us-east-1<br>Lookback:  14 days                              Waste threshold: 40%<br>════════════════════════════════════════════════════════════════════════════════</pre><pre>| Function              | Runtime    | Alloc | Peak | Avg | P95 | Util | Waste | Status      |<br>|---                    |---         |---    |---  |---  |---  |---   |---    |---          |<br>| payment-processor     | python3.11 | 1024  | 87  | 72  | 85  | 7%   | 91.5% | over-prov   |<br>| order-handler         | nodejs18   | 512   | 201 | 178 | 198 | 34.8%| 60.7% | over-prov   |<br>| image-resizer         | python3.11 | 256   | 231 | 198 | 228 | 77.3%| 9.8%  | watch       |<br>| auth-validator        | nodejs18   | 128   | 98  | 81  | 96  | 63.3%| 23.4% | optimal     |<br>|---                    |---         |---    |---  |---  |---  |---   |---    |---          |<br>| SUMMARY               |            |       |     |     |     |      |       |             |<br>| Total analyzed        | 5          | Over-prov: 2    | Optimal: 1              |<br>| Potential savings     | 1152 MB    | Under-prov: 0   | Watch: 1                |</pre><p>Colorized, sorted by severity, immediately tells you where the waste is.</p><h3>2. Three Data Strategies (With Fallback)</h3><p>Not all functions generate logs. Not all have sufficient CloudWatch metrics history. Lambda Rightsizer tries three approaches:</p><ul><li>CloudWatch Logs Insights — fast, server-side, cheap (if you have logs)</li><li>CloudWatch Logs filter — slower, but parses raw REPORT lines</li><li>CloudWatch Metrics — last resort; always available even without logs</li></ul><p>Pick the first one that succeeds for each function. No “insufficient data” if there’s any signal at all.</p><h3>3. Multi-Region Support</h3><p>Scan one region, or parallelize across multiple regions. Each run produces isolated reports, so you can compare regions side-by-side.</p><h3>4. Filtering</h3><p>Scan all functions, or target specific ones by name substring:</p><pre>python -m lambda_rightsizer.main --filter payment,order,auth</pre><p>Perfect for focusing on high-risk service domains.</p><h3>5. Function-Level Risk Scoring</h3><p>Every recommendation comes with a 1–5 risk score. High-risk changes (score ≥ 4) require explicit confirmation:</p><pre># Preview before applying<br>DRY_RUN=true bash remediation_20240315T142301Z.sh</pre><pre># Apply interactively (requires confirmation)<br>bash remediation_20240315T142301Z.sh</pre><pre># Apply in batch mode (auto-approve low-risk, skip high-risk)<br>SKIP_HIGH_RISK=true bash remediation_20240315T142301Z.sh</pre><pre># Force apply all (CI/CD with full automation)<br>FORCE=true bash remediation_20240315T142301Z.sh</pre><h3>6. Instant Rollback</h3><p>Companion rollback script restores every function to its pre-change memory value:</p><pre>bash rollback_20240315T142301Z.sh</pre><p>The backup JSON file ensures you can always reconstruct the original state, even weeks later.</p><h3>7. Configurable Thresholds</h3><p>All analysis parameters are tunable via .env:</p><pre>LOOKBACK_DAYS=30                  # analyze last 30 days instead of 14<br>UTIL_REDUCE_THRESHOLD=25          # be more aggressive on reductions<br>UTIL_INCREASE_THRESHOLD=85        # be more conservative on increases<br>SAFETY_BUFFER_FACTOR=1.30         # add 30% headroom instead of 20%<br>MIN_INVOCATIONS=20                # skip functions with &lt; 20 samples</pre><h3>8. JSON Reports for Automation</h3><p>All analysis output is available in JSON for downstream automation:</p><pre>{<br>  &quot;meta&quot;: {<br>    &quot;generated_at&quot;: &quot;2024-03-15 14:23:01 UTC&quot;,<br>    &quot;region&quot;: &quot;us-east-1&quot;,<br>    &quot;lookback_days&quot;: 14<br>  },<br>  &quot;summary&quot;: {<br>    &quot;total&quot;: 5,<br>    &quot;over_provisioned&quot;: 2,<br>    &quot;total_savings_mb&quot;: 1152<br>  },<br>  &quot;functions&quot;: [<br>    {<br>      &quot;function_name&quot;: &quot;payment-processor&quot;,<br>      &quot;allocated_mb&quot;: 1024,<br>      &quot;recommended_mb&quot;: 128,<br>      &quot;status&quot;: &quot;over_provisioned&quot;,<br>      &quot;risk_score&quot;: 2,<br>      ...<br>    }<br>  ]<br>}</pre><h3>Real-World Impact</h3><p>Let’s talk numbers. We ran Lambda Rightsizer against a mid-sized production account (60 functions, us-east-1):</p><p>MetricBeforeAfterTotal allocated memory31,680 MB18,240 MBOver-provisioned functions180Estimated annual spend$4,200$2,400Savings — $1,800/year</p><p>That’s from a single region. Multi-region accounts often see $5,000–$10,000 annual savings.</p><p>Better still: three of the originally under-provisioned functions actually improved reliability. Increased memory allocation reduced timeout events by 40%.</p><h3>Getting Started in 5 Minutes</h3><h3>1. Clone and install</h3><pre>git clone &lt;repo&gt;<br>cd lambda-rightsizer<br>python -m venv .venv<br>source .venv/bin/activate  # Windows: .venv\Scripts\activate<br>pip install -r requirements.txt</pre><h3>2. Set up IAM</h3><p>Attach the provided read-only policy to your analysis identity:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    { &quot;Sid&quot;: &quot;LambdaDiscoverFunctions&quot;, &quot;Action&quot;: [&quot;lambda:ListFunctions&quot;], &quot;Resource&quot;: &quot;*&quot; },<br>    { &quot;Sid&quot;: &quot;CloudWatchLogsInsights&quot;, &quot;Action&quot;: [&quot;logs:StartQuery&quot;, &quot;logs:GetQueryResults&quot;], &quot;Resource&quot;: &quot;arn:aws:logs:*:*:log-group:/aws/lambda/*&quot; },<br>    { &quot;Sid&quot;: &quot;CloudWatchMetrics&quot;, &quot;Action&quot;: [&quot;cloudwatch:GetMetricStatistics&quot;], &quot;Resource&quot;: &quot;*&quot; }<br>  ]<br>}</pre><p>For remediation, add the second policy to a separate role that’s only assumed when applying changes.</p><h3>3. Configure</h3><p>Copy .env.example to .env and edit:</p><pre>AWS_REGION=us-east-1<br>AWS_PROFILE=default<br>LOOKBACK_DAYS=14<br>OUTPUT_DIR=./output</pre><h3>4. Run the analysis</h3><pre>python -m lambda_rightsizer.main</pre><p>No changes are made. You’ll get a colorized console report + CSV + JSON + remediation scripts.</p><h3>5. Review and apply</h3><pre>cd output/20240315T142301Z/</pre><pre># Preview what would change<br>DRY_RUN=true bash remediation_20240315T142301Z.sh</pre><pre># Apply the changes<br>bash remediation_20240315T142301Z.sh</pre><pre># If anything goes wrong, instantly rollback<br>bash rollback_20240315T142301Z.sh</pre><p>That’s it.</p><h3>Safety Guarantees Built In</h3><h3>Read-Only by Default</h3><p>Running the analysis tool makes zero AWS API calls that modify state. It only reads.</p><h3>Pre-Change Summary</h3><p>The generated bash script prints out every change before asking for confirmation. You can see exactly what will happen.</p><h3>DRY_RUN Mode</h3><p>Preview all changes without touching anything:</p><pre>DRY_RUN=true bash remediation_20240315T142301Z.sh</pre><h3>Risk Scoring</h3><p>High-risk recommendations are flagged and require explicit per-function confirmation, even in automated deployments.</p><h3>Immediate Rollback</h3><p>Every applied change can be undone in seconds with the companion rollback script and backup JSON.</p><h3>20% Safety Headroom</h3><p>The tool never recommends below peak observed memory × 1.20, rounded to the nearest 64 MB. This protects against cold-start spikes and statistical outliers.</p><h3>No Destructive Side Effects</h3><p>Changing Lambda memory allocation does not redeploy code, modify environment variables, change IAM roles, or affect VPC settings. It takes effect on the next cold start.</p><h3>Why We Built This (And What We Learned)</h3><p>We realized that cost optimization is only possible at scale. One function? Easy to analyze manually. Fifty functions? You need tooling. Two hundred functions? You <em>must</em> automate.</p><p>The other lesson: safety first. Teams won’t adopt an optimizer that requires blind faith. Every recommendation needs context, risk scoring, and an escape hatch. Rollback is not an afterthought — it’s a core feature.</p><p>We also learned that flexibility matters. Different teams have different risk tolerances. Some want aggressive optimization; others prefer conservative 30% headroom. The tool needed to support both via configuration, not code rewrites.</p><p>Finally: data quality is everything. We built three fallback strategies for metrics collection because real-world Lambda deployments vary wildly. New functions have no history. Old functions have rotated logs. Some never use CloudWatch Logs at all. A production tool needs to degrade gracefully, not fail.</p><h3>Future Enhancements</h3><p>We’re actively working on:</p><ol><li>Cost projection module — estimate AWS bill impact of recommended changes before applying</li><li>Concurrent execution analysis — factor in concurrent execution reservations into recommendations</li><li>Duration analysis — recommend compute-optimized runtimes alongside memory changes</li><li>Cost anomaly detection — flag functions with sudden cost spikes</li><li>Multi-region orchestration — apply changes across regions in a single command with per-region rollback</li><li>Slack / PagerDuty integration — notify teams when optimization opportunities exceed a threshold</li><li>RI / Savings Plan leverage — factor in reserved capacity into recommendations</li></ol><h3>Open Source &amp; Contribution</h3><p>Lambda Rightsizer is open source. We welcome contributions:</p><ul><li>Bug reports and feature requests</li><li>Additional data collection strategies</li><li>Integration with other AWS cost tools (CloudCraft, Infracost, etc.)</li><li>Regional pricing data expansion</li><li>Language pack translations</li></ul><h3>Conclusion</h3><p>AWS Lambda over-provisioning is real, widespread, and fixable. But manual optimization doesn’t scale.</p><p>Lambda Rightsizer changes the equation: automated discovery, safe analysis, and ready-to-apply remediation, with built-in rollback and risk scoring.</p><p>In a typical account, you can find $2,000–$10,000 in annual savings in 30 minutes. More importantly, you’ll gain visibility into how your functions actually behave in production — and that visibility is worth more than the cost savings.</p><p>Stop leaving money on the table. Get started today:</p><pre>git clone &lt;repo&gt;<br>cd lambda-rightsizer<br>python -m lambda_rightsizer.main</pre><p>Then run one remediation script.</p><p>Your CFO will thank you.</p><h3>Questions?</h3><ul><li>Documentation: See the <a href="https://github.com/rushabh-ufo/lambda-rightsizer">full README</a> for detailed configuration options, architecture diagrams, and troubleshooting</li><li>Examples: Check output/ for sample reports and scripts from real-world runs</li><li>Issues: Open a <a href="https://github.com/rushabh-ufo/lambda-rightsizer">GitHub</a> issue or PR with questions, bugs, or feature requests</li></ul><h3>Connect Me</h3><p>Follow me on <a href="https://www.linkedin.com/in/rushabh-trivedi-361094168/">LinkedIn</a></p><p>If you like this give a star on the <a href="https://www.linkedin.com/in/rushabh-trivedi-361094168/">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bce15edcda1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/stop-wasting-money-on-lambda-automate-right-sizing-across-your-aws-account-8bce15edcda1">Stop Wasting Money on Lambda: Automate Right-Sizing Across Your AWS Account</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CloudWatch Alerts — Custom email notification using AWS Lambda]]></title>
            <link>https://awstip.com/cloudwatch-alerts-custom-email-notification-using-aws-lambda-c8de7a1101ac?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8de7a1101ac</guid>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 03:32:24 GMT</pubDate>
            <atom:updated>2025-12-30T12:16:51.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>CloudWatch Alerts — Custom email notification using AWS Lambda</h3><p>Often times we come across the requirement where we need to send some alert based on the cloudwatch trigger. If we take a very simple example of the cost alert from the cloudwatch (which is must for monitoring the cost and keeping you alert if going beyond the budget), you set an upper bound on the cost and trigger an alert if the overall bill is crossing that bound you set.</p><p>Cloudwatch alarm has following components as shown in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*ERYO0RediyuYAjcP.png" /><figcaption>CloudWatch Alarm components (Image courtesy: <a href="https://trailhead.salesforce.com/content/learn/modules/monitoring-on-aws/prevent-and-troubleshoot-issues-with-cloudwatch-alarms">https://trailhead.salesforce.com/content/learn/modules/monitoring-on-aws/prevent-and-troubleshoot-issues-with-cloudwatch-alarms</a>)</figcaption></figure><p>You set the Metric on which you need to monitor, the Threshold value which is the upper bound or the lower bound and the Time period during which you monitor the threshold value to be crossed.</p><p>That is very brief about the CloudWatch alert and how it works. Now Let’s deep dive in to the actual problem which I faced few days back and how I solved it.</p><p><strong>Problem:</strong></p><p>There are few lambdas in the environment which are running as per the schedule and they are generating logs. If there is a <em>specific term</em> in the log is found, we have to send an alert over email.</p><p>Sounds pretty straight?? yeah, but it has quite a few moving parts —</p><ol><li>You have to set custom metrics</li><li>Filter the log for the expected term</li><li>Trigger SNS</li><li>Send email with custom template using lambda</li></ol><p>here is a solution diagram for the mentioned solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*iZ_9nYdkFhNEhRgl1evbsw.png" /></figure><p>I will walk you through the steps to implement this solution.</p><ol><li>Create a custom metric filter in the log groups in the cloudwatch console</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbzfp9_UHi4nV9xlRiTo_g.png" /></figure><p>2. Define the filter pattern you want to filter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLlkN6_rxANWae0QOtX0Fw.png" /></figure><p>3. Select the metric namespace, metric name and value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ettmjRmroSBsj5SQf8dZg.png" /></figure><p>4. Create an Alarm and add the metric to check in that alarm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUyplKZYXdzE_rXj-MX8gg.png" /></figure><p>select the metric</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6j7OCB6gAxByjEXaKvJDNw.png" /></figure><p>Select the threshold</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVV4e0hqiQmUETu0UQYfkA.png" /></figure><p>5. Now create and SNS topic to subscribe in the alarm</p><p>6. You will need a lambda function to trigger the email with the custom email template. <a href="https://github.com/rushabh-ufo/cloudwatch-custom-alerts">Here</a> is the repository for the same.</p><p>7. Create a subscription in the SNS to for the lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft5ZUq0UXW9ycF7okuYDvg.png" /></figure><p>8. Now come back to the Cloudwatch alarm, and select the SNS topic. You should be able to see the lambda function subscription like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXlPoENnEmaPftUnl4lByg.png" /></figure><p>Hit Next and then Next. And you are almost done with the framework setup for the alarm.</p><p>Now let me explain you more on the Lambda function and what it does.</p><p>In order to send the SNS email with the custom template, you need to have a lambda function which handles the request from SNS -&gt; creates the custom email template -&gt; send email using the SES.</p><p>here is the sample code for the lambda.</p><pre>import { SESClient, SendEmailCommand } from &quot;@aws-sdk/client-ses&quot;;<br>const ses = new SESClient({ region: &#39;ap-south-1&#39;}); // change region if needed<br><br>export const lambdaHandler = async (event, context) =&gt; {<br>    console.log(&quot;Event received:&quot;, event);<br><br>    try {<br>        const snsRecord = event.Records[0].Sns;<br>        console.log(&quot;SNS Record:&quot;, snsRecord);<br>        const messageStr = snsRecord.Message;<br>        const messageObj = JSON.parse(messageStr);<br><br>        console.log(&quot;Parsed message:&quot;, messageObj);<br><br>        const alarmName = messageObj.AlarmName;<br>        const alarmDescription = messageObj.AlarmDescription || &#39;&#39;;<br>        const currentState = messageObj.NewStateValue;<br>        const reason = messageObj.NewStateReason;<br>        const timeStamp = snsRecord.Timestamp;<br>        const region = messageObj.Region;<br><br>        let alarmCategory = &#39;WARNING&#39;; // you can have custom logic to decide if this is WARNING or ERROR<br><br>        const environment = &#39;Staging&#39; // this can be decided based on the attributes from the message from SNS<br><br><br><br>        const htmlBody = `<br>            &lt;h2 style=&quot;color:#D32F2F;&quot;&gt;🔥 ${environment} | CloudWatch Alarm Triggered - ${alarmCategory}&lt;/h2&gt;<br>            &lt;p&gt;&lt;strong&gt;Alarm Name:&lt;/strong&gt; ${alarmName}&lt;/p&gt;<br>            &lt;p&gt;&lt;strong&gt;Status:&lt;/strong&gt; ${currentState} &lt;/p&gt;<br>            &lt;p&gt;&lt;strong&gt;Reason:&lt;/strong&gt; ${reason} &lt;/p&gt;<br>            &lt;p&gt;&lt;strong&gt;Timestamp:&lt;/strong&gt; ${timeStamp}&lt;/p&gt;<br>            &lt;hr&gt;<br>            &lt;p style=&quot;color:#888;&quot;&gt;This is an automated alert.&lt;/p&gt;<br>        `;<br><br>        const params = {<br>            Source: &quot;info@yourdomin.com&quot;, // update this to your verified SES email<br>            Destination: { ToAddresses: [&quot;test@example.com&quot;] }, // update this to have the list of recipient<br>            Message: {<br>                Subject: { Data: `🚨 ${alarmCategory} | ${environment} | CloudWatch Alert: ${alarmName}` },<br>                Body: { Html: { Data: htmlBody } }<br>            }<br>        };<br><br>        await ses.send(new SendEmailCommand(params))<br><br>    } catch (err) {<br>        console.error(&quot;Error processing alert:&quot;, err);<br>        throw err;<br>    }<br>  };</pre><p>If everything is configured properly, you should see alerts email like this in your mail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpdhhNB_njL1NTyHp1fjTw.png" /></figure><p>Thank you for following till this point. Let me know here in comments how was your experience configuring the alarms and also if you have got any errors I would be happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8de7a1101ac" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/cloudwatch-alerts-custom-email-notification-using-aws-lambda-c8de7a1101ac">CloudWatch Alerts — Custom email notification using AWS Lambda</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Security: Building Trust in the Cloud]]></title>
            <link>https://awstip.com/serverless-security-building-trust-in-the-cloud-b31256ba2901?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31256ba2901</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 30 May 2025 15:45:50 GMT</pubDate>
            <atom:updated>2025-05-30T15:45:50.018Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I got an awesome opportunity to speak in the Devloper talks at AWS Summit Bangaluru-2025. I had applied for the talk and luckily my talk was selected. Now the real struggle starts — gathering all the scattered thoughts from your mind, relate them and finally put them in a presentable format which you can explain in a very leyman’s terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y-i2F8pLO1vz7nmM" /></figure><p>I would like to compile the talk here in a blog.</p><p>There are few key aspects in the serverless security which need to be covered to make a secure application. we need to consider security at different layers of your application.</p><ul><li>Identity and Access Management (IAM)</li><li>API gateway</li><li>Lambda Function</li><li>Data</li><li>Monitoring and Logging</li><li>DDoS Protection</li></ul><blockquote>Security in serverless isn’t about protecting servers — it’s about protecting identities, permissions, and the code itself.<br> — Chris Munnas<br>AWS Serverless Specialist</blockquote><p>Before diving deep into the details, lets have a look at where does the usage of the serverless services stands today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_58H99HhnyIBHvEL86vW7A.png" /><figcaption>Source: <a href="https://aws.amazon.com/serverless/10th-anniversary/">https://aws.amazon.com/serverless/10th-anniversary/</a></figcaption></figure><p>Let’s understand the unique security considerations which makes the security in the serverless much different and tricky than the conventional systems with servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV8lRTXABoYKqoUsvpfWKQ.png" /><figcaption>Unique security considerations</figcaption></figure><p>Let’s explore each aspect in above image one by one in details.</p><ol><li><strong>Short Lived Execution of Lamda Function</strong> — The Lambda functions are ephemeral by nature. They spin-up quickly when invoked and vanish off once execution is done. This makes harder to maintain a stateful security controls and brings down a security implication that the attacks need to be detected fast.</li><li><strong>Increased Surface Area</strong> — Typically a serverless app contains too many small, purpose build functions (usually known as microservices). This results in a broader attack surface which increases chances of misconfigured permissions, unpatched dependencies etc.</li><li><strong>Event-Driven Nature</strong> — Functions are invoked by various events like API gateway, S3, SNS etc. Any misconfigured even can lead to a security issue.</li><li><strong>Dependency on Managed Service</strong> — A typical serverless application uses multiple managed services like dynamoDB, API gateway, S3, SQS, SNS. In case if we fail to configure the permissions properly can lead to un-intended data access/Excessive privilege exposure.</li><li><strong>Multi-Tenant Risks</strong> — In a multi-tenant environment, there are chances that the data is stored on a shared storage like a same dynamodb table or a common s3 bucket. Failure on managing permissions properly can lead to exposing the data of one tenant to another.</li></ol><p>Now having the base set for the detailed understanding on various security aspects, lets have a walk through on security at service level.</p><p><strong>Identity and Access Management (IAM)</strong></p><ol><li><strong>Principle of Least Privilege</strong> — Assign roles and policies to each Lambda function. Also you want to ensure that the function has access to the resources only which it needs. Avoid sharing roles across functions.</li><li><strong>IAM Role Scoping</strong> — Scope IAM roles narrowly and specifically to the function’s purpose. Avoid using wildcards ‘*’ unless necessary.</li><li><strong>Custom IAM Policies</strong> — Avoid using managed policies from the IAM. Create custom tailored policies.</li></ol><blockquote>Use tools like <strong>AWS Access Analyzer</strong> and <strong>IAM Access Advisor</strong> to audit and optimize permissions continuously.</blockquote><p>Now your permissions are all set! next comes is the API Gateway.</p><p><strong>API Gateway</strong></p><p>There are many key areas on which you can apply security for securing the API gateway. I will not cover all here just to keep this blog small and precise.</p><ol><li><strong>Lambda Authorizer</strong> — You can evaluate token, Generate allow/Deny policy, and optionally populate the context attributes in the request context.</li><li><strong>API keys and usage plans</strong> — now your authorized users are coming into the system, but there are chances that some of the authorized users can make thousands of API callas and would hamper overall performance of your system or may cause un-availability of the services. you can define API keys for each of your tenant and associate them with the usage plans — say this API key is eligible for 100 request/day</li><li><strong>OAuth and OpenId Connect </strong>— For more advanced authentication scenarios, you can use OAuth 2.0 or OpenID Connect (OIDC) via Amazon Cognito.</li></ol><p><strong>Lambda Function</strong></p><ol><li><strong>Principal of Least Privilege</strong> — Assign minimal IAM permissions to Each Lambda. Avoid using wildcards like s3:* or dynamodb:*.</li><li><strong>Patch Dependencies and Libraries</strong>​ — Regularly update function’s dependencies. Use tools like npm audit, pip-audit, or Snyk to detect vulnerabilities.</li><li><strong>Secure Environment Variables</strong> — Do not hardcode environment variables rather use the secrets manager and KMS.</li><li><strong>Monitor and Log Everything </strong>— Enable CloudWatch Logs and use AWS X-Ray for tracing. Use CloudTrail to track changes to Lambda and IAM policies. Set up Amazon GuardDuty for real-time threat detection</li><li><strong>Set Timeouts and Memory Limits</strong> — smartly set the timeouts and the memory limits</li><li><strong>Network Security with VPC Integration​ </strong>— For sensitive workload, prefer to run the Lambda functions inside thr VPC.</li><li><strong>Code Signing </strong>— Implement code signing to verify that the code is not tempered.</li></ol><p><strong>Data Security</strong></p><p>You have reached to the lambda, now lambda is generating/fetching data into an end system. You need to have a layer of security there on the data also.</p><p>Primarily there are 2 main aspects of the data security</p><ol><li>Encryption</li><li>Secure storage</li></ol><p>Encryption can be applied at 2 level, at rest and in transit — apply KMS keys to encrypt data at rest and https/sftp to secure data in transit</p><p>Apply strict access policies and IAM permissions to protect data in the storage</p><p><strong>Monitoring &amp; Logging</strong></p><p>Observability is always a key aspect in any system epecially when you have such a event-driven and widely distributed system.<br>AWS has a suite of services at your rescue.</p><ol><li><strong>AWS CloudTrail</strong> — Tracks AWS API calls (Lambda, API Gateway, etc.)<br>Detects who invoked a Lambda, when, and from where — critical for compliance and incident response.</li><li><strong>Amazon Cloudwatch Logs</strong> — Enable Lambda logging through CloudWatch. This helps troubleshoot errors, performance bottlenecks, and anomalies. <br>Capture logs and set alarms based on the — High error rates, long execution duration, timeouts.</li><li><strong>CloudWatch Metrics</strong> — Monitor Lambda performance. Detect failures and address issues proactively.</li><li><strong>GuardDuty </strong>— Enable GuardDuty for continuous monitoring of malicious activities and security threats.</li></ol><p><strong>DDoS Protection</strong></p><ol><li><strong>AWS WAF</strong> — Use AWS WAF to protect your APIs (via API Gateway) from common web exploits such as SQL injection and cross-site scripting (XSS). It also helps in blocking malicious traffic.</li><li><strong>AWS Shield</strong> — AWS Shield provides protection against DDoS attacks. It’s important to leverage AWS Shield Advanced for more advanced DDoS protections.</li><li><strong>Rate Limiting</strong> — Set up rate limiting and quotas in API Gateway to protect against abuse and mitigate the risk of DDoS attacks.</li></ol><p>Its awesome if you have been with me and have gone through this big blog. I know there is a lot to understand and digest here. I am summarizing the checklist here for you.</p><ol><li>Use least privilege IAM</li><li>Regularly rotate the credentials</li><li>Enable observability where ever possible</li><li>Encrypt everything you can</li><li>Protect endpoints and validate inputs</li><li>Manage your secrets properly.</li></ol><p>Here is a sample serverless application architecture you can refer where I have tried to add security at all possible level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4OZOm08Xv4FOGPqoO_6yQ.png" /><figcaption>Sample Architecture</figcaption></figure><p>Thanks for reading and support. Do add comments for suggestions/improvements/discussions. I would be happy to connect with you awesome people.</p><p>You can connect with me on my <a href="https://www.linkedin.com/in/rushabh-trivedi-361094168/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31256ba2901" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/serverless-security-building-trust-in-the-cloud-b31256ba2901">Serverless Security: Building Trust in the Cloud</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate limiting on API Gateway and Lambda]]></title>
            <link>https://rushabh-ufo.medium.com/rate-limiting-on-api-gateway-and-lambda-e5890ad0bad5?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5890ad0bad5</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[api-key]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 11:26:04 GMT</pubDate>
            <atom:updated>2024-07-23T12:55:17.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cBRpVE8ZXjhHSWWQ.jpeg" /><figcaption>Sample architectural diagram for API Key usage (Ref: <a href="https://digitalcloud.training/amazon-api-gateway/">https://digitalcloud.training/amazon-api-gateway/</a>)</figcaption></figure><p>The move to a Software-as-a-service (SaaS) delivery model carries the desire of the cost and operational efficiency.</p><p>Serverless model is a fast and flexible way to implement a SaaS based application in a multi-tenant environment.</p><p>Managing cost and operational efficiency is bit challenging and tricky in a multi-tenant environment where all the tenants are accessing the same resources either in pooled or in silo model depending on the subscription tier the have subscribed to. You need a proper mechanism to control the resource usage so that one aggressive tenant does not take over all the capacity and other tenants does not get any capacity.</p><p>This can be managed by the API Keys and Usage plans.</p><p>In this blog, I will give basic idea on how you can implement a Serverless multi-tenant SaaS project with API keys and Usage plans</p><p>All you need is,</p><ul><li>AWS Account</li><li>SAM CLI installed on your machine</li><li>Little understanding on AWS CloudFormation</li></ul><ol><li>Create a serverless project using SAM CLI using one of the quick start template</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*mPDphQM0f5qa-mPn2PC6gQ.png" /><figcaption>Create a pserverless project using SAM CLI</figcaption></figure><p>This will create a project structure and it will look similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*5HKVa8Afs6OnavM1Rslwdg.png" /><figcaption>Sample project structure</figcaption></figure><p>2. Now you can build the project</p><pre>sam build<br>Starting Build use cache<br>Manifest is not changed for (getAllItemsFunction, getByIdFunction, putItemFunction), running incremental build<br>Building codeuri: D:\&gt;api-key-usage-demo runtime: nodejs20.x metadata: {} architecture: x86_64        <br>functions: getAllItemsFunction, getByIdFunction, putItemFunction<br> Running NodejsNpmBuilder:NpmPack<br> Running NodejsNpmBuilder:CopyNpmrcAndLockfile<br> Running NodejsNpmBuilder:CopySource<br> Running NodejsNpmBuilder:CopySource<br> Running NodejsNpmBuilder:CleanUpNpmrc<br> Running NodejsNpmBuilder:LockfileCleanUp<br> Running NodejsNpmBuilder:LockfileCleanUp<br><br>Build Succeeded<br><br>Built Artifacts  : .aws-sam\build<br>Built Template   : .aws-sam\build\template.yaml<br><br>Commands you can use next<br>=========================<br>[*] Validate SAM template: sam validate<br>[*] Invoke Function: sam local invoke<br>[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch<br>[*] Deploy: sam deploy --guided</pre><p>3. Deploy it. if you are deploying for the 1st time, it will prompt for few inputs</p><pre>sam deploy</pre><p>Once its deployed successfully, it will show you something like this</p><pre>2024-07-22 16:21:21 - Waiting for stack create/update to complete<br><br>CloudFormation events from stack operations (refresh every 5.0 seconds)<br>---------------------------------------------------------------------------------------------------------------------------------------------    <br>ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason                 <br>---------------------------------------------------------------------------------------------------------------------------------------------    <br>UPDATE_IN_PROGRESS                  AWS::CloudFormation::Stack          api-key-usage-demo                  User Initiated<br>UPDATE_IN_PROGRESS                  AWS::Lambda::Function               getAllItemsFunction                 -                                    <br>UPDATE_IN_PROGRESS                  AWS::Lambda::Function               getByIdFunction                     -                                    <br>UPDATE_IN_PROGRESS                  AWS::Lambda::Function               putItemFunction                     -                                    <br>UPDATE_COMPLETE                     AWS::Lambda::Function               getAllItemsFunction                 -<br>UPDATE_COMPLETE                     AWS::Lambda::Function               getByIdFunction                     -                                    <br>UPDATE_COMPLETE                     AWS::Lambda::Function               putItemFunction                     -                                    <br>UPDATE_IN_PROGRESS                  AWS::ApiGateway::UsagePlan          SampleUsagePlan                     -                                    <br>UPDATE_COMPLETE                     AWS::ApiGateway::UsagePlan          SampleUsagePlan                     -<br>UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          api-key-usage-demo                  -                                    <br>SS                                                                                                                                               <br>UPDATE_COMPLETE                     AWS::CloudFormation::Stack          api-key-usage-demo                  -                                    <br>---------------------------------------------------------------------------------------------------------------------------------------------    <br><br><br>Successfully created/updated stack - api-key-usage-demo in us-east-1</pre><p>Now let’s start adding our own customization related to APIKey, APIGateway (by default this project template will create an API Gateway anyways even if you do not declare but I like to declare my own), UsagePlans etc.</p><p>Lets start with the <strong>API Gateway</strong></p><p>On the API Gateway, we have made <strong>ApiKeyRequired: true </strong>and also added the CORS filter.</p><pre>RestAPIGateway:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Sub &quot;${AWS::StackName}-rest-api&quot;<br>      StageName: Prod<br>      Auth:<br>        ApiKeyRequired: true<br>      Cors:<br>        AllowMethods: &quot;&#39;DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT&#39;&quot;<br>        AllowHeaders: &quot;&#39;Role,Authorization,Content-Type&#39;&quot;<br>        AllowOrigin: &quot;&#39;*&#39;&quot;</pre><p><strong>API Key:</strong></p><pre>SampleAPIKeys:<br>    Type: AWS::ApiGateway::ApiKey<br>    Properties:<br>      Enabled: true<br>      Name: Sample-API-Key</pre><p><strong>Usage plan:</strong></p><p>We have applied the quota limit for 20 API calls per day</p><pre>SampleUsagePlan:<br>    Type: AWS::ApiGateway::UsagePlan<br>    Properties:<br>      ApiStages:<br>      - ApiId: !Ref RestAPIGateway<br>        Stage: Prod<br>      Quota:<br>        Limit: 20<br>        Period: DAY<br>      Description: Sample Usage Plan<br>      UsagePlanName: Sample-Usage-Plan</pre><p><strong>Bind API key with usage plan:</strong></p><pre>SampleAPIKeyUsagePlan:<br>    Type: AWS::ApiGateway::UsagePlanKey<br>    Properties:<br>      KeyId: !Ref SampleAPIKeys<br>      KeyType: API_KEY<br>      UsagePlanId: !Ref SampleUsagePlan</pre><p>Again apply build and deploy command as earlier.</p><p>Once the stack is deployed successfully, you will be able to see the the API keys and the usage plans created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLBtys2yLitEKY_k65aaYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLW996J5rGu-0AzvJ8XRyg.png" /></figure><p>You need to copy the API key from the above and use the same in the subsequent API calls.</p><p>All set!!</p><p>You try to make the requests using this API key and it should allow you till your usage quota is not reached. In this case, its should allow you for 20 API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y24YDaELWgPeWemtziHGaA.png" /></figure><p>Once you reach the limit, it will start throwing error as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHwNLO41fDUReABuoK-rag.png" /></figure><p>This is how you can implement the API keys and Usage Plans to track usage and limit quotas for tenants.</p><p>You can refer to this <a href="https://github.com/rushabh-ufo/api-key-demo">repo</a> for the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5890ad0bad5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing AI Code Generation Tools]]></title>
            <link>https://rushabh-ufo.medium.com/comparing-ai-code-generation-tools-2e4b80bf6325?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4b80bf6325</guid>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[aws-codewhiserer]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[tabnine]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 12:43:24 GMT</pubDate>
            <atom:updated>2023-06-15T12:43:24.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the arrival of ChatGPT, there is a tremendous increase in AI tools which can help you in your daily chores starting from answering a simple question, audio/video generation, legal documentation, chatbots to code generation.</p><p>Yes, you heard it right you can generate good amount of code using these code generation tools and save fair amount of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*3oAs0mVT8KRXiYWG.jpg" /></figure><p>Few days back I got to compare the AI code generation tools. So I compared 3 tools out of many.</p><ol><li><a href="https://github.com/features/copilot">Github Co-pilot</a></li><li><a href="https://aws.amazon.com/codewhisperer/">AWS CodeWhisperer</a></li><li><a href="https://www.tabnine.com/">Tabnine</a></li></ol><p>I will not take you in the details like since when these tools are available and on which model they are built etc. I will only highlight my observations with these 3 tools in this blog and then you can decide which one is the best suited for your need.</p><p><strong>Comparison:</strong></p><ol><li>Free Tier:</li></ol><ul><li>Github Co-pilot does not provide any free tier. 😐 You have to buy subscription plan only to check the suitability to your projects.</li><li>TabNine provides a free tier where you can use very limited set of features and evaluate the tool.</li><li>AWS CodeWhisperer provides free tier for individual developer and provides full capabilities in the free tier also.😍</li></ul><p>2. AI Capabilities</p><ul><li>Github Co-pilot is designed more for general purpose development. The main advantage of co-pilot is that it’s trained on a very large set of code base by Microsoft.</li><li>Tabnine is also designed for the general purpose development but it learns from your code base and usage patterns.</li><li>AWS CodeWhisperer — AWS does not disclose on which model it’s trained but it has best support for AWS related services and code generation. I have also experienced that AWS CodeWhisperer very good on general purpose code development too.</li></ul><p>3. Supported IDEs</p><ul><li>Github Co-pilot supports JetBrains and VisualStudio</li><li>Tabnine supports wide range of IDEs you can see <a href="https://www.tabnine.com/install">here</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0z4PWJZrYZuUWiMmTZ5_Ng.png" /></figure><ul><li>AWS CodeWhisperer supports- AWS Sagemaker Studio, JupyterLab, VS Code, JetBrains, AWS Cloud9. You can see more details <a href="https://docs.aws.amazon.com/codewhisperer/latest/userguide/language-ide-support.html">here</a>.</li></ul><p><strong>Similarities:</strong></p><ul><li>They all offer wide use case of code generation and they are queally good. With all these tools you basically define what you want to do in the comment and it will suggest</li><li>Co-pilot and CodeWhisperer are both cloud based solutions</li><li>None of these tools claim that they can generate the entire software. They just aid you in generating the code snippet which you can re-use.</li></ul><p><strong>My choice:</strong></p><p>I ended up with selecting AWS CodeWhisperer as I write many serverless code in AWS Lambda and also do development in typescript and front-end.</p><p>AWS CodeWhiperer gives you awesome capabilities to generate Lambda and AWS SDK methods. For example you need to generate the method to pull the files from S3, just method put some method name relevant like getFilesFromS3Bucket and it will create entire method for you.😃</p><p>Further, when you go to your lamdaHandler, it also provides you the suggestions to add the method calls which you have generated using the AWS CodeWhisperer. 😎</p><p><strong>Closing Words:</strong></p><p>The right selection of the AI tool for you totally depends on your use case and also, the license cost you are ready to bear 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4b80bf6325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Chat-GPT with Lambda]]></title>
            <link>https://rushabh-ufo.medium.com/integrating-chat-gpt-with-lambda-d181ea900fee?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d181ea900fee</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[sam-cli]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 11:40:04 GMT</pubDate>
            <atom:updated>2023-06-09T11:41:32.019Z</atom:updated>
            <content:encoded><![CDATA[<p>Its been while I was reading about ChatGPT and its usefulness over the tech blogs. I was curious on how to integrate ChatGPT with the application and expose API which can be consumed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxnw08phazZwR_KuvKMvKA.png" /></figure><p>So I was looking to get started and with very little effort, I was able to create a small application using AWS lambda which integrates with the OpenAI.</p><p>In this blog, I will guide you with the step by step process I followed to create my sample application.</p><p>Tools I used are:<br>1. <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a><br>2. <a href="https://www.npmjs.com/package/openai">NPM package for Open API</a></p><p>Before we start, you need to create the API keys for the chatGPT from <a href="https://platform.openai.com/account/api-keys">here</a>.</p><p>You can refer to the above link installing SAM CLI. Once the CLI is installed, you can follow with me to create the application structure which we are going to deploy to AWS. You can refer <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-command-reference.html">here</a> for the SAM CLI commands.</p><p>Create a project using sam init --name chatGPT-POC and select from the option for creating project from Quick start template or any custom template. I will go with Quick Start Template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knmwR_iBwfOF2-KJcFHqYQ.png" /></figure><p>From the template selection, I selected Serverless API template and runtime as nodejs16.x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS8Vxnz8lAIA2eUt2EX0Yw.png" /></figure><p>You can enable the X-Ray tracing and Cloudwatch Application Insights if you want.</p><p>This will create a basic application structure with few of the sample lambda functions and a template.yml file.</p><p>Before we add a new lambda handler for the chatGPT API, add the dependency in the package.json for openAI.</p><p>npm install openai --save</p><p>Now your package.json should look like this.</p><pre>{<br>    &quot;name&quot;: &quot;chatGPT-POC&quot;,<br>    &quot;description&quot;: &quot;chatGPT-POC-description&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;,<br>    &quot;private&quot;: true,<br>    &quot;dependencies&quot;: {<br>        &quot;aws-sdk&quot;: &quot;^2.799.0&quot;,<br>        &quot;openai&quot;: &quot;^3.2.1&quot;<br>    },<br>    &quot;devDependencies&quot;: {<br>        &quot;jest&quot;: &quot;^26.6.3&quot;<br>    },<br>    &quot;scripts&quot;: {<br>        &quot;test&quot;: &quot;jest&quot;<br>    }<br>}</pre><p>I have used <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html">AWS Secrets Manager</a> to store the the API key as a best practice. Right now I am copying the secret value from the AWS console. You can also add that dynamically using a script.</p><p>Create a lambda definition in the template.yaml as below. The function should have the permission to access the AWS Secrets Manager to get the secret.</p><pre> GetChatGPTPromptFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: src/handlers/get-chat-gpt-prompt.lambdaHandler<br>      Runtime: nodejs16.x<br>      Architectures:<br>      - x86_64<br>      MemorySize: 128 <br>      Timeout: 300<br>      Description: A function that returns the response from the chat prompt<br>      Policies:<br>        - Version: 2012-10-17<br>          Statement:<br>            - Action: secretsmanager:GetSecretValue<br>              Effect: Allow<br>              Resource: !Ref ChatGPTSecret<br>      Environment:<br>        Variables:<br>          SECRET_NAME: !Ref ChatGPTSecret<br>      Events:<br>        Api:<br>          Type: Api<br>          Properties:<br>            Path: /getPrompt<br>            Method: POST</pre><p>Add the lambda function in the src/hanlders folder. The lambda contains lambdaHandler which is called from the API gateway and other helper functions such as getSecretFromSecretManager, getOpenAIObject, getChatGPTPrompt.</p><p>The lambda function should look something similar to this</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const { Configuration, OpenAIApi } = require(&#39;openai&#39;);<br>AWS.config.update({region: &#39;us-east-1&#39;});<br><br>exports.lambdaHandler = async (event) =&gt; {<br>    try {<br>        const input = JSON.parse(event.body);<br>        const chatGPTSecret = await exports.get_secret_from_secretsmanager();<br>        const openai = await exports.getOpenAIObject(chatGPTSecret);<br>        const gptResponse = await exports.getChatGPTPrompt(openai, input);<br>        console.log(gptResponse);<br>        return {<br>            statusCode: 200,<br>            body: JSON.stringify(gptResponse)<br>        }<br>    } catch (error) {<br>        console.log(error);<br>        return {<br>            statusCode: 500,<br>            body: JSON.stringify(error)<br>        }<br>    }<br>}<br><br>exports.getSecretFromSecretsManager = async () =&gt; {<br>    const secretsmanager = new AWS.SecretsManager();<br>    const params = {<br>        SecretId: process.env.SECRET_NAME<br>    };<br>    const data = await secretsmanager.getSecretValue(params).promise();<br>    return data.SecretString;<br>}<br><br>exports.getOpenAIObject = async (apiKey) =&gt; {<br>    const configuration = new Configuration({<br>        apiKey<br>    });<br>    const openai = new OpenAIApi(configuration);<br>    return openai;<br>}<br><br>exports.getChatGPTPrompt = async (openai, input) =&gt; {<br><br>    const response = await openai.createCompletion({<br>        model: &#39;text-davinci-003&#39;,<br>        prompt: input.data,<br>        temperature: 1,<br>        max_tokens: 256,<br>        top_p: 1<br>    });<br>    return response.data.choices[0].text;<br>}</pre><p>Now you are done with your lambda function which connects to the chatGPT. You just need to build and deploy the application to the AWS.</p><p>Run sam build command to build the application.</p><p>Last step in this process is to deploy this stack on AWS using SAM CLI.</p><p>Run sam deploy --guided command and fill the answers in the prompt.</p><p>You can now access this API from the postman or any other similar tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aIWZzsLRBBIYFXzQEhyPw.png" /></figure><p>Our sample application is working well 😍.</p><p>Our application still has much room for the improvements like:</p><ul><li>Adding secrets value from the script on runtime</li><li>Writing test cases</li><li>Adding OpenAPI spec and validations</li><li>Adding parameters in the API call</li></ul><p>You can find the entire application in my <a href="https://github.com/rushabh-ufo/chatGPT-POC">github</a> repository.</p><p>Feel free to share your feedback on my blog that will be my fuel for the upcoming blog 😎.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d181ea900fee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips on preparing for AWS certification exam AWS-Co]]></title>
            <link>https://rushabh-ufo.medium.com/tips-on-preparing-for-aws-certification-exam-aws-co-931142496096?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/931142496096</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[solutionsarchitect]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[aws-architect]]></category>
            <category><![CDATA[cloud-architect-exam]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 13:52:37 GMT</pubDate>
            <atom:updated>2023-04-07T13:53:59.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exam preparation tips for AWS-C03</h3><p>Certifications play a vital role in our careers as a technical person. There are plenty of technical certifications available and you can choose as per your career aspirations and area of interests.</p><p>For past many years I am into the cloud space and working on AWS and I have recently got re-certified on AWS Certified Solutions Architect — Associate.</p><p>I am writing this blog to help many aspirants who wants to appear for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yJmdiPJkLQSJf9K8.png" /></figure><p>My journey with AWS started in around 2018 and I started learning and understanding AWS from you-tube videos and blogs. I got my interests developed in this space and started learning more. I took couple of courses on the Pluralsight to develop detail level understanding on different AWS services like AWS VPC, EC2, routing, subnets and other basic building blocks.</p><p>Then took an Udemy course by A Cloud Guru for AWS Certified Solutions Architect — Associate along with few practice tests. These courses costs 400–500 INR each but this gives you nice understanding on most of the use cases being asked in the actual Exam.</p><p>I took the exam after preparing for around a month and I passed it with nice score.</p><p>Now I appeared again for the same exam in 2023 and passed the same but the scenario has been changed drastically. This is because AWS updates/adds many services each year and they keep updating the exams also to keep it relevant.</p><p><strong>The major thing to note here between old exam and the new exam are —</strong></p><ol><li>old exams used to have many questions which has options as true/false where as exams in 2023 does not have any such questions</li><li>in old exams many questions had direct answers that you can get right if you have only basic understanding on AWS concepts. Where as in new exam, you need to have a good and detailed level understanding on most of the services covered in the course.</li><li>in old exam, it was OK if you do not have much hands-on. You can not say so on the current exam. I would recommend to have good hand-on with AWS console with real use cases.</li></ol><p><strong>How to prepare for the Exam</strong></p><ol><li>Take course from Udemy on AWS-C03(latest exam code) by <a href="https://www.udemy.com/course/aws-certified-solutions-architect-associate-hands-on/">Neal Devis</a> or <a href="https://www.udemy.com/course/aws-certified-solutions-architect-associate-saa-c03/">Stephan Marek</a>. I would say both are equally good.</li><li>Read through the FAQs for major services</li><li>Read through the AWS white papers</li><li>Good hands-on on the AWS console</li><li><a href="https://explore.skillbuilder.aws/learn/lp/1044/solutions-architect-learning-plan-earn-a-learning-badge">AWS Architecting course</a> on AWS Skill Builder portal. This one is really cool and AWS as promoting this platform a lot.</li><li>Go through the practice tests available in these courses. Also you can purchase other courses on practice tests which gives you good amount of understanding on scenario based questions that you can be tested in the exam (though you can not expect same questions in the exam).</li></ol><p>I am pretty sure if you do prepare well with this, there are bright chances of your passing the exam (though I have seen cases where people not passing the actual exams even if they are good on above things😢 ).</p><p>Finally, before booking your exam keep looking for discount offers😍 on AWS websites. This coupons really gives nice discounts up-to 50%.</p><p><strong>Note</strong>:<em> Bare in mind that if you are planning for appearing in the exam via Pearson Center, you have to book your slot at-least 24 hour prior to the exam.</em><br>I was not aware of this and so I had to book online proctor based exam which you can appear from home. But I would strongly recommend to go to center for exam as the proctor exam is not a good experience at all 😢.</p><p>Please comment your experiences here so that can help others prepare for the same.</p><p>Wish you all happy learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=931142496096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching on AWS]]></title>
            <link>https://rushabh-ufo.medium.com/caching-on-aws-9acacf37179?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9acacf37179</guid>
            <category><![CDATA[elasticache]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 13:15:33 GMT</pubDate>
            <atom:updated>2023-04-07T13:15:33.024Z</atom:updated>
            <content:encoded><![CDATA[<p>Caching is a very critical feature in modern applications to reduce database operations and provide fast and cost efficient performance. Caching reduces the latency by avoiding amount of database calls and providing data from available the cache. AWS provides few services where you can store the session data which includes ElastiCache and Cloudfront.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yoOaPTY6qUl6uctD.png" /></figure><p><strong>What is Caching?</strong></p><p>Caching is the process of storing frequently accessed data in a cache, which is a temporary storage area that can be accessed quickly. When a user makes a request, the web application first checks if the data is already cached. If the data is available in the cache, it is served to the user, and the web application avoids making a request to the database, thus saving time and resources.</p><p><strong>AWS Services for Session Caching</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j46BC9Mv2slIQk7u_ZHutg.png" /><figcaption>Sample Architecture for Caching</figcaption></figure><p>I am here providing a very high level overview for two caching services i.e. ElastiCache and CloudFront.</p><p><strong>Amazon ElastiCache</strong></p><p>Amazon ElastiCache is a fully managed, in-memory data store that provides high performance and low latency. ElastiCache can be used to cache session data, such as user preferences/order deatils/product catalogues etc. ElastiCache comes in two varients <br>1. Memchached<br>2. Redis</p><p>With Memcached, ElastiCache provides a simple and scalable caching solution that can be used to store key-value pairs. Memcached is ideal for simple and frequently accessed data and it supports multi-threading.</p><p>With Redis, ElastiCache provides a more powerful caching solution that can be used to store complex data structures, such as lists, sets, and hashes. Redis is ideal for more complex data and use cases that require advanced data structures.</p><p>A typical flow for the caching works as depicted in the above diagram</p><ol><li>When user requests data, the server initially checks in the cache (if the data is found, it will be returned).</li><li>If no data found, server queries the database (this is called cache miss).</li><li>once data is required data is found from DB, server stores it to the cache</li><li>For any subsequent requests, server returns from the cache only by avoiding database calls</li></ol><p><strong>Amazon CloudFront</strong></p><p>Amazon CloudFront is a content delivery network (CDN) that can be used to cache frequently accessed data, such as images, videos, and session data. CloudFront can cache session data at edge locations around the world, making it ideal for global applications with a large user base.</p><p>To use CloudFront for session caching, you would configure your web application to set appropriate caching headers for session data. When a user logs into your web application, their session data would be cached at the edge location closest to the user. Subsequent requests for that user’s session could be served directly from the cache at the edge location.</p><p><strong>Benefits of Caching with AWS</strong></p><p>Session caching with AWS services provides several benefits, including:</p><ol><li>Improved performance: By reducing the number of requests to the database, session caching can significantly improve the performance of your web application.</li><li>Cost-effective: Caching data in memory is less expensive than retrieving data from a database, which can help reduce the overall cost of running your web application.</li><li>Scalability: AWS services are designed to scale as your application grows. With ElastiCache and CloudFront, you can easily scale your caching solution to meet the needs of your application.</li><li>High availability: AWS services provide high availability and data durability, ensuring that your session data is always available when you need it.</li></ol><p><strong>Conclusion</strong></p><p>Caching is a very critical aspect for an application. You should always take care of your specific usecase in order to select the right service for the caching.</p><p>I would like to hear your feedback and experiences on caching techniques that will help me and others to make right decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9acacf37179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting-up AWS ElasticSearch]]></title>
            <link>https://rushabh-ufo.medium.com/setting-up-aws-elasticsearch-768ae401eeca?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/768ae401eeca</guid>
            <category><![CDATA[logstash]]></category>
            <category><![CDATA[aws-elasticsearch]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Fri, 05 Feb 2021 20:21:06 GMT</pubDate>
            <atom:updated>2021-02-05T20:21:06.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications requires modern solutions for performance optimizations, logging and log analysis, scalability, cost optimizations etc.</p><p>For many of the real world applications, it is required to maintain log data for a long time for audit/regulatory purposes. As a purpose of this article I will show on how to configure elastic search on AWS for capturing logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_A2nTy8NOYqWUygpgVG__g.png" /></figure><p>This article focuses on four main aspects of setting-up the elastic search:</p><ul><li>Create Elastic search on AWS</li><li>Install logstash service on EC2</li><li>Connect to Kibana</li></ul><p>Let’s just directly dive into the details on configuring the ElasticSearch service on AWS</p><p><strong>Create ElasticSearch service on AWS</strong></p><p>Using AWS console go to ElasticSearch service to configure the same.</p><ul><li>Select the environment type as per the need (use prod)</li><li>On the next page in the wizard you can select the number of nodes needed in each availability zones and the size of the instance. For production environments it’s recommended that you always distribute the instances across AZs for the failover.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*V7t8yXLYQ3h_S910L1C-4w.png" /></figure><ul><li>On the other page you have the options to restrict the access to the ES cluster. For production environments, it is highly recommended to not to have public access to the cluster. User has to tunnel through to connect to the cluster(we will see this in the later part of this article).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mD3lGjlwALqt5_13UtHxjg.png" /></figure><ul><li>To connect to the cluster you need to have user access to the console. We will create a user with user name and password. This we will use in the last step to connect to the Kibana console. Also if you are creating master user, you may not need cognito user identity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13JfDDEg1FHfuUctTaDdeA.png" /></figure><ul><li>This cluster will also need an access policy which may look something like below shown.</li></ul><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;*&quot;<br>      },<br>      &quot;Action&quot;: &quot;es:*&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:es:us-east-1:1234567XXXXX:domain/domain-name/*&quot;<br>    }<br>  ]<br>}</pre><p>We don not want to change any encryption related things for now.</p><p>And you are done with your ES cluster on AWS!!! It should look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*fjqY1Jtp0rq7bhNlvXHyGA.png" /></figure><p><strong>Installing LogStach on EC2</strong></p><p>Logstash is a service which generally is not included on a linux server. You have to install the same on the EC2. LogStash works in conjunction with the Elastic search to feed the log data to the cluster.</p><p>You have to create the repo for the logstash on the server for installing the service in /etc/yum.repos.d/ and put the following code in that.</p><pre>[logstash-6.x]<br>name=Elastic repository for 6.x packages baseurl=https://artifacts.elastic.co/packages/6.x/yum gpgcheck=1 gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch enabled=1<br>autorefresh=1<br>type=rpm-md</pre><p>Install using</p><pre>sudo yum install logstash</pre><p>Update the configuration for the logstash and point the same to the</p><pre>input { <br>  file {<br>    path =&gt; &quot;&lt;your_project_dir&gt;/logfile.log&quot;<br>    start_position =&gt; &quot;beginning&quot;<br>  }<br>}<br>output { <br>  amazon_es {<br>    hosts =&gt; [&quot;KIBANA-END-POINT-URL&quot;]<br>  }<br>  region =&gt; &lt;region-name&gt;<br>  index =&gt; &quot;Index-%{+YYYY.MM.dd}&quot; <br>  aws_access_key_id =&gt; &#39;KEY&#39;<br>  aws_secret_access_key =&gt; &#39;SECRET&#39;<br>}</pre><p>You have to start the logstash service by</p><pre>sudo service logstash start</pre><p>This should start your logstash service and that should copy your logs to the Kibana.</p><p><strong>Connecting to Kibana</strong></p><p>We have created our ES cluster as VPC access only. You will not be able to connect to the cluster directly from your machine. You will need a jump server to connect to the cluster from the VPC.</p><p>You should be easily able to connect to the same using the tunnel from your machine now.</p><pre>ssh -i ~/.ssh/your-key.pem ec2-user@your-ec2-instance-public-ip -N -L 9200:vpc-your-amazon-es-domain.region.es.amazonaws.com:443</pre><p>You can see to Kibana login screen by accessing</p><pre>https://localhost:9200/_plugin/kibana</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeaVXCJVuI4SQzbmWzvSyA.png" /></figure><p>All this looks great!!!<br>You have just setup an Elasticsearch cluster on your AWS.</p><p>Next actions,<br>Create indexes on Kibana to organize logs. You can also filter the logs using the queries on Kibana console.</p><p>You can also find official documentation for ElasticSearch <a href="https://www.elastic.co/guide/index.html">here</a>.</p><p>Looking forward for your feedback and comments!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=768ae401eeca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Front-end build using AWS Pipeline]]></title>
            <link>https://rushabh-ufo.medium.com/deploying-front-end-build-using-aws-pipeline-95bf61105853?source=rss-5a8c65a68cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/95bf61105853</guid>
            <category><![CDATA[aws-codebuild]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-code-deploy]]></category>
            <category><![CDATA[building-an-aws-pipeline]]></category>
            <dc:creator><![CDATA[Rushabh Trivedi]]></dc:creator>
            <pubDate>Mon, 30 Nov 2020 12:52:29 GMT</pubDate>
            <atom:updated>2020-11-30T12:52:29.196Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying code using pipeline can be a mess if you don’t have a single reference for the task. I have derived this article based on my experience creating deployment pipelines using multiple techniques.</p><p>Code deploy pipeline looks as depicted in below picture at high level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*V7dlv_kEZ_pgkLD0LTMc5w.png" /><figcaption>CI-CD at high level</figcaption></figure><p>Code pipeline has 3 stages:</p><ol><li>Build</li><li>Copy</li><li>Deploy</li></ol><blockquote>As a side note: services we are going to use for this task are — AWS CodeBuild, AWS S3, AWS CodeDeploy, AWS CodePipeline, IAM</blockquote><p><strong>Prerequisite:</strong></p><p>You have to install code deploy agent on target EC2 instances. Run below script in order to install the agent.</p><pre>sudo yum update<br>sudo yum install ruby<br>sudo yum install wget<br>cd /home/ec2-user<br>wget https://aws-codedeploy-ca-central-1.s3.ca-central-1.amazonaws.com /latest/install<br>chmod +x ./install<br>sudo ./install auto</pre><p>Verify the code deploy agent is running</p><pre>sudo service codedeploy-agent status</pre><blockquote>The code deploy agent is a key tool for deploying the code. It’s an intelligent piece of code which gets installed on EC2 instance and performs actual deployment tasks.</blockquote><p><strong>S3 Bucket</strong></p><p>Create a bucket in S3 with appropriate name and enable versioning. This is the bucket we are going to use to store artifacts created by the build stage.</p><p>Configure bucket policy by allowing public access and add bucket policy to restrict to the specific roles in the bucket policy. The bucket policy should look like this.</p><pre>{<br>&quot;Version&quot;: &quot;2012-10-17&quot;,<br>&quot;Id&quot;: &quot;Policy1563961797256&quot;,<br>&quot;Statement&quot;: [<br>{<br>&quot;Sid&quot;: &quot;Stmt1563961794600&quot;,<br>&quot;Effect&quot;: &quot;Allow&quot;,<br>&quot;Principal&quot;: {<br>&quot;AWS&quot;: [ <br>  &quot;arn:aws:iam::123XXXXXXXX:role/service-role/service-role-name&quot;,<br>  &quot;arn:aws:iam::123XXXXXXXX:role/service-role/AWSCodePipelineServiceRole&quot;]<br>},<br>&quot;Action&quot;: &quot;s3:*&quot;,<br>&quot;Resource&quot;: &quot;arn:aws:s3:::&lt;BucketName&gt;&quot;<br>}<br>]<br>}</pre><p>The above roles mentioned in the Principal attribute, are created automatically while creating CodeBuild project and CodePipeline respectively. Once you create these two projects you can update the roles in the policy by fetching ARN from the IAM. We do not need to create these roles explicitly.</p><p><strong>Build Stage</strong></p><p>Build stage gets the code base from the Bitbucket repository and runs the build commands to create the build. We have used GIT web hooks in as a trigger to create builds i.e. PULL_REQUEST_MERGE. Once someone approves the PR and merges to the repo, this build will trigger and pull the code base from the <strong>Development </strong>branch.</p><p>Follow below wizard to create build project.</p><ol><li>Create a build project from AWS CodeBuild</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*e-g-7ozY6_yBZVxej1gS5w.png" /></figure><p>2. Select source provider, in this case it’s bit bucket repository. You have to provide auth mechanism in order to connect with bitBucket from your AWS account. This will ask you to select repository from your account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*mA3xunxe_n7lKRjlQhegXA.png" /></figure><p>3. In the Environment section, select configuration depicted in the below snap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*7Abaz7Cx3oyoaklYHdjzPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*bnBCgT6CHJVlwWfhdLQC0g.png" /></figure><p>4. Next one is the Buildspec section. This contains the hooks required to build using AWS CodeBuild. Code build uses the buildspec.yml file as a source to run the commands for the build. You can refer the current buildspec.yml file in the below code snippet.</p><pre>version: 0.2<br>env:<br>  variables:<br>    S3_BUCKET: <strong>&lt;Bucket_Name&gt;</strong><br>    APP_NAME: angular-app<br>phases:<br>  install:<br>    runtime-versions:<br>      nodejs: 10<br>  pre_build:<br>    commands:<br>      - echo Installing source NPM dependencies... <br>      - npm install<br>      - npm install -g <a href="http://twitter.com/angular/cli">@angular/cli</a><br>  build:<br>    commands:<br>      - echo Build started on `date` <br>      - npm run build<br>      - cp appspec.yml dist/<br>artifacts:<br>  files:<br>    - &#39;**/*&#39;<br>    - dist/*<br>  # discard-paths: yes<br>  base-directory: dist</pre><p>Here in the build section, we are running build commands and also copying the <strong>appspec.yml </strong>file (I will show in next section)to the dist folder which will be used in the deploy phase.</p><p>Please refer to the snaps for the code build configuration. Specific information will be provided in the respective sections.</p><p>5. In the Artifacts section, provide the name of the bucket and the artifact name which will be deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*75Iu96Wvz-IR-mrt4O5YHg.png" /></figure><p>6. Update log group and stream details (optional but useful)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*CeIUujDoZ2wdvaugAB9piA.png" /></figure><p>Great!!! You are done with the creation of the CodeBuild project.</p><p><strong>AWS CodeDeploy</strong></p><ol><li>Create CodeDeploy application by providing name and compute platform. For our purposes, it’s EC2.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*uw33pW6UEpkKeu5cG3k_RQ.png" /></figure><p>2. Once you create application, create a deployment group under that application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcV9_zZwvRuoJVO2Vqav4g.png" /></figure><p>3. Enter group name, service role (which has access to deploy the code on your behalf). Also we are sticking with In-Place deployment type here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Rob6mArFyUOgvDjfgOLXOw.png" /></figure><p>4. Keep the <strong>Agent configuration with AWS Systems Manager </strong>and <strong>Deployment settings </strong>as defaults.</p><p>5. We are not enabling <strong>Load Balancing </strong>for now.</p><p>6. Create the deployment group.</p><p>You are done with creation of the deployment app.</p><p>Now Last step is to add glue to bind build and deploy so they act as a continuous process. We will use <strong>AWS CodePipeline </strong>for that.</p><p><strong>AWS CodePipeline</strong></p><ol><li>Enter Pipeline name and service role. Select your bucket, where you are having artifacts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*N3fuJhAHYVsQad7ysDPSPQ.png" /></figure><p>2. Select source provider</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*VtfyINOf0eJAtC3ljaFQmQ.png" /></figure><p>3. Select build project in the next wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*69J0aQ7o2XJCZgNgMHTo-Q.png" /></figure><p>4. Select Deploy project in the next wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*9yVZvxNvHP_MG41zN6_ZAA.png" /></figure><p>5. Click review and Create!</p><p>You are done with the entire pipeline.</p><p>Next actions, see your pipeline in progress!! Push the code into your branch and you will see your build will be in action.</p><p>Thinking of restricting builds from specific branch or specific conditions? Keep watching this space, I will come up with that soon.</p><p>Looking forward for your feedback and comments!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95bf61105853" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>