<?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 Sami Banerjee on Medium]]></title>
        <description><![CDATA[Stories by Sami Banerjee on Medium]]></description>
        <link>https://medium.com/@er.samibanerjee?source=rss-5acdf525b2a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vebAC8joBRzFeCVH5-rKmA.jpeg</url>
            <title>Stories by Sami Banerjee on Medium</title>
            <link>https://medium.com/@er.samibanerjee?source=rss-5acdf525b2a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@er.samibanerjee/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[How I Built an Autonomous AI Code Reviewer That Catches What Humans Miss (Free, Using Groq)]]></title>
            <link>https://medium.com/@er.samibanerjee/how-i-built-an-autonomous-ai-code-reviewer-that-catches-what-humans-miss-free-using-groq-117dbeff4805?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/117dbeff4805</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 09:38:06 GMT</pubDate>
            <atom:updated>2026-06-13T09:38:06.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7r1ktDUho8C0Q9Ukk47OQ.png" /></figure><h3>Every developer has been there.</h3><p>You spend an hour writing code, run your own checks, submit a PR, and then… the reviewer asks you to fix something you completely missed.</p><p>No, not a typo. Not an indentation issue.</p><p>Something like:</p><ul><li>You used == instead of is for comparison</li><li>You left a console.log in production code</li><li>You hardcoded a secret (oops)</li><li>You didn’t handle that edge case</li><li>You’re using for i in range(len(array)) instead of enumerate</li><li>Your function is 200 lines when it should be 50</li></ul><p>You fix it, push again, get another round of review, fix again, get another round…</p><p>Sound familiar?</p><p>Here’s the thing: it’s not the developer’s fault. And it’s not the reviewer’s fault either.</p><p>It’s just math.</p><p>A human brain reviewing 47 files with 2,000+ changed lines will miss something. That’s not a character flaw, it’s biology.</p><p>So I built an AI first-pass reviewer that catches these silly mistakes <em>before</em> the human review, so your PR goes to code review clean the first time.</p><h3>The Problem With Code Reviews (That Nobody Talks About)</h3><p>Code reviews are one of the highest-leverage practices in software development.</p><p>But here’s what nobody tells you about them:</p><p>The first round is usually wasted on things a robot could catch.</p><p>Why? Because developers submit PRs with small mistakes, reviewers catch them, developers fix them, reviewers review again.</p><p>This happens not because developers are careless, but because:</p><ol><li>After staring at your own code for hours, your brain stops seeing it</li><li>You test for correctness, not style</li><li>You follow the rules you <em>remember</em>, not the ones in the documentation</li><li>You’re focused on making it work, not on whether it matches the team’s standards</li></ol><p>And reviewers? They’re human. After the 5th file in a 47-file PR, pattern recognition gets… fuzzy.</p><p>So we created a system where:</p><p>Developer submits PR → AI catches silly mistakes → Developer fixes instantly → Human reviewer gets a clean PR</p><p>The human reviewer now only sees actual architectural decisions, logic flaws, and design choices not forgotten console.logs and mismatched naming conventions.</p><h3>What This AI Reviewer Actually Does</h3><p>Think of it as a tireless first-pass reviewer that:</p><ul><li>✅ Checks for forgotten console.log, print, or debug statements</li><li>✅ Flags hardcoded secrets, API keys, and credentials</li><li>✅ Enforces YOUR team’s coding standards (not generic best practices)</li><li>✅ Catches common mistakes (wrong comparison operators, unsafe patterns, etc.)</li><li>✅ Checks for security vulnerabilities (SQL injection risks, XSS, etc.)</li><li>✅ Verifies test coverage meets your requirements</li><li>✅ Makes sure commit messages follow your format</li></ul><p>And it does all this instantly, posting a review comment directly on the PR.</p><h3>How It Works</h3><pre>Developer submits PR<br>        ↓<br>GitHub fires webhook to our service<br>        ↓<br>AI fetches the diff + your team&#39;s coding standards<br>        ↓<br>AI reviews EVERY file, EVERY line (no fatigue, no shortcuts)<br>        ↓<br>AI posts a structured review comment on the PR<br>        ↓<br>Developer sees issues immediately, fixes them<br>        ↓<br>Developer marks &quot;ready for review&quot;<br>        ↓<br>Human reviewer gets a CLEAN PR</pre><p>Now your senior developer spends 10 minutes on architectural feedback instead of 45 minutes catching missing semicolons.</p><h3>our Secret Weapon: Your Own Coding Standards</h3><p>Here’s what makes this actually useful.</p><p>Most AI code reviewers give you generic advice: “Follow best practices,” “Use meaningful variable names.”</p><p>This system is different because it reads YOUR rules.</p><p>You create a coding_standards.md file that defines:</p><ul><li>Forbidden patterns (no eval, no innerHTML, no var)</li><li>Required patterns (use const where immutable, always validate inputs)</li><li>Naming conventions (snake_case functions, UPPER_CASE constants)</li><li>Performance requirements (no N+1 queries, paginate over 1000 records)</li><li>Testing rules (minimum 80% coverage, integration tests for APIs)</li><li>Commit message format (Conventional Commits required)</li><li>Security checklist (no secrets in code, validate all inputs)</li></ul><p>Now the AI doesn’t just review against generic rules! it reviews against YOUR rules.</p><p>This is the key insight: your standards should be automated, not just documented.</p><h3>The Architecture</h3><pre>GitHub PR Event → FastAPI Webhook → Diff Fetcher → Groq LLM → Review Formatter → GitHub Comment</pre><p>The stack:</p><ul><li>FastAPI: lightweight webhook receiver (handles thousands of requests per second)</li><li>GitHub REST API: fetch PR metadata and diffs</li><li>Groq: blazing-fast LPU inference (reviews generate in seconds, not minutes)</li><li>Python: because that’s what your CI/CD pipeline already speaks</li></ul><h3>The Code: Webhook Receiver</h3><pre># groq-github-pr-reviewer-py-be/app/main.py<br>from fastapi import FastAPI, Request, HTTPException, BackgroundTasks<br>from pydantic import BaseModel<br>import hmac<br>import hashlib<br>import os<br>from .review_agent import run_autonomous_review<br><br>app = FastAPI(title=&quot;AI PR Reviewer&quot;)<br>class WebhookPayload(BaseModel):<br>    action: str<br>    pull_request: dict<br>@app.post(&quot;/webhook/github&quot;)<br>async def github_webhook(request: Request, background_tasks: BackgroundTasks):<br>    # Verify signature<br>    signature = request.headers.get(&quot;x-hub-signature-256&quot;)<br>    secret = os.getenv(&quot;GITHUB_WEBHOOK_SECRET&quot;)<br>    body = await request.body()<br>    <br>    if not verify_signature(signature, body, secret):<br>        raise HTTPException(status_code=403, detail=&quot;Invalid signature&quot;)<br>    <br>    payload = await request.json()<br>    <br>    # Only trigger on relevant actions<br>    if payload.get(&quot;action&quot;) in [&quot;opened&quot;, &quot;reopened&quot;, &quot;synchronize&quot;]:<br>        pr_data = payload[&quot;pull_request&quot;]<br>        background_tasks.add_task(<br>            run_autonomous_review,<br>            pr_number=pr_data[&quot;number&quot;],<br>            repo_full_name=pr_data[&quot;base&quot;][&quot;repo&quot;][&quot;full_name&quot;]<br>        )<br>    <br>    return {&quot;status&quot;: &quot;received&quot;}<br>def verify_signature(signature: str, body: bytes, secret: str) -&gt; bool:<br>    if not signature:<br>        return False<br>    expected = &quot;sha256=&quot; + hmac.new(<br>        secret.encode(), body, hashlib.sha256<br>    ).hexdigest()<br>    return hmac.compare_digest(expected, signature)</pre><h3>The Code: Review Agent</h3><pre># groq-github-pr-reviewer-py-be/app/review_agent.py<br>import httpx<br>import os<br>from .github_client import get_pr_files, post_pr_comment<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;You are an expert code reviewer. Analyze the provided PR diff and return a JSON review.<br>Your review MUST follow this exact format:<br>{<br>  &quot;summary&quot;: &quot;Brief overview of changes&quot;,<br>  &quot;overallAssessment&quot;: &quot;PASS | NEEDS_WORK | REJECT&quot;,<br>  &quot;issues&quot;: [<br>    {<br>      &quot;severity&quot;: &quot;critical | major | minor&quot;,<br>      &quot;file&quot;: &quot;path/to/file.py&quot;,<br>      &quot;line&quot;: 42,<br>      &quot;description&quot;: &quot;What the issue is&quot;,<br>      &quot;suggestion&quot;: &quot;How to fix it&quot;<br>    }<br>  ],<br>  &quot;suggestions&quot;: [&quot;Improvement idea 1&quot;, &quot;Improvement idea 2&quot;]<br>}<br>Rules:<br>- Be specific, not generic<br>- Flag security issues immediately<br>- Reference your team&#39;s coding standards when relevant<br>- Suggest actual fixes, not just criticism<br>&quot;&quot;&quot;<br>async def run_autonomous_review(pr_number: int, repo_full_name: str):<br>    # Fetch PR diff<br>    files = await get_pr_files(repo_full_name, pr_number)<br>    <br>    # Build context (truncate if needed)<br>    diff_context = build_diff_context(files)<br>    <br>    # Get Groq&#39;s response<br>    review = await get_groq_review(diff_context)<br>    <br>    # Format and post to GitHub<br>    comment = format_review_comment(review)<br>    await post_pr_comment(repo_full_name, pr_number, comment)</pre><h3>Environment Setup</h3><pre># .env<br>GROQ_API_KEY=gsk_...<br>GROQ_MODEL=qwen/qwen3-32b<br>GITHUB_TOKEN=ghp_...           # Fine-grained PAT<br>GITHUB_WEBHOOK_SECRET=your_random_secret_here<br>MAX_TOKENS_PER_REVIEW=4000<br>MIN_FILE_SIZE_FOR_REVIEW=10</pre><p>Pro tip: Use a fine-grained PAT with minimum permissions:</p><ul><li>Read access to repository contents</li><li>Read access to pull requests</li><li>Write access to pull request comments</li></ul><h3>Run It Locally</h3><pre>uvicorn app.main:app --reload --host 0.0.0.0 --port 8000</pre><p>Or with Docker:</p><pre>docker-compose up -d --build</pre><h3>Expose to the Internet (For Webhooks)</h3><p>GitHub needs to reach your server publicly. For local dev:</p><pre>ngrok http 8000</pre><p>Use the HTTPS URL: https://&lt;ngrok-subdomain&gt;.ngrok.io/webhook/github</p><p>Configure in GitHub: Settings → Webhooks → Add webhook → select “Pull requests”</p><h3>Can It Review Any Repo?</h3><p>This backend can review PRs for any repository your token can access, but:</p><ul><li>You must add a webhook per repo</li><li>Your GITHUB_TOKEN must have permission to read &amp; comment in that repo</li></ul><p>For true org-wide “install once, works everywhere” behavior, the next step is converting this into a GitHub App (installation tokens + app permissions).</p><h3>The Real Impact</h3><p>Let me paint you a picture:</p><p>Before this system:</p><ul><li>Developer submits PR at 4:55 PM</li><li>Reviewer starts review at 9:00 AM next day</li><li>Reviewer finds 3 issues, requests changes</li><li>Developer fixes, resubmits</li><li>Reviewer reviews again, approves</li><li>Total time: 1 day + review cycles</li></ul><p>After this system:</p><ul><li>Developer submits PR at 4:55 PM</li><li>AI reviews within 30 seconds, posts comments</li><li>Developer fixes issues instantly (while context is fresh)</li><li>Developer marks “ready for review”</li><li>Reviewer opens a clean PR, approves in 5 minutes</li><li>Total time: Same day, one review cycle</li></ul><p>That 45-minute second review cycle? Gone.</p><p>That full day of waiting? Gone.</p><h3>The Bigger Picture</h3><p>This isn’t about replacing human reviewers.</p><p>It’s about freeing them.</p><p>Your senior developer has 10 years of experience. They should be reviewing architecture, design patterns, and complex logic not hunting for forgotten console.logs.</p><p>Let the AI handle the tedious checklist. Let humans handle the interesting decisions.</p><p>What’s your biggest code review frustration? Drop it below I’d love to hear how you’re dealing with this today.</p><h3>Key Takeaways</h3><p>✅ Catches silly mistakes that waste everyone’s time<br>✅ Enforces YOUR team’s coding standards automatically<br>✅ Posts formatted Markdown comments back to GitHub instantly<br>✅ Reduces review cycles from 2–3 to 1<br>✅ Frees senior developers for actual architectural review<br>✅ Built with FastAPI, Groq, and GitHub webhooks<br>✅ Free and open source</p><blockquote><em>If you found this useful, share it with your team. Someone else is probably wasting hours on unnecessary review cycles right now.</em></blockquote><blockquote><em>This is a demo project and the fun fact is, you can modify it to fit your requirements. Isn’t that great?!</em></blockquote><blockquote><em>Here’s the repo: </em><a href="https://github.com/er-sami777/ai-pr-reviewer/tree/py-be">ai-pr-reviewer-py-be</a><em>, if you found it useful, feel free to contribute or give it a star. It truly motivates me when people benefit from my thoughts or work. Thank you!</em></blockquote><h3>Bonus: GUI-Interface-HITL (Optional Dashboard)</h3><p>If you also want a true human-in-the-loop flow, the repo includes GUI-Interface-HITL (branch: main): a React dashboard that can list accessible repos, detect PR activity, generate review drafts, and let a human approve/edit before publishing the final PR comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117dbeff4805" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Every DevOps Engineer Should Understand Merkle Trees ]]></title>
            <link>https://medium.com/@er.samibanerjee/why-every-devops-engineer-should-understand-merkle-trees-7aeb221526f7?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aeb221526f7</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[distributed-system-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 19:50:11 GMT</pubDate>
            <atom:updated>2026-04-08T19:50:11.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vU2xfwowq61ilw3yYA06PA.png" /></figure><p><strong>Let me tell you a quick story….</strong></p><p>Imagine you and I are working on a system where trust is… optional.<br>Not because we’re shady, but because systems break, networks lie, and data gets corrupted.<br>Now suppose I send you a huge file, say 10GB.</p><blockquote><strong>You ask:</strong> <em>“How do I know this is the exact file you sent?”</em></blockquote><blockquote><strong>I could say:</strong><br> → <em>“Trust me bro. 💪”</em></blockquote><p>But we’re engineers. We don’t do that here.</p><blockquote><strong>You might think:</strong><br><em>“Cool, I’ll hash the entire file and compare.”</em></blockquote><p><em>If you are from a non-tech background or don’t know what a </em><strong><em>hash</em></strong><em> is, here it is in simple terms:</em></p><p><em>👉 A hash is like a </em><strong><em>digital fingerprint of data</em></strong></p><ul><li><em>You give it any input (file, text, anything)</em></li><li><em>It gives you a fixed-length unique string</em></li></ul><p><em>Example:</em></p><pre>hello → 2cf24dba5fb0a30e...</pre><p><em>Even a tiny change:</em></p><pre>hello → Hello</pre><p><em>Gives a completely different hash.</em></p><p><em>So hashes are used to:</em></p><ul><li><em>Verify data integrity</em></li><li><em>Detect changes instantly</em></li><li><em>Ensure no tampering happened</em></li></ul><h3>🥲 Now back to the problem</h3><p>Hashing the whole file works… but what if:</p><ul><li>The file is massive?</li><li>You only downloaded 1% of it?</li><li>Or you’re in a distributed system where nodes only share chunks?</li></ul><p>Recomputing everything is expensive. Slow. Painful.</p><p>That’s where things get interesting.</p><h3>🌳 Enter: Merkle Tree (aka the genius idea)</h3><p>A Merkle Tree is basically a <strong>smart way of proving data integrity without checking everything</strong>.</p><p>Let’s build intuition the way I understood it.</p><h3>🍫 Think of it like a chocolate bar</h3><p>You break a chocolate into pieces:</p><pre>D1, D2, D3, D4</pre><p>Now instead of trusting the whole bar, you:</p><ul><li>Create a fingerprint (hash) of each piece</li><li>Then combine fingerprints and fingerprint those</li><li>Repeat until you get one final fingerprint</li></ul><p>That final fingerprint = <strong>Merkle Root</strong></p><h3>🔁 Step-by-step</h3><ol><li>Take your data chunks</li><li>Hash each chunk → small fingerprints</li><li>Combine 2 fingerprints → hash again</li><li>Keep going up</li><li>End up with ONE hash</li></ol><p>Boom. That’s your tree.</p><h3>🤯 The “Ohhh…” moment</h3><p>Here’s where it clicked for me:</p><p>👉 If any tiny piece changes, the top hash changes</p><p>Like domino effect:</p><pre>D3 changes → H3 changes → parent hash changes → root changes</pre><p>So instead of checking everything…</p><p>You just check:</p><blockquote><em>“Does the root match?”</em></blockquote><h3>⚡ Even cooler: Partial verification</h3><p>Now suppose you only care about <strong>D3</strong>.</p><p>You don’t need the full dataset.</p><p>You just need:</p><ul><li>Its own hash</li><li>Its sibling hash (H4)</li><li>The upper hash (H12)</li></ul><p>That’s it.</p><p>This is called a <strong>Merkle Proof</strong>.</p><p>And this is where the magic really hits.</p><h3>🚀 Where this is actually used (real-world stuff)</h3><h3>⛓ Blockchain (Bitcoin, Ethereum)</h3><p>Every block stores a Merkle root of transactions.</p><p>Meaning:</p><ul><li>You can verify a transaction</li><li>Without downloading the full block</li></ul><p>That’s insane efficiency.</p><h3>🧠 Git (yes, your daily tool)</h3><p>Git is basically a Merkle tree system in disguise.</p><ul><li>Every commit → hash</li><li>Every file → hash</li><li>Entire repo → connected hashes</li></ul><p>That’s why:</p><ul><li>Git detects changes instantly</li><li>History is tamper-proof</li></ul><h3>☁️ Distributed Systems</h3><p>Think:</p><ul><li>Kubernetes configs</li><li>Distributed storage (S3-like systems)</li><li>CDN sync</li></ul><p>Merkle trees help:</p><ul><li>Detect changes quickly</li><li>Sync only what’s needed</li></ul><h3>🛠️ When should YOU use it?</h3><p>Use Merkle Trees when:</p><h3>✅ Data is large</h3><p>Logs, backups, datasets, blockchain-like structures</p><h3>✅ You need trust without trust</h3><p>Zero-trust systems, distributed nodes</p><h3>✅ You want efficient sync</h3><p>Only transfer what changed, not everything</p><h3>✅ You care about tamper detection</h3><p>Security, audit logs, integrity systems</p><h3>🔧 What YOU can build with this (ideas for you)</h3><p>Since you’re into DevOps + systems, these are 🔥 ideas:</p><h3>1. 🧾 Incremental Backup Tool</h3><ul><li>Store file chunks</li><li>Use Merkle trees to detect changes</li><li>Only upload modified chunks</li></ul><p>👉 Like your own mini rsync + S3</p><h3>2. 🔍 Log Integrity System</h3><ul><li>Hash logs continuously</li><li>Store Merkle roots</li><li>Detect tampering in logs</li></ul><p>👉 DevSecOps gold</p><h3>3. 🌐 Distributed File Sync Tool</h3><ul><li>Sync between nodes</li><li>Compare Merkle roots instead of files</li><li>Transfer only differences</li></ul><h3>4. ⛓ Mini Blockchain (for learning or demo)</h3><ul><li>Transactions → Merkle tree</li><li>Blocks → store root</li><li>Verify integrity</li></ul><h3>5. 📦 Docker Image Optimization Concept</h3><p>Think:</p><ul><li>Layers hashed</li><li>Verify only changed layers</li></ul><p>(Yes… Docker kinda uses similar ideas 👀)</p><h3>🎯 Fun facts (because why not)</h3><ul><li>Bitcoin uses Merkle Trees to store thousands of transactions efficiently</li><li>Git is basically a content-addressable Merkle DAG (sounds scary, but now you get it 😄)</li><li>A Merkle proof is logarithmic in size, meaning super scalable</li><li>Named after Ralph Merkle, who invented it in 1979</li></ul><h3>🧠 My mental model (the one I actually use)</h3><blockquote><em>“Merkle Tree is just a system of layered trust built using hashes.”</em></blockquote><p>Or simpler:</p><blockquote><em>📦 Data → fingerprints → fingerprints of fingerprints → one master truth</em></blockquote><h3>🧩 Final thought</h3><p>Once you see it, you’ll notice Merkle Trees everywhere.</p><p>It’s one of those concepts that:</p><ul><li>feels simple</li><li>but powers insanely complex systems</li></ul><p>And honestly…</p><p>It’s one of those “why didn’t I think of this?” ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aeb221526f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Driven Development Life Cycles (AI-DLC): The Future of DevOps and Software Delivery]]></title>
            <link>https://medium.com/@er.samibanerjee/ai-driven-development-life-cycles-ai-dlc-the-future-of-devops-and-software-delivery-08a21cde94f0?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/08a21cde94f0</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[technology-trends]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 10:59:25 GMT</pubDate>
            <atom:updated>2025-12-21T10:59:25.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVUm2Q1wCaTsPK1_zEkmZQ.png" /></figure><p>In today’s fast-moving software landscape, artificial intelligence is no longer a “nice-to-have”, it’s essential. Teams demand faster delivery, higher quality, and continuous innovation. But simply adding AI tools to existing workflows isn’t enough. What’s needed is a fundamental shift in how software is built.</p><p>That shift is the <strong>AI-Driven Development Life Cycle (AI-DLC), </strong>a methodology that puts AI at the core of planning, building, testing, deploying, and operating software. Popularized by AWS and rapidly adopted across industries, AI-DLC is redefining modern software engineering for the AI era.</p><h3>Why Traditional SDLC and DevOps Are No Longer Enough</h3><p>Agile, Scrum, and DevOps brought automation and collaboration, but they still rely heavily on:</p><ul><li>Manual planning and estimation</li><li>Human-only decision making</li><li>Reactive monitoring and troubleshooting</li></ul><p>As AI tools emerged, many teams tried to “bolt them on” using copilots for code suggestions or chatbots for documentation. While helpful, this approach limits AI’s true potential.</p><p><strong>AI-DLC flips the model</strong>: instead of adding AI to existing workflows, it <strong>redesigns workflows around AI </strong>with humans providing context, judgment, and governance.</p><h3>What Is an AI-Driven Development Life Cycle (AI-DLC)?</h3><p>An <strong>AI-Driven Development Life Cycle</strong> is a software engineering methodology where:</p><ul><li>AI acts as a <strong>continuous collaborator</strong>, not just a tool</li><li>Context flows seamlessly across planning, development, and operations</li><li>Humans stay firmly <em>in the loop</em> for validation, ethics, and strategy</li></ul><p>AI doesn’t replace engineers; it <strong>amplifies their impact</strong> by handling repetitive cognitive work while developers focus on design, innovation, and problem-solving.</p><h3>The Three Core Phases of AI-DLC</h3><h4>1️. Inception: From Ideas to Executable Plans</h4><p>In traditional SDLC, converting business ideas into technical tasks is slow and manual.</p><p>In AI-DLC:</p><ul><li>AI translates business goals into <strong>requirements, user stories, and task breakdowns</strong></li><li>Architectural suggestions and risk assessments are generated automatically</li><li>Engineers review, refine, and approve decisions</li></ul><p>✅ Faster planning<br> ✅ Better alignment with business intent<br> ✅ Reduced ambiguity</p><h4>2️. Construction: Human + AI Collaboration</h4><p>This is where AI-DLC truly shines.</p><p>During construction, AI can:</p><ul><li>Propose architecture patterns and domain models</li><li>Generate production-ready code aligned with standards</li><li>Create automated test cases and security checks</li></ul><p>In real time, developers work with AI to guideing, refining, and correcting it.</p><p>The result?</p><ul><li>Shorter development cycles</li><li>Higher consistency</li><li>Fewer defects reaching production</li></ul><h4>3️. Operations: Intelligent, Predictive Systems</h4><p>In the operations phase, AI leverages accumulated context to:</p><ul><li>Automate infrastructure provisioning</li><li>Optimize CI/CD pipelines</li><li>Detect anomalies before failures occur</li></ul><p>Teams take a significant step away from traditional DevOps and toward <strong>predictive and self-healing systems</strong> rather than responding to incidents.</p><h3>Key Benefits of AI-Driven Development</h3><h4>🚀 Speed</h4><p>AI accelerates everything ; planning, coding, testing, and deployment. Shrinking delivery cycles from weeks to <strong>hours or days</strong>.</p><h4>💡 Higher Quality</h4><p>AI consistently applies coding standards, security rules, and testing coverage, reducing human error.</p><h4>🔄 Rapid Market Response</h4><p>Short feedback loops allow teams to adapt quickly to user behavior and market changes.</p><h4>😊 Better Developer Experience</h4><p>By removing repetitive tasks, developers focus on creative, high-value engineering work increasing satisfaction and retention.</p><h3>🏭 Industry Applications of AI-DLC</h3><p>AI-Driven Development is not limited to startups or experimental teams. It’s already transforming multiple industries.</p><h4>🏦 FinTech &amp; Banking</h4><ul><li>Automated compliance checks</li><li>Secure, high-quality releases</li><li>Faster innovation without regulatory risk</li></ul><h4>🏥 Healthcare &amp; MedTech</h4><ul><li>Strong validation and testing for safety-critical systems</li><li>Automated documentation and audit trails</li><li>Reduced risk in life-critical applications</li></ul><h4>🛒 E-Commerce &amp; Retail</h4><ul><li>Rapid feature experimentation</li><li>Personalized user experiences</li><li>Intelligent scalability during peak demand</li></ul><h4>☁ SaaS &amp; Cloud Platforms</h4><ul><li>Faster multi-tenant feature delivery</li><li>AI-optimized CI/CD pipelines</li><li>Predictive monitoring and cost optimization</li></ul><p>Across industries, the impact is clear: <strong>faster innovation, lower risk, and smarter use of human talent</strong>.</p><h3>Tools Powering AI-Driven Development</h3><p>AI-DLC is enabled by a growing ecosystem of tools, including:</p><ul><li>Generative AI coding assistants (e.g., Amazon Q Developer)</li><li>AI-aware CI/CD and DevSecOps pipelines</li><li>Predictive monitoring and observability platforms</li><li>Infrastructure-as-Code enhanced by AI insights</li></ul><p>These tools work best when combined with a <strong>methodology designed for AI-first workflows</strong>.</p><h3>Challenges and Considerations</h3><p>AI-DLC adoption comes with responsibilities:</p><h3>Governance &amp; Trust</h3><p>Teams must ensure explainability, traceability, and compliance, especially in regulated industries.</p><h3>Skill Evolution</h3><p>Engineers need to develop <strong>AI fluency</strong>, not just traditional coding skills.</p><h3>Cultural Shift</h3><p>Success requires embracing AI as a collaborator while keeping humans accountable for decisions and ethics.</p><h3>The Future of Software Engineering</h3><p>AI-Driven Development Life Cycles represent more than automation: they signal a <strong>new operating model for engineering teams</strong>.</p><p>By embedding intelligence across the entire lifecycle, organizations unlock:</p><ul><li>Unprecedented speed</li><li>Higher reliability</li><li>Continuous innovation</li></ul><p><strong>AI-DLC isn’t about replacing developers.<br>It’s about redefining what developers are capable of.</strong></p><p>Teams that adopt this mindset today will shape the future of software tomorrow.</p><blockquote>Build faster. Test smarter. Govern responsibly. When AI amplifies human judgment, innovation isn’t a goal… it’s the new standard.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08a21cde94f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Unit Testing Tutorial: From Zero to Expert]]></title>
            <link>https://medium.com/@er.samibanerjee/terraform-unit-testing-tutorial-from-zero-to-expert-833d4ae99586?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/833d4ae99586</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 14:56:37 GMT</pubDate>
            <atom:updated>2025-11-13T14:56:37.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>📚 Table of Contents</h3><ol><li>What is Terraform Unit Testing?</li><li>Why Unit Testing Matters in Infrastructure as Code</li><li>Types of Terraform Testing</li><li>Project Overview</li><li>Understanding the Testing Architecture</li><li>Step-by-Step: Writing Your First Test</li><li>Advanced Testing Patterns</li><li>Test Execution and Debugging</li><li>Best Practices and Common Pitfalls</li><li>Hands-On Examples</li></ol><h3>Installation Quick Start</h3><pre># Terraform<br># Download from: https://developer.hashicorp.com/terraform/downloads<br>terraform version<br># TFLint (Windows)<br>choco install tflint<br># or download from: https://github.com/terraform-linters/tflint/releases<br># Checkov (Python)<br>pip install checkov<br># or<br>pipx install checkov<br># AWS CLI (optional)<br># Download from: https://aws.amazon.com/cli/<br>aws --version</pre><h3>Why These Tools?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*bRAdp6nUJ6umDG-iZgSuvQ.png" /></figure><h3>🎯 What is Terraform Unit Testing?</h3><p><strong>Terraform Unit Testing</strong> is the practice of automatically verifying that your Infrastructure as Code (IaC) behaves correctly <strong>before</strong> deploying to production. Just like software developers test their code, infrastructure engineers test their Terraform configurations.</p><h3>🤔 Think of it like this:</h3><ul><li><strong>Traditional Software</strong>: Test functions, classes, and modules</li><li><strong>Terraform</strong>: Test resources, modules, and configurations</li><li><strong>Goal</strong>: Catch errors early, ensure security, validate logic</li></ul><h3>📋 What We Test:</h3><ul><li>✅ <strong>Configuration Syntax</strong>: Does the code compile?</li><li>✅ <strong>Resource Properties</strong>: Are security groups configured correctly?</li><li>✅ <strong>Security Rules</strong>: Is SSH restricted properly?</li><li>✅ <strong>Dependencies</strong>: Do modules work together?</li><li>✅ <strong>Outputs</strong>: Are the right values exposed?</li></ul><h3>🚀 Why Unit Testing Matters in Infrastructure as Code</h3><h3>💰 Cost Savings</h3><pre>❌ Without Testing: Deploy → Find Bug → Fix → Redeploy → $$$<br>✅ With Testing:    Test → Find Bug → Fix → Test → Deploy → $</pre><h3>🛡️ Security Assurance</h3><pre># This test prevents accidentally exposing SSH to the internet<br>assert {<br>  condition = !contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;) || rule.from_port != 22<br>  error_message = &quot;SSH should never be open to the internet!&quot;<br>}</pre><h3>⚡ Faster Development</h3><ul><li><strong>Immediate Feedback</strong>: Know if changes break things in seconds</li><li><strong>Confidence</strong>: Deploy knowing your infrastructure is tested</li><li><strong>Documentation</strong>: Tests serve as living documentation</li></ul><h3>🔄 Continuous Integration</h3><ul><li><strong>Automated Validation</strong>: Every code change is automatically tested</li><li><strong>Team Collaboration</strong>: Prevent team members from breaking each other’s work</li><li><strong>Compliance</strong>: Ensure security and compliance rules are always followed</li></ul><h3>🏗️ Types of Terraform Testing</h3><h3>1. Static Analysis ⚡ (Fastest, Cheapest)</h3><pre>terraform fmt -check   # Code formatting<br>terraform validate     # Syntax validation<br>tflint                 # Linting rules<br>checkov -d .           # Security scanning<br>terraform test         # Run unit tests</pre><h3>Extra commands</h3><pre>checkov -d . --config-file .checkov.yml # Run security scanning<br>checkov -d . --config-file .checkov.yml --framework terraform --skip-check CKV_AWS_23,CKV_AWS_24,CKV_AWS_25,CKV_AWS_26,CKV_AWS_27 # Run security scanning with skip checks<br>checkov -d . --config-file .checkov.yml --framework terraform --skip-check CKV_AWS_23,CKV_AWS_24,CKV_AWS_25,CKV_AWS_26,CKV_AWS_27 --skip-path .terraform --output cli # Run security scanning with skip checks and cli output</pre><pre>terraform test -filter=tests/unit_tests.tftest.hcl # Run unit tests<br>terraform test -filter=tests/unit_tests.tftest.hcl -verbose # Run unit tests</pre><p><strong>What it does</strong>: Checks code without running it <strong>Time</strong>: Seconds <strong>Cost</strong>: Free</p><h3>2. Unit Tests 🧪 (Fast, Plan-only)</h3><pre>run &quot;test_security_rules&quot; {<br>  command = plan  # Only plans, doesn&#39;t create resources<br>  <br>  assert {<br>    condition = contains(security_group_ports, 443)<br>    error_message = &quot;HTTPS port must be allowed&quot;<br>  }<br>}</pre><p><strong>What it does</strong>: Tests logic without creating real resources <strong>Time</strong>: 10–30 seconds <strong>Cost</strong>: Free</p><h3>3. Integration Tests 🔗 (Slower, Creates Real Resources)</h3><pre>run &quot;test_real_deployment&quot; {<br>  command = apply  # Actually creates AWS resources<br>  <br>  assert {<br>    condition = startswith(output.security_group_id, &quot;sg-&quot;)<br>    error_message = &quot;Should create a real security group&quot;<br>  }<br>}</pre><p><strong>What it does</strong>: Tests with real cloud resources <strong>Time</strong>: 2–5 minutes <strong>Cost</strong>: Small AWS charges</p><h3>📁 Project Overview</h3><p>This project demonstrates <strong>all three testing levels</strong> with AWS Security Groups:</p><pre>📦 d:/DevOps/TF/unit-testing/<br>├── 🏗️ Infrastructure Code<br>│   ├── main.tf              # Main configuration<br>│   ├── variables.tf         # Input parameters<br>│   ├── outputs.tf           # Return values<br>│   └── modules/security-group/  # Reusable module<br>│       ├── main.tf<br>│       ├── variables.tf<br>│       └── outputs.tf<br>├── 🧪 Tests<br>│   ├── tests/unit_tests.tftest.hcl           # Plan-only tests<br>│   ├── tests/security_validation.tftest.hcl  # Security tests<br>│   └── tests/integration_tests.tftest.hcl    # Apply tests<br>├── 🔧 Configuration<br>│   ├── .tflint.hcl          # Linting rules<br>│   ├── .checkov.yml         # Security scanning<br>│   └── .github/workflows/   # CI/CD pipeline<br>└── 📚 Documentation<br>    ├── README.md            # This tutorial<br>    └── TESTING_GUIDE.md     # Quick reference</pre><h3>🏛️ What We’re Building</h3><p><strong>Three Security Groups</strong> with proper security:</p><ol><li><strong>Web Security Group</strong>: HTTP/HTTPS from internet, SSH from admin only</li><li><strong>Database Security Group</strong>: MySQL/PostgreSQL from web servers only</li><li><strong>Load Balancer Security Group</strong>: HTTP/HTTPS from internet</li></ol><h3>🏗️ Understanding the Testing Architecture</h3><h3>📋 Test File Structure</h3><p>Every .tftest.hcl file follows this pattern:</p><pre># 1. VARIABLES BLOCK - Set test inputs<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;my-test&quot;<br>  admin_cidr   = &quot;10.0.0.0/8&quot;<br>}</pre><pre># 2. RUN BLOCK - Define a test scenario<br>run &quot;test_name&quot; {<br>  command = plan  # or &quot;apply&quot;<br>  <br>  # 3. ASSERT BLOCKS - Define what should be true<br>  assert {<br>    condition     = some_expression == expected_value<br>    error_message = &quot;Helpful error message if test fails&quot;<br>  }<br>}</pre><h3>🔍 Key Components Explained</h3><h4>Variables Block</h4><pre>variables {<br>  aws_region   = &quot;us-east-1&quot;    # Override default variables<br>  project_name = &quot;test-project&quot;  # Use test-specific values<br>}</pre><p><strong>Purpose</strong>: Set specific values for testing (different from production)</p><h4>Run Block</h4><pre>run &quot;descriptive_test_name&quot; {<br>  command = plan  # &quot;plan&quot; or &quot;apply&quot;<br>  # ... assertions go here<br>}</pre><p><strong>Purpose</strong>: Define a test scenario. Each run block is one test.</p><h4>Assert Block</h4><pre>assert {<br>  condition     = module.web_sg.vpc_id == data.aws_vpc.default.id<br>  error_message = &quot;Web security group should be in the default VPC&quot;<br>}</pre><p><strong>Purpose</strong>: Define what should be true. If condition is false, test fails.</p><h3>✍️ Step-by-Step: Writing Your First Test</h3><p>Let’s write a simple test from scratch to understand the process.</p><h3>Step 1: Create a Basic Test File</h3><pre># tests/my_first_test.tftest.hcl</pre><pre># Set test variables<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;first-test&quot;<br>}</pre><pre># Test that variables are set correctly<br>run &quot;test_variables&quot; {<br>  command = plan<br>  <br>  assert {<br>    condition     = var.aws_region == &quot;us-east-1&quot;<br>    error_message = &quot;AWS region should be us-east-1&quot;<br>  }<br>  <br>  assert {<br>    condition     = var.project_name == &quot;first-test&quot;<br>    error_message = &quot;Project name should be first-test&quot;<br>  }<br>}</pre><h3>Step 2: Run the Test</h3><pre>terraform test -filter=tests/my_first_test.tftest.hcl -verbose</pre><h3>Step 3: Understand the Output</h3><pre>✅ Success! 1 passed, 0 failed.<br>  run &quot;test_variables&quot;... pass</pre><p><strong>Congratulations!</strong> You just wrote and ran your first Terraform test! 🎉</p><h3>🧪 Advanced Testing Patterns</h3><h3>Pattern 1: Testing Resource Properties</h3><pre>run &quot;test_security_group_ports&quot; {<br>  command = plan<br>  <br>  # Test that web security group allows HTTP<br>  assert {<br>    condition = contains([<br>      for rule in module.web_security_group.security_group_ingress : rule.from_port<br>    ], 80)<br>    error_message = &quot;Web security group must allow HTTP (port 80)&quot;<br>  }<br>  <br>  # Test that web security group allows HTTPS<br>  assert {<br>    condition = contains([<br>      for rule in module.web_security_group.security_group_ingress : rule.from_port<br>    ], 443)<br>    error_message = &quot;Web security group must allow HTTPS (port 443)&quot;<br>  }<br>}</pre><p><strong>What this does</strong>:</p><ul><li>Loops through all ingress rules</li><li>Extracts the from_port of each rule</li><li>Checks if port 80 and 443 are in the list</li></ul><h3>Pattern 2: Security Validation</h3><pre>run &quot;test_ssh_security&quot; {<br>  command = plan<br>  <br>  # Ensure SSH is NOT open to the entire internet<br>  assert {<br>    condition = alltrue([<br>      for rule in module.web_security_group.security_group_ingress :<br>      !(rule.from_port == 22 &amp;&amp; contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;))<br>    ])<br>    error_message = &quot;SSH (port 22) should NEVER be open to 0.0.0.0/0!&quot;<br>  }<br>}</pre><p><strong>What this does</strong>:</p><ul><li>Checks every ingress rule</li><li>Ensures no rule allows SSH (port 22) from anywhere (0.0.0.0/0)</li><li>Fails the test if this dangerous configuration is found</li></ul><h3>Pattern 3: Cross-Resource Validation</h3><pre>run &quot;test_database_isolation&quot; {<br>  command = plan<br>  <br>  # Database should only accept connections from web security group<br>  assert {<br>    condition = alltrue([<br>      for rule in module.db_security_group.security_group_ingress :<br>      length(rule.security_groups) &gt; 0  # Uses security group references<br>    ])<br>    error_message = &quot;Database should use security group references, not CIDR blocks&quot;<br>  }<br>}</pre><p><strong>What this does</strong>:</p><ul><li>Validates that database security group uses security group references</li><li>This is more secure than allowing CIDR blocks</li></ul><h3>Pattern 4: Output Validation</h3><pre>run &quot;test_outputs&quot; {<br>  command = apply  # Need apply to get real IDs<br>  <br>  assert {<br>    condition = startswith(output.web_security_group_id, &quot;sg-&quot;)<br>    error_message = &quot;Security group ID should start with &#39;sg-&#39;&quot;<br>  }<br>  <br>  assert {<br>    condition = output.web_security_group_id != output.db_security_group_id<br>    error_message = &quot;Web and database security groups should be different&quot;<br>  }<br>}</pre><p><strong>What this does</strong>:</p><ul><li>Tests actual AWS resource IDs (requires apply)</li><li>Validates output format and uniqueness</li></ul><h3>🎮 Test Execution and Debugging</h3><h3>Running Tests</h3><h4>Option 1: Run All Tests</h4><pre>terraform test</pre><p><strong>Result</strong>: Runs ALL test files (including integration tests that create resources)</p><h4>Option 2: Run Specific Test File</h4><pre>terraform test -filter=tests/unit_tests.tftest.hcl</pre><p><strong>Result</strong>: Runs only unit tests (plan-only, no resources created)</p><h4>Option 3: Run with Verbose Output</h4><pre>terraform test -filter=tests/unit_tests.tftest.hcl -verbose</pre><p><strong>Result</strong>: Shows detailed plan output for debugging</p><h3>Understanding Test Results</h3><h4>✅ Success Output</h4><pre>Success! 6 passed, 0 failed.<br>  run &quot;test_security_group_creation&quot;... pass<br>  run &quot;test_web_security_group_rules&quot;... pass<br>  run &quot;test_db_security_group_rules&quot;... pass</pre><h4>❌ Failure Output</h4><pre>Failure! 2 passed, 1 failed, 3 skipped.<br>  run &quot;test_ssh_security&quot;... fail<br>    Error: SSH should NEVER be open to 0.0.0.0/0!</pre><h4>🔍 Debugging Failed Tests</h4><ol><li><strong>Read the Error Message</strong>: It tells you exactly what went wrong</li><li><strong>Check the Condition</strong>: Look at the assert condition that failed</li><li><strong>Use Verbose Mode</strong>: See the actual Terraform plan</li><li><strong>Verify Your Logic</strong>: Make sure your test logic is correct</li></ol><h3>Common Test Failures and Solutions</h3><h4>Problem: “Unknown condition value”</h4><pre>Error: Unknown condition value<br>  on tests/unit_tests.tftest.hcl line 20</pre><p><strong>Cause</strong>: Trying to access computed values during plan <strong>Solution</strong>: Use command = apply or test different attributes</p><h4>Problem: “0 passed, 0 failed”</h4><pre>Success! 0 passed, 0 failed.</pre><p><strong>Cause</strong>: Tests not discovered or syntax errors <strong>Solution</strong>: Check file naming (must end in .tftest.hcl) and syntax</p><h4>Problem: “No valid credential sources found”</h4><pre>Error: No valid credential sources found</pre><p><strong>Cause</strong>: AWS credentials not configured <strong>Solution</strong>: Configure AWS profile or environment variables</p><h3>🎯 Best Practices and Common Pitfalls</h3><h3>✅ Best Practices</h3><h4>1. Start with Plan Tests</h4><pre># Good: Fast, cheap, catches most issues<br>run &quot;test_config&quot; {<br>  command = plan<br>  # ... assertions<br>}</pre><h4>2. Use Descriptive Test Names</h4><pre># Good: Clear what is being tested<br>run &quot;test_ssh_restricted_to_admin_network&quot; { }</pre><pre># Bad: Unclear purpose<br>run &quot;test1&quot; { }</pre><h4>3. Write Clear Error Messages</h4><pre># Good: Explains what went wrong and why it matters<br>assert {<br>  condition     = !contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;)<br>  error_message = &quot;SSH access from 0.0.0.0/0 is a security risk. Restrict to admin networks only.&quot;<br>}</pre><pre># Bad: Unclear what to do<br>assert {<br>  condition     = some_condition<br>  error_message = &quot;Test failed&quot;<br>}</pre><h4>4. Test Security First</h4><pre># Always test security-critical configurations<br>run &quot;test_no_public_database_access&quot; {<br>  command = plan<br>  <br>  assert {<br>    condition = alltrue([<br>      for rule in module.db_security_group.security_group_ingress :<br>      !contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;)<br>    ])<br>    error_message = &quot;Database should never be accessible from the internet&quot;<br>  }<br>}</pre><h4>5. Use Variables for Test Data</h4><pre># Good: Configurable test data<br>variables {<br>  test_admin_cidr = &quot;192.168.1.0/24&quot;<br>}</pre><pre># Bad: Hardcoded values in assertions<br>assert {<br>  condition = rule.cidr_blocks == [&quot;192.168.1.0/24&quot;]<br>}</pre><h3>❌ Common Pitfalls</h3><h4>1. Testing Computed Values in Plan</h4><pre># ❌ This will fail - IDs are unknown during plan<br>run &quot;bad_test&quot; {<br>  command = plan<br>  assert {<br>    condition = output.security_group_id != null  # Unknown during plan!<br>  }<br>}</pre><pre># ✅ This works - test known values<br>run &quot;good_test&quot; {<br>  command = plan<br>  assert {<br>    condition = module.web_sg.security_group_vpc_id == data.aws_vpc.default.id<br>  }<br>}</pre><h4>2. Forgetting to Handle Null Values</h4><pre># ❌ This can fail if cidr_blocks is null<br>assert {<br>  condition = contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;)<br>}</pre><pre># ✅ This handles null values properly<br>assert {<br>  condition = rule.cidr_blocks != null &amp;&amp; contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;)<br>}</pre><h4>3. Not Cleaning Up Integration Tests</h4><pre># ❌ Creates resources but doesn&#39;t clean up<br>run &quot;integration_test&quot; {<br>  command = apply<br>  # ... tests but no cleanup<br>}</pre><pre># ✅ Terraform automatically cleans up after each test file<br># Just make sure you don&#39;t have persistent state</pre><h3>🛠️ Hands-On Examples</h3><p>Let’s walk through creating tests for our security group project.</p><h3>Example 1: Basic Security Group Test</h3><p><strong>Goal</strong>: Ensure web security group is created in the correct VPC</p><pre># tests/basic_test.tftest.hcl<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;basic-test&quot;<br>}</pre><pre>run &quot;test_web_security_group_vpc&quot; {<br>  command = plan<br>  <br>  assert {<br>    condition     = module.web_security_group.security_group_vpc_id == data.aws_vpc.default.id<br>    error_message = &quot;Web security group should be created in the default VPC&quot;<br>  }<br>}</pre><p><strong>Run it</strong>:</p><pre>terraform test -filter=tests/basic_test.tftest.hcl -verbose</pre><h3>Example 2: Port Configuration Test</h3><p><strong>Goal</strong>: Verify that web security group has the correct ports</p><pre># tests/port_test.tftest.hcl<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;port-test&quot;<br>}</pre><pre>run &quot;test_web_ports&quot; {<br>  command = plan<br>  <br>  # Test HTTP port<br>  assert {<br>    condition = contains([<br>      for rule in module.web_security_group.security_group_ingress : rule.from_port<br>    ], 80)<br>    error_message = &quot;Web security group must allow HTTP (port 80)&quot;<br>  }<br>  <br>  # Test HTTPS port<br>  assert {<br>    condition = contains([<br>      for rule in module.web_security_group.security_group_ingress : rule.from_port<br>    ], 443)<br>    error_message = &quot;Web security group must allow HTTPS (port 443)&quot;<br>  }<br>  <br>  # Test SSH port<br>  assert {<br>    condition = contains([<br>      for rule in module.web_security_group.security_group_ingress : rule.from_port<br>    ], 22)<br>    error_message = &quot;Web security group must allow SSH (port 22)&quot;<br>  }<br>}</pre><h3>Example 3: Security Validation Test</h3><p><strong>Goal</strong>: Ensure SSH is not open to the internet</p><pre># tests/security_test.tftest.hcl<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;security-test&quot;<br>  admin_cidr   = &quot;192.168.1.0/24&quot;  # Restrictive admin access<br>}</pre><pre>run &quot;test_ssh_security&quot; {<br>  command = plan<br>  <br>  # Critical security test: SSH should not be open to everyone<br>  assert {<br>    condition = alltrue([<br>      for rule in module.web_security_group.security_group_ingress :<br>      !(rule.from_port == 22 &amp;&amp; contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;))<br>    ])<br>    error_message = &quot;SECURITY VIOLATION: SSH (port 22) must not be open to 0.0.0.0/0&quot;<br>  }<br>  <br>  # Verify SSH is restricted to admin network<br>  assert {<br>    condition = anytrue([<br>      for rule in module.web_security_group.security_group_ingress :<br>      rule.from_port == 22 &amp;&amp; contains(rule.cidr_blocks, var.admin_cidr)<br>    ])<br>    error_message = &quot;SSH should be accessible from admin network (${var.admin_cidr})&quot;<br>  }<br>}</pre><h3>Example 4: Database Isolation Test</h3><p><strong>Goal</strong>: Ensure database is only accessible from web servers</p><pre># tests/database_test.tftest.hcl<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;db-test&quot;<br>}</pre><pre>run &quot;test_database_isolation&quot; {<br>  command = plan<br>  <br>  # Database should not be accessible from the internet<br>  assert {<br>    condition = alltrue([<br>      for rule in module.db_security_group.security_group_ingress :<br>      !((rule.from_port == 3306 || rule.from_port == 5432) &amp;&amp; <br>        rule.cidr_blocks != null &amp;&amp; contains(rule.cidr_blocks, &quot;0.0.0.0/0&quot;))<br>    ])<br>    error_message = &quot;Database ports should NEVER be accessible from the internet&quot;<br>  }<br>  <br>  # Database should have MySQL port<br>  assert {<br>    condition = contains([<br>      for rule in module.db_security_group.security_group_ingress : rule.from_port<br>    ], 3306)<br>    error_message = &quot;Database security group should allow MySQL (port 3306)&quot;<br>  }<br>  <br>  # Database should have PostgreSQL port<br>  assert {<br>    condition = contains([<br>      for rule in module.db_security_group.security_group_ingress : rule.from_port<br>    ], 5432)<br>    error_message = &quot;Database security group should allow PostgreSQL (port 5432)&quot;<br>  }<br>}</pre><h3>Example 5: Integration Test (Creates Real Resources)</h3><p><strong>Goal</strong>: Test actual resource creation and cleanup</p><pre># tests/integration_test.tftest.hcl<br>variables {<br>  aws_region   = &quot;us-east-1&quot;<br>  project_name = &quot;integration-test&quot;<br>}</pre><pre>run &quot;test_real_deployment&quot; {<br>  command = apply  # This creates real AWS resources!<br>  <br>  # Test that real security group IDs are generated<br>  assert {<br>    condition     = startswith(output.web_security_group_id, &quot;sg-&quot;)<br>    error_message = &quot;Web security group ID should start with &#39;sg-&#39;&quot;<br>  }<br>  <br>  # Test that ARNs are properly formatted<br>  assert {<br>    condition = can(regex(&quot;^arn:aws:ec2:[a-z0-9-]+:[0-9]+:security-group/sg-[a-z0-9]+$&quot;, <br>                    output.web_security_group_arn))<br>    error_message = &quot;Web security group ARN format is invalid&quot;<br>  }<br>  <br>  # Test that all security groups are unique<br>  assert {<br>    condition     = output.web_security_group_id != output.db_security_group_id<br>    error_message = &quot;Web and database security groups should have different IDs&quot;<br>  }<br>}</pre><p><strong>⚠️ Warning</strong>: This test creates real AWS resources and may incur small charges!</p><h3>🚀 Quick Start Guide</h3><h3>Prerequisites Setup</h3><ol><li><strong>Install Terraform</strong> (&gt;= 1.0)</li></ol><pre># Download from: https://developer.hashicorp.com/terraform/downloads terraform version</pre><p><strong>2. Configure AWS Credentials</strong></p><pre># Option 1: AWS CLI <br>aws configure --profile root  <br># Option 2: Environment Variables <br>$env:AWS_ACCESS_KEY_ID = &quot;your-key&quot; <br>$env:AWS_SECRET_ACCESS_KEY = &quot;your-secret&quot; <br>$env:AWS_DEFAULT_REGION = &quot;us-east-1&quot;</pre><p><strong>3. Initialize Terraform</strong></p><pre>terraform init</pre><h3>Running Tests</h3><h4>Safe Tests (No AWS Resources Created)</h4><pre># Run unit tests only<br>terraform test -filter=tests/unit_tests.tftest.hcl</pre><pre># Run security validation tests<br>terraform test -filter=tests/security_validation.tftest.hcl</pre><pre># Run with detailed output<br>terraform test -filter=tests/unit_tests.tftest.hcl -verbose</pre><h4>Full Tests (Creates Real AWS Resources)</h4><pre># ⚠️ WARNING: This creates real AWS resources and may cost money<br>terraform test</pre><pre># Clean up afterward<br>terraform destroy -auto-approve</pre><h3>Expected Results</h3><pre>✅ Success! 14 passed, 0 failed.<br>  tests/unit_tests.tftest.hcl... pass<br>    run &quot;test_security_group_creation&quot;... pass<br>    run &quot;test_web_security_group_rules&quot;... pass<br>    run &quot;test_db_security_group_rules&quot;... pass<br>    run &quot;test_alb_security_group_rules&quot;... pass<br>    run &quot;test_module_outputs&quot;... pass<br>    run &quot;test_security_group_descriptions&quot;... pass<br>  tests/security_validation.tftest.hcl... pass<br>    run &quot;test_ssh_access_restrictions&quot;... pass<br>    run &quot;test_database_security_isolation&quot;... pass<br>    run &quot;test_database_ports&quot;... pass<br>    run &quot;test_egress_rules_validation&quot;... pass<br>    run &quot;test_security_group_descriptions&quot;... pass<br>    run &quot;test_vpc_assignment&quot;... pass<br>    run &quot;test_specific_port_ranges&quot;... pass<br>    run &quot;test_no_duplicate_rules&quot;... pass</pre><h3>🎓 What You’ve Learned</h3><p>By completing this tutorial, you now understand:</p><h3>🧠 Concepts</h3><ul><li>✅ What Terraform unit testing is and why it matters</li><li>✅ Different types of testing (static, unit, integration)</li><li>✅ The testing pyramid for Infrastructure as Code</li><li>✅ When to use plan vs apply in tests</li></ul><h3>🛠️ Technical Skills</h3><ul><li>✅ How to write .tftest.hcl files</li><li>✅ Using variables, run, and assert blocks</li><li>✅ Testing resource properties and security rules</li><li>✅ Debugging failed tests and common error patterns</li></ul><h3>🏗️ Best Practices</h3><ul><li>✅ Security-first testing approach</li><li>✅ Descriptive test names and error messages</li><li>✅ Proper test organization and structure</li><li>✅ Cost-effective testing strategies</li></ul><h3>🚀 Real-World Application</h3><ul><li>✅ Complete working example with AWS Security Groups</li><li>✅ Production-ready test suite with 20+ test cases</li><li>✅ CI/CD integration patterns</li><li>✅ Static analysis and security scanning</li></ul><h3>📚 Additional Resources</h3><h3>📖 Official Documentation</h3><ul><li><a href="https://developer.hashicorp.com/terraform/language/tests">Terraform Testing Documentation</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">AWS Provider Documentation</a></li></ul><h3>🎯 Best Practice Guides</h3><ul><li><a href="https://cloud.google.com/docs/terraform/best-practices/testing">Google Cloud: Terraform Testing Best Practices</a></li><li><a href="https://spacelift.io/blog/terraform-test">Spacelift: How to Test Terraform Code</a></li></ul><h3>🛠️ Tools and Extensions</h3><ul><li><a href="https://github.com/terraform-linters/tflint">TFLint</a> — Terraform linter</li><li><a href="https://www.checkov.io/">Checkov</a> — Security and compliance scanner</li><li><a href="https://terratest.gruntwork.io/">Terratest</a> — Go-based testing framework</li></ul><h3>🎥 Video Tutorials</h3><ul><li><a href="https://www.youtube.com/watch?v=N73chhccmo8&amp;t=39s">Validate your code with the Terraform test framework</a></li><li><a href="https://www.youtube.com/watch?v=o5mtHtfR45Q&amp;t=305s">Terraform Test — Terraform v1.6.0 — Native Test Framework for IaC, Explained with Demo</a></li><li><a href="https://www.youtube.com/watch?v=4U2S6sXcuac&amp;t=425s">Using the Terraform Test Framework</a></li></ul><h3>🤝 Contributing and Next Steps</h3><h3>🔄 Extend This Project</h3><ol><li><strong>Add More Security Groups</strong>: Create additional security groups for different tiers</li><li><strong>Test Different Scenarios</strong>: Add tests for edge cases and error conditions</li><li><strong>Multi-Region Testing</strong>: Test deployments across different AWS regions</li><li><strong>Custom Modules</strong>: Create and test your own reusable modules</li></ol><h3>🚀 Advanced Topics to Explore</h3><ol><li><strong>Terratest with Go</strong>: Write integration tests in Go for complex scenarios</li><li><strong>Policy as Code</strong>: Use Open Policy Agent (OPA) for advanced compliance testing (<a href="https://medium.com/devsecops-ai/guardrails-for-your-cloud-a-simple-guide-to-opa-and-terraform-aada0d589dc5">You can check it</a> !!)</li><li><strong>Multi-Cloud Testing</strong>: Extend tests to Azure, GCP, or other providers</li><li><strong>Performance Testing</strong>: Test infrastructure performance and scalability</li></ol><h3>📝 Share Your Experience</h3><ul><li>Create your own testing examples</li><li>Share lessons learned with the community</li><li>Contribute improvements to this tutorial</li></ul><p><strong>🎉 Congratulations!</strong> You’re now equipped with the knowledge and tools to implement comprehensive Terraform unit testing in your own projects. Start small, test often, and build confidence in your Infrastructure as Code!</p><h3>📞 Need Help?</h3><p>If you encounter issues or have questions:</p><ol><li><strong>Check the Error Message</strong>: Most Terraform errors are descriptive</li><li><strong>Review the Test Logic</strong>: Ensure your assertions make sense</li><li><strong>Use Verbose Mode</strong>: terraform test -verbose shows detailed output</li><li><strong>Consult Documentation</strong>: Official Terraform docs are comprehensive</li><li><strong>Community Support</strong>: Stack Overflow, HashiCorp forums, and GitHub discussions</li><li><strong>And for my beautiful, pretty words </strong>— you know where to reach out 😎</li></ol><h3>📚 Reference</h3><ul><li><a href="https://developer.hashicorp.com/terraform/language/tests">Terraform Testing Documentation</a></li><li><a href="https://github.com/terraform-linters/tflint">TFLint</a></li><li><a href="https://github.com/terraform-linters/tflint-ruleset-terraform/tree/main">TFLint Ruleset</a></li><li><a href="https://github.com/terraform-linters/tflint-ruleset-aws">TFLint Ruleset AWS</a></li><li><a href="https://www.checkov.io/">Checkov</a></li><li><a href="https://terratest.gruntwork.io/">Terratest</a> # (optional) one of the best tools for testing infrastructure as code</li><li><a href="https://www.terraform.io/">Terraform</a></li></ul><blockquote>If you guys need the repo, drop a comment — let’s see how many of you actually made it to the end! 👀</blockquote><h3>📢📢📢📢</h3><p><strong>Happy Testing!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833d4ae99586" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own Kubernetes Cluster Without Losing Your Mind ]]></title>
            <link>https://medium.com/@er.samibanerjee/building-your-own-kubernetes-cluster-without-losing-your-mind-51915d0540e8?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/51915d0540e8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Sun, 11 May 2025 11:13:50 GMT</pubDate>
            <atom:updated>2025-05-11T11:13:50.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Because who doesn’t want their own mini data center?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f42kXbgQ7W_rjf6ImJim0w.png" /></figure><p>Ever wondered what it feels like to have your own <strong>Kubernetes cluster</strong>? You know, that thing that makes tech people’s eyes light up in job interviews? Well, grab your coffee ☕ (you’ll need it), and let me show you how to build one right on your laptop — no cloud bills, no complicated setups, just pure local development goodness.</p><h3>What We’re Building (In Human Words, I Promise)</h3><p>Imagine having two virtual computers (we call them VMs) talking to each other:</p><ul><li>One is the boss (Master Node) 👑 — giving orders and keeping everything in check</li><li>One is the worker (Worker Node) 🛠️ — doing the actual heavy lifting</li></ul><p>Together, they form a mini-datacenter that can run all sorts of cool applications. It’s like having a tiny cloud in your laptop!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXxQzAjU530CsAXEhA-3pg.png" /></figure><h3>What You’ll Need 🛠️</h3><p>Let’s gather our ingredients for this tech recipe:</p><ul><li>A computer with some free RAM (4GB should do)</li><li>Some free disk space (20GB to be safe)</li><li><a href="https://www.virtualbox.org/wiki/Downloads">VirtualBox</a> (the thing that creates virtual computers)</li><li><a href="https://www.vagrantup.com/downloads">Vagrant</a> (the magical tool that sets everything up)</li><li>A desire to feel like a tech wizard 🧙‍♂️</li><li>Coffee (optional but highly recommended) ☕</li></ul><h3>The Easy Part: Setting Up 🚀</h3><p>Remember those times when setting up development environments felt like solving a Rubik’s cube blindfolded? Not today! We’re using Vagrant, which is like having a personal assistant who sets up everything for you.</p><ol><li>Clone this repo (fancy way of saying “download”):</li></ol><pre>git clone https://github.com/TryToLearnProgramming/vagrant<br>cd vagrant</pre><p>2. Start the magic:</p><pre>vagrant up</pre><p>Now go grab another coffee ☕ — your computer will be busy for a few minutes creating your personal Kubernetes paradise.</p><h3>What’s Actually Happening? 🤔</h3><p>While you’re sipping that coffee, here’s what’s going on behind the scenes (in human terms):</p><ol><li><strong>Creating Virtual Machines:</strong></li></ol><ul><li>Think of it as creating two mini-computers inside your computer</li><li>Each gets its own memory, CPU, and virtual hard drive</li><li>It’s like having two tiny servers on your laptop!</li></ul><p><strong>2. Installing the Software:</strong></p><ul><li>Ubuntu (because we’re fancy) 🎩</li><li>Docker (for running containers)</li><li>Kubernetes tools (the secret sauce)</li><li>Network stuff (so they can talk to each other)</li></ul><p>It’s like ordering a pizza 🍕 — you don’t need to know how to make the dough, you just need to know what toppings you want!</p><h3>Making It Work 🛠️</h3><p>Once everything is installed, you’ll need to do a few things to get your cluster running:</p><ol><li>Connect to your boss node (master):</li></ol><pre>vagrant ssh master</pre><p>2. Initialize the cluster (wake up the boss):</p><pre>sudo kubeadm init --pod-network-cidr=10.201.0.0/16 --apiserver-advertise-address=192.168.63.1<br># This command sets up the master node and tells it to use a specific network range for the pods</pre><p>Copy the kubeadm join command from the output.</p><p>3. Install the network plugin (because even virtual computers need internet):</p><pre>kubectl apply -f https://github.com/weaveworks/weave/releases/download/v2.8.1/weave-daemonset-k8s.yaml</pre><p>4. Join the worker node (make it part of the family):</p><pre>vagrant ssh worker</pre><p>5. Run the join command (this is where the magic happens):</p><pre>sudo kubeadm join 192.168.63.1:6443 --token &lt;token&gt; --discovery-token-ca-cert-hash sha256:&lt;hash&gt;</pre><p>(Replace &lt;token&gt; and &lt;hash&gt; with the actual values from the master node&#39;s output)</p><h3>When Things Go Wrong (Because They Will) 🔧</h3><p>Let’s be honest — technology isn’t perfect. Here’s your “things went wrong” cheat sheet:</p><ol><li><strong>The “Turn It Off and On Again” Approach:</strong></li></ol><pre>sudo kubeadm reset <br>sudo systemctl restart kubelet <br>sudo systemctl restart containerd</pre><p><strong>2. The “Clean Slate” Method:</strong></p><pre>vagrant destroy <br>vagrant up</pre><p>Yes, sometimes starting over is the best solution!</p><h3>Why Would You Want This? 🤷</h3><p>Great question! Having your own Kubernetes cluster is useful for:</p><ul><li>Learning how container orchestration works (sounds fancy at parties)</li><li>Testing your applications before deploying to the cloud</li><li>Feeling like a tech superhero 🦸‍♂️</li><li>Impressing your tech friends (or confusing your non-tech friends)</li></ul><h3>Cool Things You Can Do Now 🎮</h3><p>Once your cluster is up and running, you can:</p><ul><li>Deploy web applications</li><li>Set up monitoring</li><li>Practice DevOps workflows</li><li>Finally understand what all those Kubernetes memes are about</li><li>Play around without worrying about cloud costs 💰</li></ul><h3>Pro Tips for Success 🎯</h3><ol><li><strong>Be Patient:</strong></li></ol><ul><li>Rome wasn’t built in a day, and neither is a perfect Kubernetes cluster</li><li>Some commands take time to complete</li><li>Perfect time to refresh that coffee ☕</li></ul><p><strong>2. Keep Notes:</strong></p><ul><li>Commands you used</li><li>Errors you encountered</li><li>Solutions you found</li><li>Future you will thank present you!</li></ul><h3>Conclusion 🎉</h3><p>Congratulations! You now have your own Kubernetes cluster running on your laptop. It’s like having a data center in your pocket (well, technically on your hard drive, but you get the point).</p><p>Remember, everyone starts somewhere. Today it’s a local Kubernetes cluster, tomorrow… well, probably debugging that same cluster — but that’s part of the fun! 😉</p><blockquote>Along the way, you might run into unexpected issues. That’s normal. Actually, those bumps in the road are where your real growth happens. Each problem you tackle sharpens your debugging skills and gives you a deeper understanding of how things work under the hood.</blockquote><blockquote>There are also some extra steps you might need to figure out yourself to get things running smoothly in more advanced setups. But don’t worry — I believe in you. You’ve already made it this far, and that’s no small feat.</blockquote><blockquote>Please don’t forget to share your journey below — especially the problems you faced and how you solved them. Your experience might be exactly what someone else needs.</blockquote><blockquote><strong><em>“Troubleshooting isn’t failure — it’s the forge where real skills are made.”</em></strong></blockquote><h3>🙏 Acknowledgments</h3><ul><li><a href="https://kubernetes.io/docs/tutorials/kubernetes-basics/">Kubernetes documentation</a></li><li><a href="https://developer.hashicorp.com/vagrant/docs">Vagrant Documantation</a></li><li>The amazing DevOps community</li><li>The amazing Kubernetes community</li></ul><h3>Want to Learn More? 📚</h3><p>Check out the complete project on GitHub: <a href="https://github.com/yourusername/vagrant-kubernetes">Vagrant Kubernetes Cluster</a></p><p>Happy clustering! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51915d0540e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guardrails for Your Cloud: A Simple Guide to OPA and Terraform]]></title>
            <link>https://medium.com/devsecops-ai/guardrails-for-your-cloud-a-simple-guide-to-opa-and-terraform-aada0d589dc5?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aada0d589dc5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[policy-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 08:13:39 GMT</pubDate>
            <atom:updated>2025-05-07T20:06:10.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*1dJd9q04exEFEbTwBm02yg.jpeg" /></figure><h3>Introduction: Why We Need Policy Gates</h3><p>Imagine you’re building a massive cloud infrastructure with dozens of developers deploying resources daily. Without guardrails, this freedom can quickly lead to:</p><ul><li>Security vulnerabilities from misconfigured resources</li><li>Unexpected costs from oversized instances</li><li>Compliance violations that put your organization at risk</li><li>Configuration drift that makes environments unpredictable</li></ul><p>This is where <strong>Open Policy Agent (OPA)</strong> comes in — think of it as a friendly but strict security guard for your infrastructure code.</p><h3>What is OPA? The Infrastructure Judge</h3><p>OPA is an open-source, general-purpose policy engine that can:</p><ul><li>Evaluate JSON data against policy rules</li><li>Make yes/no decisions about whether operations should proceed</li><li>Provide detailed reasons for those decisions</li></ul><p>OPA doesn’t just work with Terraform — it can evaluate policies across Kubernetes, CI/CD pipelines, API gateways, and more. But today, we’ll focus on how it supercharges your Terraform workflow.</p><h3>Why Terraform + OPA = Infrastructure Magic</h3><p>When paired with Terraform, OPA becomes your policy-as-code solution that can:</p><ol><li><strong>Prevent problematic deployments</strong> before they happen</li><li><strong>Automate approvals</strong> for safe changes</li><li><strong>Reduce human review burden</strong> by focusing only on policy violations</li><li><strong>Enforce standards consistently</strong> across teams and projects</li></ol><h3>How It Works: The Simple Version</h3><p>Here’s the basic flow:</p><ol><li>Developer writes Terraform code to create/modify infrastructure</li><li>Before applying, Terraform generates a plan (what will change)</li><li>This plan is converted to JSON</li><li>OPA evaluates the JSON against policy rules written in Rego</li><li>OPA returns pass/fail and reasons</li><li>Based on results, the pipeline either proceeds or blocks the changes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqWLLqndk1rplFDc8hmpLQ.png" /></figure><h3>Writing Your First OPA Policy in Rego</h3><p>Rego is OPA’s policy language. It looks intimidating at first, but the basics are simple. Here’s a policy checking if S3 buckets have encryption enabled:</p><pre>package terraform.cloud_resources</pre><pre># Rule that evaluates to true if all S3 buckets have encryption enabled<br>s3_buckets_encrypted {<br>    bucket := input.resource_changes[_]<br>    bucket.type == &quot;aws_s3_bucket&quot;<br>    <br>    # Check if server-side encryption is configured<br>    encryption := bucket.change.after.server_side_encryption_configuration[_].rule<br>    encryption.apply_server_side_encryption_by_default.sse_algorithm<br>}</pre><h3>Real-World Policies You Can Implement Today</h3><p>Let’s look at some practical policies you might want to enforce:</p><h3>1. Blast Radius Control</h3><p>Limit the scope of changes in a single deployment:</p><pre># Only allow plans that modify less than 30% of resources<br>blast_radius_threshold := 30</pre><pre>authz if {<br>    blast_radius.score &lt; blast_radius_threshold<br>    # Other conditions...<br>}</pre><h3>2. Required Resource Tagging</h3><p>Ensure all resources have required tags for cost allocation and governance:</p><pre># Enforce specific tags on all resources<br>required_tags := [<br>    &quot;Environment&quot;,<br>    &quot;Project&quot;,<br>    &quot;Owner&quot;<br>]</pre><pre>resources_have_required_tags {<br>    resource := input.resource_changes[_]<br>    all_tags_present(resource.change.after.tags)<br>}</pre><h3>3. Deployment Schedule Restrictions</h3><p>Prevent risky deployments during critical business periods:</p><pre># No deployments on weekends or Fridays<br>restricted_days := [&quot;Friday&quot;, &quot;Saturday&quot;, &quot;Sunday&quot;]</pre><pre>is_restricted_day {<br>    day := time.weekday(time.now_ns())<br>    restricted_days[_] == day<br>}</pre><h3>4. Security Controls</h3><p>Block common security misconfigurations:</p><pre># Prevent security groups with wide-open access<br>open_security_group_rules {<br>    sg := input.resource_changes[_]<br>    sg.type == &quot;aws_security_group&quot;<br>    <br>    rule := sg.change.after.ingress[_]<br>    rule.cidr_blocks[_] == &quot;0.0.0.0/0&quot;<br>    rule.from_port &lt;= 22<br>    rule.to_port &gt;= 22<br>}</pre><h3>Implementing OPA in Your Workflow<br>Here’s how to integrate OPA into your Terraform workflow:</h3><ol><li>Generate a Terraform plan:</li></ol><pre>terraform plan - out tfplan.binary</pre><p>2. Convert the plan to JSON:</p><pre>terraform show -json tfplan.binary &gt; tfplan.json</pre><p>3. Run OPA against policies:</p><pre>opa exec - decision terraform/analysis/authz - bundle policy/ tfplan.json</pre><p>4. Check the detailed results:</p><pre>opa exec - decision terraform/analysis/authz_reason - bundle policy/ tfplan.json</pre><h3>Advanced: OPA Beyond Basic Checks</h3><p>As you get comfortable with OPA, you can implement more sophisticated policies:</p><ul><li><strong>Drift detection</strong>: Identify when resources have been changed outside of Terraform</li><li><strong>Cost estimation</strong>: Reject changes that would exceed budget thresholds</li><li><strong>Cross-resource validation</strong>: Ensure related resources are configured correctly together</li><li><strong>Contextual approvals</strong>: Apply different rules based on environment or team</li></ul><h3>Conclusion: Start Small, Scale Up</h3><p>The beauty of OPA is that you can start with just one or two simple policies and gradually build up your policy library. Each policy you add creates another layer of protection for your infrastructure.</p><p>Begin with the most critical rules for your organization — maybe it’s ensuring encryption, proper tagging, or preventing public access to sensitive resources. Then expand as your team gets comfortable with the process.</p><p>By implementing policy as code with OPA and Terraform, you’re building guardrails that help developers move fast without breaking things — or at least without breaking important things!</p><p><em>Ready to get started? Clone our sample </em><a href="https://github.com/TryToLearnProgramming/opa-terraform-policies"><em>repository</em></a><em> with ready-to-use policies for common AWS resources and see how OPA can transform your infrastructure governance today.</em></p><h3>🙏 Acknowledgments</h3><ul><li><a href="https://www.openpolicyagent.org/docs/latest/">Open Policy Agent Documentation</a></li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">Terraform AWS Provider</a></li><li>The amazing DevOps community</li><li>The amazing DevOps community</li></ul><p><em>Ready to get started? Clone our sample repository with ready-to-use policies for common AWS resources and see how OPA can transform your infrastructure governance today.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aada0d589dc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/guardrails-for-your-cloud-a-simple-guide-to-opa-and-terraform-aada0d589dc5">Guardrails for Your Cloud: A Simple Guide to OPA and Terraform</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Docker container deployment in EC2 using custom-git-agent]]></title>
            <link>https://medium.com/@er.samibanerjee/automate-docker-container-deployment-in-ec2-using-custom-git-agent-b481d17947a?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b481d17947a</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 08:32:30 GMT</pubDate>
            <atom:updated>2023-09-01T08:33:44.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*I7FDq-Uo-Nj5g-M3bA7cZQ.png" /></figure><p>Before CI/CD was introduced, the manual process looked like this. Developers push their code into GitHub and ask the DevOps/deployment team to deploy it on the server. But time has changed. Now we all are aware of the power of automation.</p><h4>****************************BUT******************************</h4><h3>Every time whenever we need an automated deployment or CI/CD solution in EC2 we always think about Jenkins or AWS CodeDeploy, but how about that if we have a service running in the EC2 which automatically detects the events from GitHub or Bitbucket and deploys our code in EC2/Server and run it as well.</h3><h3>Here I try to create a custom agent for this. So, Let&#39;s get started 😊</h3><p>Let&#39;s assume the scenario first, then we jump on the code and setup. Here we have a Server/EC2 we need to deploy a docker application in it. For building a docker image we will use GitHub-actions and store that image into DockerHub. Then we trigger our custom-git-agent after the GitHub-action task is completed and the agent will pull the image from the docker hub in EC2 and run that.</p><p>First step: Write some Python code to create a flask app (our agent)</p><pre>from flask import Flask, request, jsonify<br>import subprocess<br>import os<br><br>app = Flask(__name__)<br><br># Path of the Scripts<br>SCRIPTS_DIR = &quot;/home/ubuntu/scripts&quot;<br><br># Define a route to receive the GitHub webhook events<br>@app.route(&#39;/webhook/&#39;, methods=[&#39;POST&#39;])<br>def webhook():    <br>    payload = request.get_json()<br>    # Extract relevant information from the payload<br>    event_type = request.headers.get(&#39;X-GitHub-Event&#39;)<br>    print(&quot;the event =&gt; &quot;,event_type)<br>    tag = payload[&#39;tag&#39;]<br>    # Run a shell script based on event type<br>    if event_type == &#39;workflow_run&#39;:<br>        print(&quot;github_actions started...&quot;)<br>        script_path = os.path.join(SCRIPTS_DIR, &quot;action-script.sh&quot;)<br>        subprocess.run([&quot;bash&quot;, script_path, tag])<br>        print(&quot;sucessfully run: &quot;, script_path)<br>    return jsonify({&#39;message&#39;: &#39;Webhook received&#39;}), 200<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><p>Our Python script is ready. It will run on port 8080 and listen to GitHub/Bitbucket’s events. Next, create an action-script for the task you want to perform:</p><pre>#!/bin/bash<br><br>if [ ! -x &quot;$(command -v docker)&quot; ]<br>then<br>    sudo apt install -y docker.io<br>fi<br><br>if [ $(sudo docker ps -aq)!=&quot;&quot; ]<br>then<br>    echo &quot;removing old cotainer and Image...\n&quot;<br>    sudo docker rm -f $(sudo docker ps -aq)<br>    sudo docker rmi -f $(sudo docker images -aq)<br>fi<br><br>echo &quot;Running new image...&quot;<br>sudo docker run -d --rm -p 80:80 --name web sami203/demo-docker:$1</pre><p>sudo chmod 755 action-script.sh</p><p>I write a simple bash script according to the task which I want to perform.</p><p>It will be better to run the .py script as a service, so make it –</p><p>sudo nano /lib/systemd/system/git-agent.service</p><pre>[Unit]<br>Description=Keeping my sources fresher than Arch Linux<br>After=multi-user.target<br><br>[Service]<br>ExecStart=/usr/bin/python3 /home/ubuntu/reader.py<br>Type=simple<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>sudo systemctl daemon-reload</p><p>sudo systemctl enable git-agent.service</p><p>sudo systemctl start git-agent.service</p><p>sudo systemctl status git-agent.seervice</p><p>You successfully set your CD/deployment agent, Congratulations 🎊</p><p>Second Step: Now we have to set up a CI/build environment in GitHub using GitHub-actions.</p><p>Open your GitHub repo click on repo setting and configure actions. Write a build.yml</p><pre>name: Build and Push to Docker-Hub<br><br>on:<br>  push:<br>    branches:<br>      - main<br>    # paths:<br>    #   - .github/**<br>    #   - simpleapp/**<br><br>jobs:<br>  build:<br>    name: Build Docker Image and Push into Docker-Hub<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>      <br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v2<br>        with:<br>          username: ${{ secrets.DOCKER_USERNAME }}<br>          password: ${{ secrets.DOCKER_PASSWORD }}<br>      <br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v2<br>      <br>      - name: Build and push<br>        uses: docker/build-push-action@v4<br>        with:<br>          context: .<br>          file: ./Dockerfile<br>          push: true<br>          tags: ${{ secrets.DOCKER_USERNAME }}/demo-docker:${{ github.sha }}<br><br>      - name: The current paths<br>        run:<br>          echo $PWD<br><br>      - name: webhook call<br>        run: |<br>          curl -s -o /dev/null -X POST -H &quot;Content-Type: application/json&quot; -H &quot;X-GitHub-Event: workflow_run&quot; -d &#39;{&quot;action&quot;:&quot;requested&quot;,&quot;workflow_run&quot;:{&quot;status&quot;:&quot;queued&quot;},&quot;repository&quot;:{&quot;name&quot;:&quot;docker-demo&quot;}, &quot;tag&quot;:&quot;${{ github.sha }}&quot;}&#39; http://&lt;PUBLIC_IP_OF_EC2&gt;:8080/webhook/</pre><p>to trigger the agent we sent a post request with headers and a payload</p><p><strong>curl -s -o /dev/null -X POST -H “Content-Type: application/json” -H “X-GitHub-Event: workflow_run” -d ‘{“action”: “requested”, “workflow_run”:{“status”: “queued”}, “repository”: {“name”: “docker-demo”}, “tag”: “${{ github.sha }}”}’ </strong><a href="http://%3cPUBLIC_IP_OF_EC2%3e:8080/webhook/"><strong>http://&lt;PUBLIC_IP_OF_EC2&gt;:8080/webhook/</strong></a></p><blockquote><strong>You can setup a reverse proxy using nginx for better security.</strong></blockquote><p>Run the action job and wait for a while, we will see your docker application is successfully deployed.</p><p>NOTE:<br>Here is my GitHub repo you can visit for reference -<br>custom-agent=&gt;&gt;<br><a href="https://github.com/TryToLearnProgramming/github-cicd-custome-webhook">https://github.com/TryToLearnProgramming/github-cicd-custome-webhook</a><br>docker-application with github-actions=&gt;&gt;<br><a href="https://github.com/TryToLearnProgramming/docker-demo">https://github.com/TryToLearnProgramming/docker-demo</a></p><h4>Thank You</h4><h3>Here I am, signing off. I will come back with another topic. Thank you for joining me on this topic. I appreciate your time and engagement. Stay tuned for more interesting discussions in the future!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b481d17947a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Deploy a 3-Tier Application in EKS and Implement CI-CD with GitHub and ArgoCD.]]></title>
            <link>https://medium.com/@er.samibanerjee/how-to-deploy-a-3-tier-application-in-eks-and-implement-ci-cd-with-github-and-argocd-22d5258f0113?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/22d5258f0113</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 07:23:01 GMT</pubDate>
            <atom:updated>2023-11-28T05:30:14.133Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p><em>“Containerization is this trend that’s taking over the world to allow people to run all kinds of different applications in a variety of different environments. When they do that, they need an orchestration solution in order to keep track of all of those containers and schedule them and orchestrate them. Kubernetes is an increasingly popular way to do that.” — </em>Dan Kohn <a href="http://bitmason.blogspot.com/2017/02/podcast-cloud-native-computing.html">(<em>Cloud Native Computing Foundation (CNCF), in a podcast with Gordon Haff)</em></a></p><p><strong>WHAT ARE KUBERNETES AND EKS?🤔</strong><br>Kubernetes or K8S is an open-source container orchestration tool it helps to deploy, manage, and scale containerized applications.<br>So, <a href="https://aws.amazon.com/eks/"><strong>EKS</strong></a> is a managed Kubernetes service to run Kubernetes in the AWS cloud.</p><p><strong>WHAT DOES A 3-TIER APPLICATION MEAN?</strong> <br>An application that has a presentation tier or user interface; the application tier, where data is processed; and the data tier, where the data associated with the application is stored and managed.</p><h3>Now Let’s move on to our agenda, how to deploy our 3-tier application in EKS and implement CICD with GitHub Actions and ArgoCD. You can see the diagram below.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrNRP31C1Ynl9jc87n5s2Q.jpeg" /></figure><p>So first we need to create an application and containerized it and store that container images in a container image registry (like — Dockerhub, ECR, etc. Here I use DockerHub). Then we create an EKS cluster in AWS and then we automate the deployment process with CI/CD (GithubActions/ArgoCD).</p><p>Step 1:<br>Here I created a simple application using ReactJS(as front-end), NodeJs(Express as back-end), and MongoDB (as Database). This application has some basic features like login, register, update, and delete. <br>We containerize this application with Docker.</p><pre># back-end container<br>FROM node:16.20<br>WORKDIR /app<br>COPY . .<br>RUN cp .env.example.docker .env<br>RUN npm install<br>RUN npm install pm2 -g<br>EXPOSE 7770<br>ENTRYPOINT [&quot;pm2-runtime&quot;, &quot;index.js&quot;]</pre><pre># front-end container<br>FROM node:16.20 AS node-build<br>WORKDIR /app<br>COPY . .<br>RUN cp .env.example .env<br>RUN yarn<br>RUN yarn build<br><br>FROM nginx:alpine<br>WORKDIR /usr/share/nginx/html<br>RUN rm -rf ./*<br>COPY --from=node-build /app/build/ .<br>COPY default.conf /etc/nginx/conf.d/<br>ENTRYPOINT [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Here is the GitHub repo — <a href="https://github.com/TryToLearnProgramming/e-commerce-front-end/tree/fe-ci">fe</a>, <a href="https://github.com/TryToLearnProgramming/e-commerce-back-end/tree/be-ci">be</a> for reference.</p><p>Step 2:<br>Create all the necessary manifest files which were going to use for Kubernetes deployment inside a separate repo, later we will use this repo for CD (Continuous Deployment) purposes. I named this repo <a href="https://github.com/TryToLearnProgramming/gitops/tree/k-argo">gitops</a>, because we going to follow the well-known <a href="https://www.redhat.com/en/topics/devops/what-is-gitops">GitOps</a> method here.</p><p>Step 3: Create an EKS cluster in AWS<br>Install <a href="https://awscli.amazonaws.com/AWSCLIV2.msi">AWS-CLI</a>, and <a href="https://kubernetes.io/docs/tasks/tools/">Kubectl</a>, <a href="https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html">eksctl</a> in your local system.</p><p>step A:<br>Create an IAM user with programmatic access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*N0x4tTwDnirHykab_5wpOg.png" /></figure><p>I attached a custom policy (eks_full_access) that this user can access AWS EKS console.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;eks:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;iam:PassRole&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;iam:PassedToService&quot;: &quot;eks.amazonaws.com&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>then create an Access-Key and Secret-Access-Key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*hvNLiFMMHg6RuXiosRHfyQ.png" /></figure><p>use this commands to configure aws cli —</p><pre>aws configure set aws_access_key_id AJFJVDYF.....<br>aws configure set aws_secret_access_key 2ttfdGD/uivIH.....<br>aws configure set default.region ap-northeast-1</pre><p>step B:<br>Create two Roles<br>1. for the EKS cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*HDPl6QfvOEkHIdHBBdu66w.png" /></figure><p>2. for EKS node_group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*ApYtrYMoudcZe29hpYLh3A.png" /></figure><p>step C: Create an EKS cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9f04Awd3jEU4RaccAThxw.png" /></figure><p>step D: Create NodeGroup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKiuEab-JBX3wKnP2Sl85Q.png" /></figure><p>step E: Access EKS throuch you Terminal</p><pre>aws eks update-kubeconfig --region ap-northeast-1 --name Test_Node<br>kubectl get ns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*yPSVD2jr_pHynnrLFYsARQ.png" /></figure><p>step F: Install add-ons in EKS cluster<br>Ingress-nginx controller:</p><p>Bofre this stape you have to issue a wildcard certificate from AWS ACM for your domain. Here in my case I issued a wildcard certificate for my domain <br>*.yourdomain.com (i.g *.showyrskills.in)</p><pre>1. Download the deploy.yaml template:<br>wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/aws/nlb-with-tls-termination/deploy.yaml<br>2. Edit the file and change the VPC CIDR in use for the Kubernetes cluster:<br>proxy-real-ip-cidr: XXX.XXX.XXX/XX<br>3. Change the AWS Certificate Manager (ACM) ID as well:<br>arn:aws:acm:us-west-2:XXXXXXXX:certificate/XXXXXX-XXXXXXX-XXXXXXX-XXXXXXXX<br>4. Deploy the manifest:<br>kubectl apply -f deploy.yaml<br><br><br><br><br>** reference: https://kubernetes.github.io/ingress-nginx/deploy/#aws</pre><p>Now check in AWS&gt;EC2&gt;LoadBalancer you will see a load balancer created by NGINX ingress-controller type Network. Now point your domain to this DNS from AWS Route53 or CPanel or where your domain is for hosting.</p><p>Here I have 3 domains -<br>showyrskills.in =&gt; front end<br>api.showyrskills.in =&gt; back end<br>argo.showyrskills.in =&gt; argocd console</p><p>ArgoCD:</p><pre>kubectl create namespace argocd &amp;&amp; kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml </pre><pre># argo-svc-ingress.yaml<br><br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: argo-service<br>  namespace: argocd<br>spec:<br>  type: NodePort <br>  selector:<br>    app.kubernetes.io/name: argocd-server<br>  ports:<br>    - name: http<br>      port: 80 # Service Port<br>      targetPort: 8080 # Container Port<br>      nodePort: 31880<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  annotations:<br>    kubernetes.io/ingress.class: nginx<br>    nginx.ingress.kubernetes.io/backend-protocol: &quot;HTTPS&quot;<br>    nginx.ingress.kubernetes.io/force-ssl-redirect: &quot;true&quot;<br>  name: argocd-ingress<br>  namespace: argocd<br>spec:<br>  rules:<br>  - host: argo.showyrskills.in<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: argocd-server<br>            port:<br>              number: 80<br></pre><pre>kubectl apply -f argo-svc-ingress.yaml</pre><p>try to log in to ArgoCD console;<br> username: admin<br> password: kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; | base64 -d #for linux user</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot; <br><br># open https://www.base64decode.org/ &gt; and enter the return value.<br># for windows system.</pre><p>Step 4: Configure CI/CD:</p><p>CI -<br>Add .github/workflows/<a href="https://github.com/TryToLearnProgramming/e-commerce-front-end/blob/fe-ci/.github/workflows/ci.yml">ci.yml</a> in <strong>fe</strong> and <strong>be</strong> repo.</p><pre>#fe/.github/workflows/ci.yaml<br>name: Build and Push to Docker-Hub<br><br>on:<br>  push:<br>    branches:<br>      - fe-ci<br><br>jobs:<br>  build:<br>    name: Build Docker Image and Push into Docker-Hub<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>      <br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v2<br>        with:<br>          username: ${{ secrets.DOCKER_USERNAME }}<br>          password: ${{ secrets.DOCKER_PASSWORD }}<br>      <br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v2<br>      <br>      - name: Build and push<br>        uses: docker/build-push-action@v4<br>        with:<br>          context: .<br>          file: ./Dockerfile<br>          push: true<br>          tags: ${{ secrets.DOCKER_USERNAME }}/e-commerce-front-end:${{ github.sha }}<br><br>      - name: The current paths<br>        run:<br>          echo $PWD<br>      - name: Checkout GitOps<br>        uses: actions/checkout@v3<br>        with:<br>          repository: TryToLearnProgramming/gitops<br>          path: ./gitops<br>          ref: k-argo<br>          token: ${{ secrets.REPO_PAT }}<br>      <br>      - name: update kustomization in gitops<br>        run:  |<br>          cd gitops<br>          sed -Ei &quot;/\-\ name\:\ sami203\/e\-commerce\-front\-end$/{n;s/\w+$/${{ github.sha }}/}&quot; ./deployments/node-app/kustomization.yaml<br>          git config --global user.email &quot;samivivake@gmail.com&quot;<br>          git config --global user.name &quot;gitops&quot;<br>          git add .<br>          git commit -m &quot;Deploying latest image&quot;<br>          git pull &amp;&amp; git push</pre><pre>#be.github/workflows/ci.yaml<br>name: Build and Push to Docker-Hub<br><br>on:<br>  push:<br>    branches:<br>      - be-ci<br>    # paths:<br>    #   - .github/**<br>    #   - simpleapp/**<br><br>jobs:<br>  build:<br>    name: Build Docker Image and Push into Docker-Hub<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>      <br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v2<br>        with:<br>          username: ${{ secrets.DOCKER_USERNAME }}<br>          password: ${{ secrets.DOCKER_PASSWORD }}<br>      <br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v2<br>      <br>      - name: Build and push<br>        uses: docker/build-push-action@v4<br>        with:<br>          context: .<br>          file: ./dockerfile.back-end<br>          push: true<br>          tags: ${{ secrets.DOCKER_USERNAME }}/e-commerce-back-end:${{ github.sha }}<br><br>      - name: The current paths<br>        run:<br>          echo $PWD<br>      - name: Checkout GitOps<br>        uses: actions/checkout@v3<br>        with:<br>          repository: TryToLearnProgramming/gitops<br>          path: ./gitops<br>          ref: k-argo<br>          token: ${{ secrets.REPO_PAT }}<br>      <br>      - name: update kustomization in gitops<br>        run:  |<br>          cd gitops<br>          sed -Ei &quot;/\-\ name\:\ sami203\/e\-commerce\-back\-end$/{n;s/\w+$/${{ github.sha }}/}&quot; ./deployments/node-app/kustomization.yaml<br>          git config --global user.email &quot;samivivake@gmail.com&quot;<br>          git config --global user.name &quot;gitops&quot;<br>          git add .<br>          git commit -m &quot;Deploying latest image&quot;<br>          git pull &amp;&amp; git push</pre><p>you can change this accordingly.</p><p>then configure Actions secrets and then wait to push your code to the repo.</p><p>GitHub action will build Docker Image and then push it into DockerHub then it will update the image tag in deployments/node-app/kustomization.yaml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*N3DgDdb0f7R4ud8oAIJFZQ.png" /></figure><p>CD — <br>As previously discussed, we going to use <a href="https://github.com/TryToLearnProgramming/gitops/tree/k-argo/deployments/node-app">gitops</a> as our CD repo, ArgoCD will read the changes and deploy the changes into the EKS. So how it will detect the changes? for this we use kustomization. You can read more about Kustomize on there official page (<a href="https://kustomize.io/">click_here</a>).</p><pre># deployment kustomization.yaml<br><br>namespace: node-app<br>resources:<br>  - ../../base/apps/be<br>  - ../../base/apps/fe<br>  - ../../base/apps/mongo<br>  - be-ingress.yaml<br>  - fe-ingress.yaml<br>  - be-cm.yaml<br>patchesStrategicMerge:<br>  - be-deploy.yaml<br>  - fe-deploy.yaml<br>images:<br>  - name: sami203/e-commerce-front-end<br>    newTag: df9ed947fc47811d1a7c827cf42772d98418e184<br>  - name: sami203/e-commerce-back-end<br>    newTag: 701e32a54ffa0fe3435e368d3f470c8e0290d0d1</pre><p>and inside every resource directory, there are different kustomization.yaml files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*bWUkEP8VtpZngp_w1W2i-g.png" /></figure><pre># kustomization.yaml<br>resources:<br>  - deploy.yaml<br>  - service.yaml</pre><p>push this repo in github, then run the command to create the argocd application.</p><pre>kubectl apply -f deployments/node-app/app.yaml<br># this is a ArgoCD application manifest file.</pre><p>you can see the application in the ArgoCD console -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*LYcWkLan1XvmXSVPNpMwFg.png" /></figure><p>*** Now push the code into fe and be the repo that you created earlier. Go to the Actions tab, you will see that the pipeline is running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*ipqWBV-gsVs0xfmcakv0JA.png" /></figure><p>let&#39;s wait till complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*4bTksvzaEnql1yZNBpHHyw.png" /></figure><p>Go to ArgCD and you will see the deployment process is started automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BREI7vJATo09pyl8yAatMw.png" /></figure><p>Wait for some time then try to access your front-end and back-end sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*fjNBtUnfua9tRO-mKlG7JQ.png" /></figure><p>register a user and you are able to log in to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwwRyd1fjHP7ldWgICYlrA.png" /></figure><h3>Congratulations!!! You successfully deploy an Application in EKS 🎉🥳🎉.</h3><p><strong>But one thing</strong>, in starting I said this is a 3-tier application right? so, where is the database ??? 🙄. Don’t worry we already have a database pod running, and the manifest files are inside <a href="https://github.com/TryToLearnProgramming/gitops/tree/k-argo/base/apps/mongo">gitops/base/apps/mongo/</a>. In base/app, we have basic application manifests deployment, service, secrets, pv, pvc. And in <a href="https://github.com/TryToLearnProgramming/gitops/tree/k-argo">gitops</a>/<a href="https://github.com/TryToLearnProgramming/gitops/tree/k-argo/deployments">deployments</a>/node-app/ we have application manifests ingress, configmap, argocd-application which can be changed quickly if required.</p><p>For a better understanding please follow the GitHub repositories.</p><h3>Thank You</h3><p>follow for more content and keep reading 😊.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22d5258f0113" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about Load balancers | Set-up an Application Loadbalencer in AWS]]></title>
            <link>https://medium.com/@er.samibanerjee/all-you-need-to-know-about-load-balancers-set-up-an-application-loadbalencer-in-aws-ac2cd4c1429?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2cd4c1429</guid>
            <category><![CDATA[elb]]></category>
            <category><![CDATA[application-load-balancer]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 13:32:32 GMT</pubDate>
            <atom:updated>2023-03-21T13:32:32.529Z</atom:updated>
            <content:encoded><![CDATA[<p>Let&#39;s assume there is a server and many clients are visiting it, suddenly the number of clients increases so, now what? the response time get will slow down or might crash cause the server is processing an excessive amount of requests.</p><p>How we avoid this situation? We can do one thing, we can use multiple servers and distribute that total load among them.</p><p>But How? Don’t worry, there is a method called Load Balancing, which distributes the load among multiple servers. Using the load balancing technique reduces response time, increases throughput, and in general speed things up for each end user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*UKJKdwekf_dhkaekl4Bcyg.jpeg" /></figure><blockquote>A load balancer acts as the “traffic police” <a href="https://medium.com/@itIsMadhavan/what-is-load-balancer-and-how-it-works-f7796a230034">sitting in front of your servers and routing client requests across all servers capable of fulfilling those requests in a manner that maximizes speed and capacity utilization and ensures that no one server is overworked, which could degrade performance. If a single server goes down, the load balancer redirects traffic to the remaining online servers. When a new server is added to the server group, the load balancer automatically starts to send requests to it.</a></blockquote><p>Load balancers are divides in to two categories — <strong>Layer-7(Application loadbalancer) and Layer-4(Network loadbalancer)</strong></p><p><a href="https://docs.aws.amazon.com/elasticloadbalancing/index.html#elastic-load-balancing---version-2"><strong>In AWS there is Elastic Load Balancing (ELB), under ELB there are different Load Balancers:</strong></a></p><p><strong>Application Load balancer</strong> (ALB)—<br>An Application Load Balancer functions at the application layer, the seventh layer of the OSI model. After the load balancer receives a request, it evaluates the listener rules in priority order to determine which rule to apply and then selects a target from the target group for the rule action. You can configure listener rules to route requests to different target groups based on the content of the application traffic. Routing is performed independently for each target group, even when a target is registered with multiple target groups. You can configure the routing algorithm used at the target group level. The default routing algorithm is round robin; alternatively, you can specify the least outstanding requests routing algorithm.</p><p><strong>Network Load Balancer (NLB) — <br></strong>A Network Load Balancer functions at the fourth layer of the OSI model. It can handle millions of requests per second. After the load balancer receives a connection request, it selects a target from the target group for the default rule. It attempts to open a TCP connection to the selected target on the port specified in the listener configuration.</p><p><strong>Classic Load Balancer (CLB) — <br></strong>A Classic Load Balancer more closely resembles traditional load balancing, but virtual devices replace physical hardware to evenly distribute your incoming requests and ensure a clean, fast user experience.</p><p><strong>Gateway Load Balancer — <br></strong>A Gateway Load Balancer operates at the third layer of the Open Systems Interconnection (OSI) model, the network layer. It listens for all IP packets across all ports and forwards traffic to the target group that’s specified in the listener rule. It maintains the stickiness of flows to a specific target appliance using a 5-tuple (for TCP/UDP flows) or 3-tuple (for non-TCP/UDP flows). The Gateway Load Balancer and its registered virtual appliance instances exchange application traffic using the <a href="https://datatracker.ietf.org/doc/html/rfc8926">GENEVE</a> protocol on port 6081.<br>Gateway Load Balancers use Gateway Load Balancer endpoints to securely exchange traffic across VPC boundaries. A Gateway Load Balancer endpoint is a VPC endpoint that provides private connectivity between virtual appliances in the service provider VPC and application servers in the service consumer VPC. You deploy the Gateway Load Balancer in the same VPC as the virtual appliances. You register the virtual appliances with a target group for the Gateway Load Balancer.</p><p>Now let&#39;s set up an Application Load Balancer in AWS:</p><p>step: 1<br>Log in to the AWS console, then launch 2 or more EC2 Instances. Because we are going to balance the load among them -&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xa1Dlns4EqFOy6YuPjs6eQ.png" /></figure><p>give a nice name to that instance, for the quick setup I use “user data” under Advance details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cA5lnWLh2nTFVMKQfeXUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDwzpU9Dts1lL_3LsVJ9Ng.png" /></figure><p>By adding a simple script you can install Nginx and change that index.html file, to show those reflections. now click on <strong>Launch.</strong></p><p>*** use this same process to launch other servers. just change server 1 to server 2 and so on.</p><p>Step 2, create a target group:</p><p>Go to EC2 &gt; load balancing &gt; Target Groups</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*iB6XY82W8YK0tZR1v9x3eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrlRA5sfvE5quQbV3Vc_6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*11lhoPz1epqxLbPSzV2ZLQ.png" /></figure><p>choose the VPC where you launched the instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZx5VBzpg5tI5NYOeRzdiw.png" /></figure><p>after creating the Tagget group we have to associate it with a Load Balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jC5nM8hKckldL3olKPlAg.png" /></figure><p>Step 3, Creating an Application Load Balancer-</p><p>Go to EC2 &gt; Load balancing &gt; Load balancers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*bivm0r25ocPOApwJSMTBKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8PmB9xNPqRfLKBx17iKdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fZFaid7iyZJzT24ORLt_Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcYClqVvRZXBmCVOHKFESA.png" /></figure><p>give a nice name to your load balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjMomUKfj36xbtZhtCYM4w.png" /></figure><p>select your VPC which one you chose for your Target Group. And select at least 2 availability zones with public subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVF2G66oD7pAE8UoZgRH4w.png" /></figure><p>Create a Security Group with HTTP and HTTPS protocols and select your Target Group.</p><p>Security Group -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgv9Z1NE96GtociQ2W5kig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IY3VQuQSZ4w9c74YQOuN4Q.png" /></figure><p>After the load balancer is in the active state, copy the DNS and open it in the browser.</p><p>Continuously refreshing the URL in the browser you can see that the load is distributed between server-1 and server-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*lCLsV3a9jZPqI08W57nWFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*eoRN4YWYBBT1gsvZ9bSj_w.png" /></figure><p>This is how the load balancer works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2cd4c1429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy, Reverse Proxy, and Setup a Reverse Proxy Server with Nginx]]></title>
            <link>https://medium.com/@er.samibanerjee/proxy-reverse-proxy-and-setup-a-reverse-proxy-server-with-nginx-f2e7211826fe?source=rss-5acdf525b2a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e7211826fe</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[nginx-reverse-proxy]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Sami Banerjee]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 10:29:38 GMT</pubDate>
            <atom:updated>2023-02-07T10:29:43.288Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>What is a Proxy? Basically, proxy means the authority to represent someone else.</p><p>Proxy Server 🙄? A <strong>proxy server</strong> is a system or router that provides a gateway between users and the internet.</p><p>Instead of connecting directly to a server, the client directs the request to the proxy server for files and other information. It provides the benefits such as privacy, security, and caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*79pO7-ElxbRYizQn6alFNQ.png" /><figcaption>How client and Server communicate via Proxy</figcaption></figure><p>Now, what is Reverse Proxy? From the name, it&#39;s clear that the process is similar but in a reverse way. In the Proxy method, the proxy server requests the internet on your behalf. In reverse proxy, the incoming requests from the internet reach you through the proxy server instead of exposing your server. It gives you the benefits of the load balancer, privacy, and security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YdoFGoY-f3_hs9ZH.png" /><figcaption>difference between Forward Proxy and Reverse Proxy</figcaption></figure><p>Let’s move on and<br>et’s set up a simple reverse proxy server with Nginx 😄</p><p>Here I use AWS EC2 to create an Nginx Reverse Proxy server and a Destination Server.</p><p>Step-1</p><p>Launch two EC2 instances (I used a Ubuntu Server) one for the destination server and one for the reverse proxy server:-</p><p>Install Nginx in both of the servers</p><pre>sudo apt update &amp;&amp; sudo apt install -y nginx<br>sudo service nginx status</pre><p>now type <a href="http://localhost/">http://</a>&lt;public_ip_of_you_ec2&gt; in your browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTbkhqX-6vGYSk-x2lbeQg.png" /><figcaption>Server A is the destination server Server B is Reverse Proxy Server</figcaption></figure><p>(changed the content in /var/www/html/index.html for identification)</p><p>step-2</p><p>Create Nginx proxy files in /etc/nginx/sites-available/ in Server B (Here I use Server B as a Reverse Proxy server):-</p><pre>sudo nano /etc/nginx/sites-available/proxy<br>sudo ln -s /etc/nginx/sites-available/proxy /etc/nginx/sites-enabled/</pre><pre>                                                                               <br>server{<br>        listen 80;<br>        server_name test.com;<br><br>        location / {<br>                proxy_pass http://35.74.79.211:80;<br>                proxy_set_header Host $Host;<br>                proxy_set_header x-Real-IP $remote_addr;<br>                proxy_set_header x-Forward-For $proxy_add_x_forwarded_for;<br>                proxy_set_header x-Forward-Proto $scheme;<br>        }<br>}</pre><blockquote>I pointed test.com domain with Server B’s public IP (https://43.206.102.50). When you hit this domain the domain redirects you to <a href="http://35.74.79.211/">http://35.74.79.211</a>:80 and you see the server A’s content instead of server B’s. This is how this reverse proxy will work.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*uwjXgmAIckRcX_B1OOtOrw.png" /><figcaption>test.com is pointed with Server B’s public IP, but this content belongs to Server A</figcaption></figure><p>With this technique, we can run applications running on https://localhost:port (i.e, react or node applications) in a domain, just by changing <strong>proxy_pass </strong><a href="http://35.74.79.211:80;"><strong>http://127.0.0.1:&lt;port&gt;;</strong></a><strong> of </strong>the existing server.</p><p>Hope this content is “simple but tasty” as your need. So keep learning, and obviously supporting for more like this; don’t forget to share.</p><h3>Thank You</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e7211826fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>