<?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 Geert Kinthaert on Medium]]></title>
        <description><![CDATA[Stories by Geert Kinthaert on Medium]]></description>
        <link>https://medium.com/@gkinthaert?source=rss-5a0278d79bbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Geert Kinthaert on Medium</title>
            <link>https://medium.com/@gkinthaert?source=rss-5a0278d79bbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gkinthaert/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[Moving from an AI prototype to a real deployment]]></title>
            <link>https://medium.com/@gkinthaert/moving-from-an-ai-prototype-to-a-real-deployment-11bc9fb86bcd?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/11bc9fb86bcd</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[grc]]></category>
            <category><![CDATA[ai-grc]]></category>
            <category><![CDATA[ai-production]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 03:55:32 GMT</pubDate>
            <atom:updated>2026-10-17T03:55:32.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUIzRzx-PcGtF9FXLtONqA.png" /></figure><p><em>Most of us have been building something using LLMs and AI capabilities over the last year or so. I have done so myself using a slew of tools: MCP, n8n, ElevenLabs, RAG, Claude Code, Copilot, Codex, Cursor, Gemini, Ollama, Amazon Bedrock, Amazon SageMaker… the list goes on and on… every week there seems to be some new capability that will enhance our lives or potentially transform what we can deliver for our companies. The prototype is the exciting new shiny object, and fairly quickly implemented. You input some data, get answers, it is fast and it is fun. That is, however, the easy part. Still, you want to get it out into the wild and show off what you build ASAP: Look what I did — isn’t this amazing!!</em></p><p><em>Hold on! Check your enthusiasm: You are actually still miles away from deploying this into something production worthy!</em></p><p>OK, so the prototype worked awesomely. I ran 50 test tickets through the AI ITSM assistant I put together in an hour, and 48 came back with responses that looked correct. I was happy. When I shared it someone even said “this is cool you should launch this thing”.</p><p>In the back of my mind I knew this to be a bit premature: The submissions into the AI tool were clean and somewhat formulaic, I was the sole person using the agent, and nobody had yet asked it an impossible question I would not have thought up myself. I have been around IT projects long enough to know that curbing my enthusiasm was warranted: What you don’t know, or test, is what is likely to hurt you. There is a often used saying in IT going something like someone yelling ‘but <em>it works on my laptop’ </em>while the app in question is on fire in a production environment. I’ve seen that in practice a few times myself.</p><p>AI is not that different from traditional IT since the problem issues are usually similar: crappy data, unclear or non-identified goals, missing evaluations and reality checks, and no way to gauge what is going on once the system is live. The additional, newish layer one might think of as the culprit is the model used, and sure, different models have different capabilities, but to be fair, one should not blame the model if you did not try to tackle data, goals, evals, and monitoring first.</p><p>Not addressing those in IT projects, and specifically, AI projects, will doom your best efforts, and the numbers back this up. MIT’s NANDA initiative reports that about 95% of enterprise generative AI pilots show no measurable P&amp;L impact. IDC research found that for every 33 proofs of concept an enterprise starts, only about 4 reach production. RAND has found that over 80% of AI projects fail, roughly double the rate of ordinary IT projects. Most AI efforts collapse between the prototype and production deployment.</p><h3>So, how to address this?</h3><ol><li><strong>Business-goal translation:</strong> Am I building the right thing?</li><li><strong>Production engineering: </strong>Will that right thing survive reality?</li><li><strong>Evaluation and testing:</strong> Make sure I know when it stops working.</li><li><strong>Reliability engineering:</strong> make sure it keeps working, and fails gracefully when otherwise.</li><li><strong>Governance, risk, and compliance (GRC):</strong> make sure I can prove it is safe, accountable, and allowed to run.</li></ol><h3>First: Good AI can still solve the wrong problem</h3><p>You boss says “We need fewer support tickets.” and you hear “we need a AI chatbot,” so the team builds one, and does it well. Chatbot accuracy lands at 92%.</p><p>And yet, customer satisfaction remains at 40%, support volume remains crazy high, and the business impact is negligible. Nothing is wrong with the AI. We just got the initial analysis wrong.</p><p>When we finally looked at what requesters were actually asking, it was about delays in provisioning/access, and the dominant issue was that they could not tell what the holdup or the status was. The fix that moved the needle was proactive notifications. Fewer “where is my request at?” tickets.</p><p><strong>Business asks for an app or a technology, but what is needed is outcome.</strong> They ask for “AI chatbot,” “automation,” or “machine learning.” What they mean is faster delivery. a status update, lower cost, better customer experience, higher revenue. Get to the bottom of what the real ask is.</p><h3>Discovery conversation</h3><p>It may be worth having a structured discovery session before anyone starts coding (or buying) something. The goal is to turn a vague request like “we want to use AI to automate invoice processing” into a buildable REAL problem. I am looking for five things:</p><ul><li><strong>Business goal:</strong> What is the real desired outcome?</li><li><strong>Current workflow:</strong> What does it look like right now step by step?</li><li><strong>Pain point:</strong> What is the bottleneck, and how bad is it, measured?</li><li><strong>AI opportunity:</strong> Where could we actually deploy AI where it will help?</li><li><strong>Success criteria:</strong> How will we know it worked?</li><li><strong>Constraints: </strong>More on this in the GRC section, but we need to ask about data classification, compliance and regulatory requirements, among others.</li></ul><p>AI is not the first thing I ask about. Instead, ask what outcome the client is trying to improve. If they say they want invoices processed faster, I will ask how long it takes today. That gives us a measurable baseline to work from. Next, I ask them to walk me through what the workflow looks like, with as much detail we can get. Only then do we talk about AI, and by that point the opportunities should reveal themselves. Look for workflow items that are manual, or take a long time, or are repetitive. AI can extract key fields, summarize files, and even flag missing information.</p><p>Also, don’t try to have AI take care of the whole workflow. The biggest impact is often achieved by improving one or a few small components in the flow.</p><h3>The framework</h3><ol><li><strong>Identify the business outcome.</strong> Push beyond “we need AI” to something measurable: processing time, cost, revenue, customer satisfaction, a productivity KPI.</li><li><strong>Map the workflow.</strong> Someone submits an invoice, an employee verifies documents, checks policy, approves or rejects, the requester is notified.</li><li><strong>Find the AI opportunities.</strong> Look for steps that are repetitive, document-heavy, or rule-bound.</li><li><strong>Prototype the minimum viable AI intervention.</strong> Build the smallest useful thing. Less is more! This is important as we often tend to want to over-build.</li></ol><p>Note: The Anthropic engineering team shared in <a href="https://www.anthropic.com/engineering/building-effective-agents"><em>Building Effective Agents</em></a><em>, </em>that after working with dozens of teams, they found that the most successful implementations used simple, composable patterns rather than complex frameworks, and they recommend finding the simplest solution possible and adding complexity only when it is needed. That might mean not building an agent at all. Start with the problem, and let the architecture follow.</p><h3>Second: Production is guardrails around intelligence</h3><ul><li>A <strong>prototype</strong> asks: <em>does it work?</em></li><li>A <strong>production system</strong> asks: <em>when does it fail, and can we detect it and recover?</em></li></ul><p>Prototypes run on limited data, with one or few users, have simple inputs, and involve manual testing. Production means a lot of real data, many users, unexpected inputs, and continuous usage.</p><h3>The prototype is just a few lines of code</h3><p>A basic retrieval-augmented generation (RAG) pipeline is fairly simple: retrieve documents for the query, stuff them into a prompt, call the model, return the answer. While a great way to demo, it is a sure way to fail at a production level at these levels:</p><ul><li><strong>Retrieval</strong>: It grabs the incorrect documents.</li><li><strong>Generation:</strong> The model writes a confident, but incorrect, answer.</li><li><strong>API:</strong> There is a timeout or an outage.</li><li><strong>System:</strong> Nobody can monitor what is going on in this black box</li></ul><p>Often, what breaks, is not one thing. A document parser chokes on a scan, the LLM gets partial text and guesses, validation is either missing or too loose, and a wrong value flows straight into the system.</p><p><strong>The model is not enough.</strong> What surrounds the model mattered much more: data ingestion, validation, business rules, API integration, error handling, monitoring, and a feedback loop with users.</p><h3>Hardening the system</h3><p><strong>Step 1: Improve retrieval and inputs.</strong> Instead of sending a document straight to the model, build a real pipeline: parse, clean, chunk, embed into a vector store, retrieve only the relevant context, and then generate.</p><p>Most wrong answers trace to this layer, not to the model. Treat the quality of your inputs as a engineering issue. Gartner has predicted that a large majority of AI projects without AI-ready data will be abandoned, so this is crucial to address!</p><p><strong>Step 2: Handle failure.</strong> Assume every dependency will time out eventually. Add timeout detection and retries for transient errors. Add a fallback model for when the primary one is down. Validate outputs against a schema and business rules, and reject invalid ones. Anything that still cannot be resolved goes to a human review queue. A graceful “I’m not sure, a person will look at this” beats any confident wrong answer every time.</p><p><strong>Step 3: Make the system observable.</strong> Log structured traces of every request: the input, what was retrieved, the prompt, the output, the validation result, the latency, and the cost. Dashboards for request volume, error rate, and response time, can be valuable.</p><h3>Agents need similar guardrails</h3><p>This is also needed when you move from RAG to agents. A production-ready agent is really a loop: plan, call a tool, observe the result, verify, pass through a decision gate, and then, and only then, complete the task.</p><p>The verification and decision-gate steps are what separate it from a demo. One more lesson from <a href="https://www.anthropic.com/engineering/building-effective-agents">Anthropic’s agent guidance</a>: When they built their coding agent for SWE-bench, they spent more time optimizing the tools than the overall prompt. Clear tool definitions and well-designed interfaces often matter more than clever prompting.</p><h3>Production checklist</h3><p>You need affirmative answers to these questions:</p><ul><li><strong>Retrieval:</strong> Is it finding the right information?</li><li><strong>Validation:</strong> Does it check inputs and outputs?</li><li><strong>Recovery:</strong> Does it handle temporary failures?</li><li><strong>Logging:</strong> Can I determine what happened after the fact?</li><li><strong>Monitoring:</strong> Can I see problems as they emerge in prod?</li><li><strong>Evaluation:</strong> Can I measure whether it is actually working? This one is often skipped by engineers as it is a measure of output quality, not a technical metric.</li></ul><h3>Third: Evaluation is of the utmost importance</h3><p>I have build many a dashboard in my career, and the importance of having this for your AI tools is no less than any other technology. These are useful to show the measure of API success, response time, and number of requests. All systems operational, one would think.</p><p>Then there is the qualitative aspect, a measure that often remains undefined with other technologies as well (i.e. CSAT in ITSM world is sometimes missing or under-reported). Likewise, AI quality is often not measured.</p><p>Let’s say, you update the knowledge base used in RAG with new documents. The system keeps running and the response time is still awesome, but now it cites the old documentation. Nothing alerts you of that. API errors, response time, server health, and request volume are all OK.</p><p>What is not being measured is the answer quality, correctness, grounding, and user satisfaction. Unfortunately the usual way of us finding out is when you get an angry user slacking or emailing you about having gotten the wrong information from your AI tool. Not good. Worse, your whole chain of command is cc-ed.</p><p><strong>Traditional monitoring tells you that the system is running. Evaluation tells you whether it is running correctly.</strong></p><p>These are very different pieces of information, and generative AI makes the second one hard because an AI response can look perfectly correct, while actually being totally wrong.</p><p>And don’t believe just me: <a href="https://hamel.dev/blog/posts/evals-faq/">Hamel Husain and Shreya Shankar</a>, who teach evals to practitioners, note that in the projects they have worked on, 60 to 80% of development time went into error analysis and evaluation. That ratio sounds extreme until you have been burned once.</p><h3>Start with a golden test set</h3><p>Begin with known cases. For example, for a support assistant include the following in the test set: an order-tracking scenario, a refund scenario, a security scenario, and an unexpected question. For invoices, include: clean documents, scans, missing fields, contradictory information, and the odd format nobody planned for. Each has a known good outcome. These sets are your ground truth, and they likely grow every time production teaches you something new.</p><p>Don’t sweat it too much. You will evolve this golden test set over time and will continue to add items during the lifecycle of your AI tool. If you think it to be incomplete or incorrect at first, it will get better.</p><h3>Two ways to check</h3><p>Run the test set through the system and grade the outputs in two complementary ways:</p><ul><li><strong>Rule-based checks</strong> are deterministic and cheap. Is the output valid JSON? Are the required fields present? Does the invoice amount match the source document? Does the answer cite a source? Use code wherever a rule can express the requirement.</li><li><strong>LLM-as-judge</strong> uses a second model to grade what rules cannot, such as whether an answer is grounded in the retrieved context, relevant to the question, and appropriate in tone.</li></ul><p>Here are some best practices for LLM judges:</p><ul><li><strong>Do error analysis first.</strong> Read real traces, take notes on what went wrong, and group the notes into a failure taxonomy. Husain and Shankar recommend reviewing 30 or more traces by hand before automating anything. The failures you find tell you which evaluators to build, so you are not guessing.</li><li><strong>Prefer binary pass/fail over 1 to 5 scores.</strong> Each judge should target one specific failure mode with a clear definition of pass and fail. Vague rubrics produce vague scores.</li><li><strong>Validate the judge against humans.</strong> An LLM judge is itself a model that can be wrong. Label a sample by hand, measure how often the judge agrees, and revisit it periodically.</li><li><strong>Pin the judge’s model version</strong> so your CI results do not shift when a provider updates something underneath you.</li></ul><h3>From responses to numbers</h3><p>Evaluation turns a pile of responses into metrics you can act on: the share of responses that are fully correct, the share that are partial, the hallucination rate, and the trend over time. In the ticketing prototype, 48 out of 50 sounded great. In production I would want that number broken down by category (scanned versus clean, short versus long, each ticket type), because an overall average hides the segments that will hurt you.</p><h3>The loop that saves releases</h3><p>The real power comes from running this continuously in a loop: <strong>test, check, measure, improve.</strong> Wire it into your release process, and it catches regressions before someone else will.</p><p>With this loop in place, a small and well-intentioned change that goes wrong, will produce a blocked release. Without it you should anticipate that angry phone call. The only difference is whether the evaluation loop exists.</p><p>In production the loop keeps running. Score a sample of live traffic, compare against a baseline from previous runs, and alert someone who can step in and fix (maybe you!), when quality degrades, even when every infrastructure related metric is green.</p><p>Investigate, fix, and add the failing case to the golden test set, and ultimately the system improves.</p><h3>Fourth: Reliability engineering keeps it working after you go live</h3><p>Reliability engineering gives an AI system a shared definition of what is ‘good enough’, a budget to address failure, and a practiced response when the thing fails.</p><p>Evaluation tells you whether an answer is right. Reliability engineering decides what the system does about it at 2 a.m., and who gets paged.</p><p>Site reliability engineering (SRE) emerged along running services that had to stay up. AI systems inherit all of those problems and add a new one: a system can be fully available and still be failing. So think about AI reliability in two layers:</p><ul><li><strong>Service reliability</strong> asks whether it is up, fast, and affordable.</li><li><strong>Quality reliability</strong> asks whether it is correct, grounded, and safe.</li></ul><h3>Turn success metric into SLOs</h3><p>In the discovery stage we asked how we would measure success. The answers should become service level objectives (SLOs): explicit targets that the client and the engineering team agree on, long before a production launch.</p><ul><li><strong>Availability: </strong>i.e<strong>. </strong>9.5% of requests return a valid, schema-conformant result.</li><li><strong>Latency:</strong> i.e. 95% of documents under 30 pages finish in under 60 seconds; larger files run asynchronously.</li><li><strong>Quality:</strong> i.e. at least 98% accuracy on critical extracted fields in a weekly human-audited sample, and fewer than 1% of summaries containing an unsupported statement.</li><li><strong>Cost:</strong> i.e. average model and processing cost per claim stays under an agreed ceiling.</li><li><strong>Oversight:</strong> ie. the human review queue is cleared within one business day.</li></ul><p>NOTE: Treat these numbers as items that you negotiate with your leadership, or clients. There is a trade-off that needs to considered, and you have to think of the comfort level of your customer, with $$ spent.</p><h3>Use error budgets to settle the ship-or-fix argument</h3><p>Take feelings, sentiment, opinions out of the equation.</p><p>For example, a 98% quality SLO leaves a 2% error budget. While the system is inside budget, the team keeps shipping features. When quality burns through the budget too fast, new work pauses until reliability recovers.</p><p>This replaces opinion with a rule that engineers and clients agreed to in advance. Pay attention to burn rate, meaning how fast the budget is being consumed, rather than jumping at every individual bad answer.</p><p>Act on trends that matter, instead of noise.</p><h3>Release as if the system is potentially nefarious</h3><p>Before your AI system goes out and takes over a public utility… just kidding but you should put controls in place to avoid even the slightest worry</p><p>In AI systems, code is not the only thing that can change: Prompts, retrieval settings, model versions, and knowledge-base content can all change answers, so you should treat each one as a versioned, reviewable, reversible artifact.</p><ul><li>Run every change through the golden-set regression. That includes knowledge-base updates (which will likely occur quite often)</li><li>Use shadow mode first, where the new version runs on live traffic and its results are compared but not served. Then use a canary on a small slice of traffic, with automatic rollback when quality metrics regress.</li><li>Pin model versions and test upgrades like any other dependency upgrade. A provider’s improvement can be your regression.</li><li>Put a kill switch behind a feature flag so you can drop to human-only handling in minutes.</li></ul><h3>Design for the expected failures</h3><pre>Failure: <strong>Provider timeout or brief outage </strong><br>Reliability pattern: <br>Timeouts, retries with exponential backoff and jitter, fallback model<br><br>Failure: <strong>Retry storm during incident</strong><br>Reliability pattern:<br>Circuit breakers, rate limits, queues that absorb bursts<br><br>Failure: <strong>Retried request processed twice </strong><br>Reliability pattern: <br>Idempotency keys, so a claim is never handled twice<br><br>Failure: <strong>Low confidence/invalid output </strong><br>Reliability pattern: <br>Graceful degradation: flag it, return partial result, route to human review<br><br>Failure: <strong>Corrupt/unreadable document </strong><br>Reliability pattern: <br>Quarantine in a dead-letter queue instead of retrying forever<br><br>Failure: <strong>Runaway agent loop</strong> <br>Reliability pattern: <br>Step limits, token and cost budgets, hard timeouts<br><br>Failure: <strong>Instructions hidden in a document </strong><br>Reliability pattern: <br>Treat document text as data, not commands, restrict tools an agent can call</pre><h3>Break things on purpose</h3><p>Run game days before launch. Inject provider timeouts, feed in corrupted documents and empty retrievals, simulate the jump from 1 to 1000 users with realistic document sizes, and confirm the fallbacks actually fire. Include adversarial inputs too. A claim document that contains text telling the model to ignore its instructions (indirect prompt injection) is a reliability test and a security test in one.</p><h3>Make incidents boring</h3><p>Write runbooks for AI-specific incidents, such as the assistant quoting an outdated policy: flip the kill switch, roll back the knowledge base, notify the client. Hold blameless postmortems, and make one output non-negotiable: every incident adds its failing cases to the golden set. Track time to detect and time to recover. The target I care about most is simple: <strong>Find out before the customer, or the media, does!</strong></p><h3>Fifth: Governance, risk, and compliance are design inputs, not a final stage</h3><p>In regulated industries like insurance, governance, risk, and compliance (GRC) requirements shape the architecture. Many pilots stall here, when security, legal, or compliance reviews are done after the demo, and the system cannot produce the evidence they ask for.</p><h3>Add constraints to the discovery conversation</h3><p>Before design starts, ask:</p><ul><li>What data is in these documents? Personal, financial, or health data changes everything.</li><li>Which jurisdictions and regulators are applicable here?</li><li>Does the system influence a decision about a person, such as approving a claim or setting a price?</li><li>Who is accountable for an AI-assisted decision, by name?</li><li>What will an auditor or regulator want to see, and how long must we keep it?</li></ul><p>These answers let you risk-tier the use case early. In the EU AI Act, for example, AI used for risk assessment and pricing in life and health insurance is explicitly listed as high-risk, and a claims assistant could land close to that line depending on what it decides. Legal will make the classification call, ultimately, but you want to know early in the project.</p><p>Note: A human in the loop reduces risk only if there is real oversight. But if the reviewers approve every AI summary in two seconds, you have a rubber stamp, not a control. Measure override rates and review times so you can tell the difference. By the way, rubber stamping is not an AI specific problem solely, it can be an issue across tech stacks.</p><h3>Map GRC goals to controls</h3><pre>Goal:            Control:                       Evidence:<br>Accountability   Named owner per system         Change records, decision log<br>                 Approvals for material changes<br>Transparency     Source citations, links from   Traces showing what the model<br>                 each summary to claim docs,    saw<br>                 clear AI involvement <br>                 disclosure<br>Human oversight  Review queue,                  Review logs with override<br>                 confidence thresholds,         rates<br>                 ability to override,<br>                 abilit to escalate<br>Accuracy and     Golden sets, regression        Eval reports and CI history<br>robustness       gates, SLOs<br><br>Data protection  Data minimization, PII         Dataflow map, retention<br>and privacy      redaction before model         policy<br>                 calls, retention limits,<br>                 access controls, data<br>                 residency, vendor terms<br>                 on data use<br><br>Security         Prompt injection defense,      red team, test results<br>                 least privilege settings,<br>                 secrets management<br><br>Fairness         Evaluate quality by            slice level metrics<br>                 segment, review outcomes<br>                 for unequal impact<br><br>Auditability     Structured logs for            tamper free audit trail<br>                 input, retrieved sources,<br>                 prompt and model versions,<br>                 output, and reviewer<br><br>Incident         runbooks, kill switch,         incident register, tickets<br>response         postmortems, client<br>                 notification process.</pre><h3>Know the frameworks, and map them to your loop</h3><ul><li><strong>NIST AI Risk Management Framework</strong> organizes the work into four functions: Govern, Map, Measure, and Manage.</li><li><strong>ISO/IEC 42001</strong> is a certifiable standard for an AI management system.</li><li><strong>The EU AI Act</strong> applies risk tiers, with the heaviest duties on high-risk systems: risk management, data governance, documentation, human oversight, and post-market monitoring.</li><li><strong>Existing rules </strong>Privacy law such as GDPR, HIPAA, and attestations such as SOC 2 apply to AI systems.</li></ul><h3>Some documents worth keeping around</h3><ol><li><strong>System record.</strong> Covers purpose, intended and out-of-scope uses, data sources, model and prompt versions, known limitations, latest eval results, and the accountable AI owner.</li><li><strong>Risk register.</strong> Lists the top risks, such as wrong claim values, personal data leaking into prompts, prompt injection, and outdated policy answers. Scored by likelihood and impact, assigned an owner, and linked to a specific test and a specific alert.</li><li><strong>Change log.</strong> Every model upgrade, prompt edit, and knowledge-base update passes the regression gate and gets recorded. This is the document that answers the question every auditor eventually asks: what changed, and who approved it?</li></ol><p>Note: GRC does not slow delivery of your AI project. It is what lets a system exist in a regulated environment.</p><h3>Wrapping it up</h3><p>So, the next time you complete an AI tool or agent and have dreams of moving from lab prototype to a production environment where it will be accessed and used by others, spend a few minutes on what that should look like:</p><ol><li>Do I know what business outcome this addresses, and how I will measure it?</li><li>Do I know how it could fail, and what happens when it does?</li><li>Will I hear about a regression/failure from a test, or from a user?</li><li>Could I show an auditor what the system did, why, and who approved the change?</li></ol><p>If you have a promising demo, don’t let it intimidate you, but know that some interesting work is still to be done...</p><h3>Sources</h3><ul><li>Anthropic Engineering, <a href="https://www.anthropic.com/engineering/building-effective-agents"><em>Building Effective Agents</em></a></li><li>Hamel Husain and Shreya Shankar, <a href="https://hamel.dev/blog/posts/evals-faq/"><em>AI Evals: Everything You Need to Know</em></a></li><li>Arize Phoenix documentation on <a href="https://arize.com/docs/phoenix/evaluation/concepts-evals/llm-as-a-judge">LLM-as-a-judge best practices and golden datasets</a></li><li>MIT NANDA, <em>The GenAI Divide: </em><a href="https://www.aigl.blog/state-of-ai-in-business-2025/"><em>State of AI in Business 2025</em></a></li><li>RAND Corporation <a href="https://www.rand.org/pubs/research_reports/RRA2680-1.html">research on why AI projects fail</a></li><li>NIST, <em>AI Risk Management Framework (AI RMF 1.0)</em></li><li>ISO/IEC 42001, the standard for AI management systems</li><li>Google, <a href="https://research.google/pubs/site-reliability-engineering-how-google-runs-production-systems/"><em>Site Reliability Engineering</em></a>, on SLOs, error budgets, and postmortems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11bc9fb86bcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform primer 4: HCP]]></title>
            <link>https://medium.com/@gkinthaert/terraform-primer-4-hcp-483dd65f73ee?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/483dd65f73ee</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraform-cloud]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 14:10:53 GMT</pubDate>
            <atom:updated>2026-10-14T14:10:53.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVPn0lfszEZmqS9Q_zDOfQ.png" /></figure><p>The last post in the Terraform series. There are no real technical nuggets in this one, but a good read if you have questions on HOW you want to set up your Terraform infrastructure in order to further safeguard your operations.</p><h3>HCP Terraform: Managing infrastructure at enterprise scale</h3><p>You build modules, you organize your code, and set up remote state in Amazon S3 or Azure Storage. Your team collaborates via pull requests. You have a flow going and life is great.</p><p>Then you, or ‘someone’ accidentally runs <em>terraform apply </em>directly on a laptop, bypassing the code review process. Or, worse, you (or someone) accidentally destroys production infrastructure. It can happen.</p><p>This is where HCP Terraform can come to the rescue. HCP Terraform brings governance to Terraform itself. It is an enterprise platform that turns local Terraform into an audited, approved, and cost-estimated system.</p><h3>Terraform on a laptop vs HCP Terraform</h3><p>Of course you can run your production infrastructure with a local instantiation of Terraform. I do that today myself. There are, however, some differences and additional control and audit features your enterprise might benefit from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*JYQvYGG_Eu5QWYtvub7_KA.png" /><figcaption>feature comparison</figcaption></figure><h3>Arguments for HCP Terraform?</h3><p><strong>Scenario 1: Accidental prod destroy</strong></p><p>Imagine you, tired, on a second shift, running<em> terraform destroy -auto-approve</em>. In production. Suddenly your slack is blowing up.</p><p>With local Terraform, that is immediate damage. You now scramble to pull code back from GitHub and hope that terraform.state versioning in S3 is working for you…</p><p>With HCP Terraform, <em>terraform destroy</em> is not a command you can just fat finger on your own. It requires version control system integration, approvals, and is tied to an audit trail.</p><p><strong>Scenario 2: Unreviewed apply</strong></p><p>You merge to main and this triggers the CI workflow that also runs <em>terraform apply. </em>This was not reviewed, and a policy was ignored and likely an auditable security control is missed.</p><p>HCP Terraform makes plan review mandatory. It is impossible to run apply without explicit approval.</p><p><strong>Scenario 3: Cost surprises</strong></p><p>You add a new cluster that ships to production and a huge bill shows up next month on your cloud account.</p><p>HCP Terraform estimates what the costs are, before the apply. You know what the impact is, before committing.</p><p>In each of these scenarios HCP Terraform can provide additional checks and safeguards.</p><h3>HCP Terraform platform</h3><p>HCP Terraform is a SaaS platform you log into at <a href="https://app.terraform.io/">app.terraform.io</a>. There is a free tier but it has a resource cap of 500 managed resources (Resources Under Management / RUM). HCP Terraform allows for unlimited users.</p><p>Some of the core features are remote Terraform execution, VCS (version control system) integration, private module registry, single sign-on (SSO), and basic policy enforcement (Sentinel and Open Policy Agent (OPA)).</p><p>The paid tiers kick in once you exceed 500 managed resources. At that threshold you must upgrade to a paid subscription plan (such as Essentials, Standard, or Premium), which uses a pay-as-you-go pricing model based on peak hourly resource counts. The local Terraform CLI tool remains free to download and use independently</p><p>For a quick comparison (but read the documentation as this will evolve over time): The free tier includes: remote state, basic VCS integration, limited concurrency runs, and support for one (1) organization. The paid tiers add team management, sentinel policies, cost estimation and a slew of advanced APIs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*asTPk_hmUQAfEUGNZoaJog.png" /></figure><h3>Key HCP Terraform terminology:</h3><ul><li><strong>Organization: </strong>Your company/team (the top-level container)</li><li><strong>Projects: </strong>Logical groupings (optional, for org structure)</li><li><strong>Runs: </strong>Executions (plan, apply, destroy)</li><li><strong>Policies: </strong>Rules enforced via Sentinel/Open Policy Agent (OPA)</li><li><strong>Workspaces: </strong>A working directory + state file (analogous to an environment). It is important to note that these HCP Terraform workspaces are NOT analogous to terraform workspaces. Think of HCP Terraform workspace as a dedicated, cloud-hosted environment for a specific infrastructure component. It acts like an isolated Azure subscription or AWS account. Local workspaces, on the other hand, use the <strong>exact same backend configuration</strong>. If you accidentally run <em>terraform workspace select production </em>instead of <em>staging</em>, a single local command can accidentally overwrite production infrastructure. HCP Terraform eliminates this risk by treating workspaces as hard boundaries.</li></ul><p>HCP workspaces are the right way to separate dev/staging/prod.</p><pre>HCP Organization<br>├── Project: Production<br>│   ├── Workspace: prod-aws (prod infrastructure in AWS)<br>│   ├── Workspace: prod-azure (prod infrastructure in Azure)<br>│   └── Workspace: prod-backup (disaster recovery)<br>│<br>├── Project: Staging<br>│   ├── Workspace: staging-aws<br>│   └── Workspace: staging-azure<br>│<br>└── Project: Development<br>    └── Workspace: dev (shared dev environmentu</pre><h3>HCP Terraform setup: how to start in 5 steps</h3><h3>1. Create an account</h3><p>First things first: Go to <a href="https://app.terraform.io/">app.terraform.io</a>, and sign up. You can start with the free tier or if you have weighed the options already, you can dive right into the paid tiers.</p><h3>2. Create your organization</h3><p>I would name it after your company/team. After all this is where all your infrastructure will live.</p><pre>MyCompany-Engineering<br>├── Workspaces...<br>├── Teams...<br>├── Policies...</pre><h3>3. Generate an API Token</h3><p>Create a token for CLI authentication:</p><pre># Home &gt; API Tokens &gt; Create an API Token<br># Copy the token<br>export TF_CLOUD_TOKEN=&quot;eyJhbGc...&quot;<br><br>#########################<br><br># or add to .terraformrc<br>credentials &quot;app.terraform.io&quot; {<br>  token = &quot;eyJhbGc...&quot;<br>}</pre><h3>4. Create your workspace(s)</h3><p>In HCP:</p><ol><li><strong>Create Workspace</strong></li><li>Choose <strong>VCS Connection</strong> (GitHub, GitLab, etc.) or <strong>No VCS</strong></li><li>Give the workspace a meaningful name (i.e. dev-aws, prod-azure)</li><li>Configure settings</li></ol><h3>5. Configure your Terraform code</h3><p>Update your backend block:</p><pre>terraform {<br>  cloud {<br>    organization = &quot;MyCompany-Engineering&quot;<br><br>    workspaces {<br>      name = &quot;prod-aws&quot;<br>    }<br>  }<br>}</pre><p>Or, alternatively, you can also use the <em>terraform login</em> command, which updates <em>.terraformrc</em> automatically.</p><p>Once that is done, <em>terraform init</em> will connect to HCP. The stae has migrated from S3 or your blob storage to HCP! The commands <em>terraform plan</em> and <em>terraform apply </em>will now use HCP as the backend.</p><pre>$ terraform init<br>Initializing Terraform Cloud...<br>Do you want to copy existing state to the new backend?<br>(yes/no) yes</pre><h3>Working with VCS-driven workflows</h3><p>HCP really shines in taking the code that lives in your version control systems and realizing infrastructure. You may already be working with GitHub Actions or GitLab CI, but HCP offers a great alternative within the Terraform ecosystem. The entire CI/CD pipeline is implicit.</p><p>Of course, you <em>can</em> use CI/CD if you want custom logic, but VCS-driven workflows in Terraform will handle 90% of cases.</p><h3>1. Connect your Git repository</h3><ol><li>Go to workspace settings</li><li><strong>VCS Connection</strong></li><li>Authenticate GitHub/GitLab/Azure DevOps</li><li>Select the repository</li><li>Set a working directory (if it is not the root)</li></ol><p>As a result of doing this, every push will trigger a plan. Pull requests will get automatic plan comments. Merge to main triggers apply. You can rollback via <em>terraform destroy</em> run.</p><h3>Automatic plan on PR (Pull Request)</h3><pre># Feature branch<br>git checkout -b feature/add-cdn<br># Modify Terraform code<br>terraform {<br>  resource &quot;aws_cloudfront_distribution&quot; &quot;main&quot; { ... }<br>}<br>git commit -m &quot;Add CDN&quot;<br>git push origin feature/add-cdn<br><br># Create PR<br># → HCP automatically runs terraform plan<br># → Comments plan on PR</pre><p>The PR shows estimated cost, resource changes, and policy violations.</p><pre>Terraform Plan<br><br>To: Apply<br>Plans: 3 to add, 0 to change, 0 to destroy<br>Estimated Cost Change: +$450/month</pre><p>Reviewers see the plan without running <em>terraform plan</em> locally.</p><h3>Speculative plans</h3><p>Pull requests create speculative plans showing what would happen, without being in queue for apply. There are no locks acquired, these are read and preview only, and very useful to review things before a merge.</p><h3>Merge and auto-apply</h3><p>When you merge to main:</p><ol><li>Your version control system notifies HCP</li><li>HCP queues a confirmed plan</li><li>The plan runs immediately</li><li>The plan auto-applies (or could require manual confirmation, depending on settings you specify)</li><li>Apply runs on the HCP infrastructure</li><li>Run history is visible in HCP</li><li>State is updated</li></ol><h3>Remote runs: Terraform executes in HCP</h3><p>When you merge to main, the plan and apply run on HCP&#39;s infrastructure, not your laptop.</p><h3>What are the benefits?</h3><ol><li><strong>Consistent environment: </strong>Always the same OS, tool versions, network</li><li><strong>Distributed execution: </strong>HCP handles concurrency, queuing, locking</li><li><strong>No local credentials needed: </strong>HCP authenticates to AWS/Azure on your behalf</li><li><strong>Logs in HCP UI: </strong>Searchable, versioned</li><li><strong>Cost estimation: </strong>Calculated by HCP before applying</li><li><strong>Notifications: </strong>Slack, webhooks, etc.</li></ol><h3>Run states and lifecycle</h3><p>A run has the following lifecycle:</p><ol><li><strong>Queued: </strong>Waiting for previous runs to finish</li><li><strong>Planning: </strong><em>terraform plan</em><strong> </strong>running</li><li><strong>Planned: </strong>Plan complete, awaiting confirmation</li><li><strong>Confirmed: </strong>Approved via UI or auto-approved</li><li><strong>Applying: </strong><em>terraform apply</em><strong> </strong>running</li><li><strong>Applied: </strong>Complete, state updated</li></ol><p>AND you can pause between states to set up approval gates.</p><h3>Cost estimation</h3><p>Before apply, HCP calculates estimated cost changes:</p><pre>Resources to add:<br>  aws_rds_cluster_instance (3 × $0.62/hour)         +$44.64/month<br>  aws_elasticache_cluster (1 × $0.25/hour)          +$180/month<br>  aws_ebs_volume (2 × $0.10/GB, 100GB each)         +$20/month<br><br>Total estimated change: +$244.64/month</pre><p>You see the impact before committing. I<strong>f your org has an AWS Reserved Instance strategy, HCP can integrate with it for more accurate estimates.</strong></p><h3>Permissions, teams &amp; governance</h3><p>Local Terraform has no built-in permissions. You either have access to S3/Azure Storage or you do not. HCP changes that. You have a couple of different levels: Organization, team, workspace, as well as service accounts.</p><h3>Organization-level permissions/roles</h3><ul><li><strong>Owner: </strong>Full access, manage billing</li><li><strong>Admin: </strong>Manage teams, policies, projects</li><li><strong>Maintainer: </strong>Create/manage workspaces and runs</li><li><strong>Writer: </strong>Queue plans and applies</li><li><strong>Reader: </strong>View workspaces and runs</li></ul><p>Assign users to roles at the organization level.</p><h3>Team-level permissions</h3><p>Create teams and assign access to specific workspaces:</p><pre>Team: Platform Engineering<br>├── Members: alice, bob<br>├── Workspaces: prod-*, staging-*<br>├── Permissions: Admin (manage runs, variables, state)<br><br>Team: App Engineering<br>├── Members: charlie, diana<br>├── Workspaces: dev<br>├── Permissions: Write (queue runs only)<br><br><br>### in this example<br># Alice (Platform) can manage prod and staging. <br># Charlie (App) can only run terraform on dev.</pre><h3>Workspace-level permissions</h3><p>Fine-grained control:</p><pre>Workspace: prod-aws<br>├── Teams: Platform Engineering (Admin)<br>├── Teams: QA (Read-only, view runs)<br>├── Require approval before apply (explicit policy)</pre><h3>Service accounts</h3><p>For CI/CD or tools that are not people:</p><pre># Create service account in HCP UI<br># Get API token<br>export TF_API_TOKEN=&quot;...&quot;<br><br># Service account has limited permissions<br># Run Terraform via CLI or API as the service account<br>terraform apply</pre><p>Service accounts log runs to the activity audit. You know which entity changed your infrastructure.</p><h3>State management in Terraform HCP</h3><p>An important aspect of HCP is that it manages state files for you. The main security value is that state moves out of local files or S3 buckets and into a service built for protecting and tracking.</p><h3>1. Protecting state</h3><ul><li><strong>Encryption:</strong> State is encrypted at rest and in transit (TLS). HashiCorp docs mention it is using Vault-backed encryption on the service side.</li><li><strong>Automatic locking:</strong> Each workspace locks its state during a run, which prevents concurrent applies from corrupting it.</li><li><strong>Versioned history:</strong> Every change creates a new state version, so you can see what changed and recover an earlier version if needed.</li><li><strong>Remote execution:</strong> Runs happen on HCP Terraform’s infrastructure so state doesn’t need to live on developer laptops or CI runners.</li></ul><h3>2. Access control</h3><ul><li><strong>Role-based access:</strong> Teams get permissions at the workspace or project level (read, plan, write, admin), with custom roles on higher tiers.</li><li><strong>Separate state permissions:</strong> Access to state versions and state outputs can be controlled independently of the ability to run plans, which matters because reading raw state can expose secrets.</li><li><strong>Scoped state sharing:</strong> Workspaces can share outputs with specific other workspaces, rather than granting broad access to the full state.</li><li><strong>Identity features:</strong> SSO/SAML, SCIM provisioning, and MFA enforcement are available, depending on plan.</li><li><strong>Tokens:</strong> User, team, and organization tokens are scoped, so automation doesn’t need a human’s credentials.</li></ul><h3>3. Reducing secrets in the first place</h3><ul><li><strong>Dynamic provider credentials:</strong> OIDC-based workload identity lets runs get short-lived cloud credentials instead of storing long-lived keys.</li><li><strong>Sensitive variables:</strong> Variables marked sensitive are encrypted and can’t be read back through the UI or API.</li><li><strong>Vault integration:</strong> You can pull secrets at runtime instead of hardcoding them.</li></ul><h3>4. Audit and governance</h3><ul><li><strong>Run history:</strong> Each run records who or what triggered it, the VCS commit, the plan, and the apply outcome, all tied to the resulting state version.</li><li><strong>Audit trails:</strong> An API records organization events such as permission changes, workspace modifications, and state access. This is generally limited to higher-tier plans, and logs can often be forwarded to a SIEM.</li><li><strong>Policy as code:</strong> Sentinel or OPA policies run between plan and apply and can block noncompliant changes, such as public buckets or unapproved regions.</li><li><strong>Run tasks and health checks:</strong> Integrations with third-party security scanners, plus drift detection, flag infrastructure that has diverged from its declared state.</li></ul><h3>5. Caveats</h3><ul><li><strong>State still holds secrets.</strong> Marking a value sensitive hides it in output but not necessarily in the state file, so restricting who can read state is essential.</li><li><strong>Feature availability varies by plan.</strong> Audit trails, custom roles, and some policy features sit in higher tiers, and HashiCorp’s packaging has changed several times, including since IBM’s acquisition.</li><li><strong>Self-hosting is an option.</strong> Terraform Enterprise offers similar capabilities if you need to keep everything in your own environment.</li></ul><p>For current plan and compliance details check HashiCorp’s documentation.</p><p><em>This was the last post in a series of 4 on Terraform. See previous editions: </em><a href="https://medium.com/@gkinthaert/terraform-primer-1-core-concepts-58bbe981ec7c"><em>Terraform Primer 1: Core concepts</em></a><em>, </em><a href="https://medium.com/@gkinthaert/terraform-primer-2-scaling-up-ef8d62051d36"><em>Terraform Primer 2: Scaling up</em></a><em>, </em><a href="https://medium.com/@gkinthaert/terraform-primer-3-all-about-modules-632aec4ac23f"><em>Terraform primer 3: All about modules</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483dd65f73ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform primer 3: All about modules]]></title>
            <link>https://medium.com/@gkinthaert/terraform-primer-3-all-about-modules-632aec4ac23f?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/632aec4ac23f</guid>
            <category><![CDATA[aws-terraform-tutorial]]></category>
            <category><![CDATA[terraform-azure]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 23:07:50 GMT</pubDate>
            <atom:updated>2026-10-14T14:12:22.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5sge7sasZhCiVVZkou72Q.png" /></figure><h3>Modules, reusability &amp; enterprise-grade IaC</h3><p>I remember using AWS CloudFormation nested stacks which are, basically, stacks that call another stack. It is useful for breaking monster templates into manageable pieces.</p><p><strong>Terraform modules</strong> are conceptually similar, while being somewhat different at the same time. That is because these modules are just directories of code with inputs and outputs. There is no service overhead, and no API calls made to deploy a module. TL/DR it is just code organization.</p><p>After racing through some <a href="https://medium.com/@gkinthaert/terraform-primer-1-core-concepts-58bbe981ec7c">Terraform basics</a> and scaling in a <a href="https://medium.com/@gkinthaert/terraform-primer-2-scaling-up-ef8d62051d36">second installment</a>, I am now addressing the creation of Terraform modules, composing these, and using them to build enterprise infrastructure at scale.</p><h3>Code organization, NOT new resources</h3><p>A <strong>module</strong> is a directory containing Terraform configuration files.</p><pre># module inventory<br>modules/<br>├── vpc/<br>│   ├── main.tf          # VPC, subnets, route tables<br>│   ├── variables.tf     # Input variables<br>│   └── outputs.tf       # Exported values<br>├── database/<br>│   ├── main.tf          # RDS or Azure Database<br>│   ├── variables.tf<br>│   └── outputs.tf<br>└── compute/<br>    ├── main.tf          # EC2 or VMs<br>    ├── variables.tf<br>    └── outputs.tf</pre><p>Each module is self-contained. Each describes one particular segment of your infrastructure. When you call a module, you pass inputs (the variables you provide), and get outputs (the data exposed by the module). The end result is still the same, you create resources on your cloud platform of choice</p><pre># calling the vpc module and applying to a prod environment<br>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;<br><br>cidr_block  = &quot;10.0.0.0/16&quot;<br>  environment = &quot;prod&quot;<br>}<br># Access module outputs<br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  subnet_id = module.vpc.private_subnets[0]<br>}</pre><h3>Example 1: building a reusable AWS VPC module</h3><p>Let’s take a small part of the previously illustrated module library, and let’s plan to build a VPC that is deployable across dev, staging, and prod. I will use the vpc module for this…</p><h3>The basic module structure</h3><p>Yes, I could have built additional files and used .tfvars, but you can organize things in modules in a way that makes sense for your enterprise</p><pre>modules/vpc/<br>├── main.tf<br>├── variables.tf<br>└── outputs.tf</pre><h3>Files:</h3><h3>1. variables.tf</h3><pre># modules/vpc/variables.tf<br><br>variable &quot;cidr_block&quot; {<br>  description = &quot;CIDR block for VPC&quot;<br>  type        = string<br>  validation {<br>    condition     = can(cidrhost(var.cidr_block, 0))<br>    error_message = &quot;Must be a valid CIDR block.&quot;<br>  }<br>}<br>variable &quot;availability_zones&quot; {<br>  description = &quot;AZs for subnets&quot;<br>  type        = list(string)<br>  default     = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>}<br>variable &quot;enable_nat_gateway&quot; {<br>  description = &quot;Create NAT gateway for private subnets&quot;<br>  type        = bool<br>  default     = false<br>}<br>variable &quot;environment&quot; {<br>  description = &quot;Environment name (dev, staging, prod)&quot;<br>  type        = string<br>  validation {<br>    condition     = contains([&quot;dev&quot;, &quot;staging&quot;, &quot;prod&quot;], var.environment)<br>    error_message = &quot;Environment must be dev, staging, or prod.&quot;<br>  }<br>}<br>variable &quot;tags&quot; {<br>  description = &quot;Common tags&quot;<br>  type        = map(string)<br>  default     = {}<br>}</pre><h3>2. main.tf</h3><pre># modules/vpc/main.tf<br><br>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block           = var.cidr_block<br>  enable_dns_hostnames = true<br>  enable_dns_support   = true<br><br>tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;vpc-${var.environment}&quot;<br>    }<br>  )<br>}<br># Public subnets<br>resource &quot;aws_subnet&quot; &quot;public&quot; {<br>  count             = length(var.availability_zones)<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = cidrsubnet(var.cidr_block, 2, count.index)<br>  availability_zone = var.availability_zones[count.index]<br>  map_public_ip_on_launch = true<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;subnet-public-${count.index + 1}&quot;<br>      Type = &quot;Public&quot;<br>    }<br>  )<br>}<br># Private subnets<br>resource &quot;aws_subnet&quot; &quot;private&quot; {<br>  count             = length(var.availability_zones)<br>  vpc_id            = aws_vpc.main.id<br>  cidr_block        = cidrsubnet(var.cidr_block, 2, count.index + length(var.availability_zones))<br>  availability_zone = var.availability_zones[count.index]<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;subnet-private-${count.index + 1}&quot;<br>      Type = &quot;Private&quot;<br>    }<br>  )<br>}<br># Internet Gateway<br>resource &quot;aws_internet_gateway&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;igw-${var.environment}&quot;<br>    }<br>  )<br>}<br># Public route table<br>resource &quot;aws_route_table&quot; &quot;public&quot; {<br>  vpc_id = aws_vpc.main.id<br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.main.id<br>  }<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;rt-public-${var.environment}&quot;<br>    }<br>  )<br>}<br># Route table associations<br>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  count          = length(aws_subnet.public)<br>  subnet_id      = aws_subnet.public[count.index].id<br>  route_table_id = aws_route_table.public.id<br>}<br># NAT Gateway (optional)<br>resource &quot;aws_eip&quot; &quot;nat&quot; {<br>  count  = var.enable_nat_gateway ? 1 : 0<br>  domain = &quot;vpc&quot;<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;eip-nat-${var.environment}&quot;<br>    }<br>  )<br>  depends_on = [aws_internet_gateway.main]<br>}<br>resource &quot;aws_nat_gateway&quot; &quot;main&quot; {<br>  count         = var.enable_nat_gateway ? 1 : 0<br>  allocation_id = aws_eip.nat[0].id<br>  subnet_id     = aws_subnet.public[0].id<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;nat-${var.environment}&quot;<br>    }<br>  )<br>  depends_on = [aws_internet_gateway.main]<br>}<br># Private route table (with NAT if enabled)<br>resource &quot;aws_route_table&quot; &quot;private&quot; {<br>  count  = var.enable_nat_gateway ? 1 : 0<br>  vpc_id = aws_vpc.main.id<br>  route {<br>    cidr_block     = &quot;0.0.0.0/0&quot;<br>    nat_gateway_id = aws_nat_gateway.main[0].id<br>  }<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;rt-private-${var.environment}&quot;<br>    }<br>  )<br>}<br>resource &quot;aws_route_table_association&quot; &quot;private&quot; {<br>  count          = var.enable_nat_gateway ? length(aws_subnet.private) : 0<br>  subnet_id      = aws_subnet.private[count.index].id<br>  route_table_id = aws_route_table.private[0].id<br>}</pre><h3>3. outputs.tf</h3><pre># modules/vpc/outputs.tf<br>output &quot;vpc_id&quot; {<br>  description = &quot;VPC ID&quot;<br>  value       = aws_vpc.main.id<br>}<br>output &quot;vpc_cidr&quot; {<br>  description = &quot;VPC CIDR block&quot;<br>  value       = aws_vpc.main.cidr_block<br>}<br>output &quot;public_subnet_ids&quot; {<br>  description = &quot;Public subnet IDs&quot;<br>  value       = aws_subnet.public[*].id<br>}<br>output &quot;private_subnet_ids&quot; {<br>  description = &quot;Private subnet IDs&quot;<br>  value       = aws_subnet.private[*].id<br>}<br>output &quot;public_subnet_cidrs&quot; {<br>  description = &quot;Public subnet CIDR blocks&quot;<br>  value       = aws_subnet.public[*].cidr_block<br>}<br>output &quot;private_subnet_cidrs&quot; {<br>  description = &quot;Private subnet CIDR blocks&quot;<br>  value       = aws_subnet.private[*].cidr_block<br>}<br>output &quot;internet_gateway_id&quot; {<br>  description = &quot;Internet Gateway ID&quot;<br>  value       = aws_internet_gateway.main.id<br>}<br>output &quot;nat_gateway_ip&quot; {<br>  description = &quot;NAT Gateway EIP&quot;<br>  value       = var.enable_nat_gateway ? aws_eip.nat[0].public_ip : null<br>}</pre><p>What does this provide?</p><ul><li><strong>It provides input flexibility:</strong> CIDR block, Availability Zones, NAT gateway can all be toggled</li><li><strong>Sets up smart defaults:</strong> here, the NAT gateway is optional</li><li><strong>The output provides maximum visibility:</strong> Expose everything we need to see</li><li><strong>We have useful tags:</strong> These are parameterized for environment tracking</li><li><strong>Validation:</strong> Check the input constraints upfront</li></ul><h3>Using the modules…</h3><p>This will show reusability…</p><h3>A. Setting up the VPC in the DEV environment</h3><p>I have no need for a NAT Gateway here, so <em>enable_nat_gateway = false. Environment = dev. </em>I also set an appropriate CIDR block</p><pre># environments/dev/main.tf<br><br>module &quot;vpc&quot; {<br>  source = &quot;../../modules/vpc&quot;<br><br>cidr_block         = &quot;10.0.0.0/16&quot;<br>  availability_zones = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>  enable_nat_gateway = false  # Dev doesn&#39;t need NAT<br>  environment = &quot;dev&quot;<br>  tags = {<br>    Environment = &quot;dev&quot;<br>    ManagedBy   = &quot;Terraform&quot;<br>  }<br>}<br>resource &quot;aws_security_group&quot; &quot;web&quot; {<br>  name   = &quot;web-sg-dev&quot;<br>  vpc_id = module.vpc.vpc_id<br>  ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  tags = {<br>    Name = &quot;web-sg-dev&quot;<br>  }<br>}</pre><h3>B. Using that same module to set up the VPC in PROD</h3><p>I do want to use a NAT Gateway in this case, and the CIDR block will be one that fits the production environment</p><pre># environments/prod/main.tf<br><br>module &quot;vpc&quot; {<br>  source = &quot;../../modules/vpc&quot;<br><br>cidr_block         = &quot;10.100.0.0/16&quot;  # Different CIDR<br>  availability_zones = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;, &quot;us-east-1c&quot;]  # More AZs<br>  enable_nat_gateway = true  # Prod needs NAT for outbound<br>  environment = &quot;prod&quot;<br>  tags = {<br>    Environment = &quot;prod&quot;<br>    ManagedBy   = &quot;Terraform&quot;<br>    CostCenter  = &quot;Engineering&quot;<br>  }<br>}<br>resource &quot;aws_security_group&quot; &quot;web&quot; {<br>  name   = &quot;web-sg-prod&quot;<br>  vpc_id = module.vpc.vpc_id<br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  tags = {<br>    Name = &quot;web-sg-prod&quot;<br>  }<br>}</pre><h3>Example 2: Ok, now apply modules to multi-cloud…</h3><p>I want to build a module that works on both AWS and Azure clouds. One of the challenges I have with this is that AWS and Azure have different resource types…</p><p>What to do?</p><h3>Let’s try this with the database module, and set up Postgres on AWS/Azure</h3><h3>Files:</h3><h3><strong>1. variables.tf</strong></h3><pre># modules/database/variables.tf<br><br>variable &quot;cloud_provider&quot; {<br>  description = &quot;Cloud provider (aws or azure)&quot;<br>  type        = string<br>  validation {<br>    condition     = contains([&quot;aws&quot;, &quot;azure&quot;], var.cloud_provider)<br>    error_message = &quot;Must be aws or azure.&quot;<br>  }<br>}<br><br>variable &quot;engine&quot; {<br>  description = &quot;Database engine&quot;<br>  type        = string<br>  default     = &quot;postgres&quot;<br>}<br>variable &quot;engine_version&quot; {<br>  description = &quot;Engine version&quot;<br>  type        = string<br>  default     = &quot;15&quot;<br>}<br>variable &quot;instance_class&quot; {<br>  description = &quot;Instance size (db.t3.micro for AWS, B_Standard_B1s for Azure)&quot;<br>  type        = string<br>}<br>variable &quot;allocated_storage&quot; {<br>  description = &quot;Storage in GB&quot;<br>  type        = number<br>  default     = 20<br>}<br>variable &quot;database_name&quot; {<br>  description = &quot;Database name&quot;<br>  type        = string<br>}<br>variable &quot;username&quot; {<br>  description = &quot;Master username&quot;<br>  type        = string<br>}<br>variable &quot;password&quot; {<br>  description = &quot;Master password&quot;<br>  type        = string<br>  sensitive   = true<br>}<br>variable &quot;environment&quot; {<br>  description = &quot;Environment name&quot;<br>  type        = string<br>}<br>variable &quot;tags&quot; {<br>  description = &quot;Common tags&quot;<br>  type        = map(string)<br>  default     = {}<br>}<br># AWS-specific<br>variable &quot;aws_vpc_security_group_ids&quot; {<br>  description = &quot;Security groups for AWS RDS&quot;<br>  type        = list(string)<br>  default     = []<br>}<br>variable &quot;aws_db_subnet_group_name&quot; {<br>  description = &quot;DB subnet group for AWS&quot;<br>  type        = string<br>  default     = &quot;&quot;<br>}<br># Azure-specific<br>variable &quot;azure_resource_group_name&quot; {<br>  description = &quot;Resource group name for Azure&quot;<br>  type        = string<br>  default     = &quot;&quot;<br>}<br>variable &quot;azure_location&quot; {<br>  description = &quot;Azure location&quot;<br>  type        = string<br>  default     = &quot;eastus&quot;<br>}</pre><h3>2. main.tf</h3><pre># modules/database/main.tf<br><br># AWS RDS<br>resource &quot;aws_db_instance&quot; &quot;postgres&quot; {<br>  count = var.cloud_provider == &quot;aws&quot; ? 1 : 0<br>  identifier           = &quot;postgres-${var.environment}&quot;<br>  engine               = var.engine<br>  engine_version       = var.engine_version<br>  instance_class       = var.instance_class<br>  allocated_storage    = var.allocated_storage<br>  storage_type         = &quot;gp3&quot;<br>  db_name              = var.database_name<br>  username             = var.username<br>  password             = var.password<br>  skip_final_snapshot  = var.environment != &quot;prod&quot;<br>  publicly_accessible  = false<br>  vpc_security_group_ids = var.aws_vpc_security_group_ids<br>  db_subnet_group_name   = var.aws_db_subnet_group_name<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;postgres-${var.environment}&quot;<br>    }<br>  )<br>}<br># Azure Database for PostgreSQL<br>resource &quot;azurerm_postgresql_flexible_server&quot; &quot;postgres&quot; {<br>  count = var.cloud_provider == &quot;azure&quot; ? 1 : 0<br>  name                   = &quot;postgres-${var.environment}&quot;<br>  resource_group_name    = var.azure_resource_group_name<br>  location               = var.azure_location<br>  version                = var.engine_version<br>  administrator_login    = var.username<br>  administrator_password = var.password<br>  sku_name               = var.instance_class<br>  storage_mb             = var.allocated_storage * 1024<br>  <br>  backup_retention_days = var.environment == &quot;prod&quot; ? 30 : 7<br>  tags = merge(<br>    var.tags,<br>    {<br>      Name = &quot;postgres-${var.environment}&quot;<br>    }<br>  )<br>}</pre><h3>3. outputs.tf</h3><pre># modules/database/outputs.tf<br><br>output &quot;endpoint&quot; {<br>  description = &quot;Database endpoint&quot;<br>  value = var.cloud_provider == &quot;aws&quot; ? aws_db_instance.postgres[0].endpoint : azurerm_postgresql_flexible_server.postgres[0].fqdn<br>}<br><br>output &quot;port&quot; {<br>  description = &quot;Database port&quot;<br>  value       = var.cloud_provider == &quot;aws&quot; ? aws_db_instance.postgres[0].port : 5432<br>}<br>output &quot;database_name&quot; {<br>  description = &quot;Database name&quot;<br>  value       = var.database_name<br>}</pre><h3>Using this multi-cloud module…</h3><p>I applied this same module to different clouds, with different inputs. The module abstracts the differences.</p><pre># environments/prod-aws/main.tf<br>module &quot;database&quot; {<br>  source = &quot;../../modules/database&quot;<br><br>cloud_provider = &quot;aws&quot;<br>  instance_class = &quot;db.t3.small&quot;<br>  database_name  = &quot;appdb&quot;<br>  username       = &quot;postgres&quot;<br>  password       = var.db_password  # Fetch from secrets manager<br>  aws_vpc_security_group_ids = [aws_security_group.database.id]<br>  aws_db_subnet_group_name   = aws_db_subnet_group.main.name<br>  environment = &quot;prod&quot;<br>  tags = {<br>    Environment = &quot;prod&quot;<br>  }<br>}</pre><pre># environments/prod-azure/main.tf<br>module &quot;database&quot; {<br>  source = &quot;../../modules/database&quot;<br><br>cloud_provider = &quot;azure&quot;<br>  instance_class = &quot;Standard_B1ms&quot;  # Azure SKU<br>  database_name  = &quot;appdb&quot;<br>  username       = &quot;postgres&quot;<br>  password       = var.db_password<br>  azure_resource_group_name = azurerm_resource_group.main.name<br>  azure_location            = &quot;eastus&quot;<br>  environment = &quot;prod&quot;<br>  tags = {<br>    Environment = &quot;prod&quot;<br>  }<br>}</pre><h3>Module sources</h3><p>Your modules can live in different places. They can be local, live in Git/GitHub, or reside on the Terraform registry</p><h3>1. Local modules</h3><p>Modules and environments are one…</p><pre>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;  # Relative path<br>}</pre><h3>2. GitHub Modules</h3><p>Here <em>?ref=</em> nails down the version</p><pre>module &quot;vpc&quot; {<br>  source = &quot;git::https://github.com/company/terraform-modules.git//modules/vpc?ref=v2.1.0&quot;<br>}</pre><h3>3. Terraform Registry</h3><p>The Terraform Registry (<a href="http://registry.terraform.io/"><em>registry.terraform.io</em></a>) hosts community modules that have been vetted by HashiCorp.</p><pre>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;~&gt; 5.0&quot;<br>  <br>  name = &quot;my-vpc&quot;<br>  cidr = &quot;10.0.0.0/16&quot;<br>  # ... AWS VPC module arguments<br>}</pre><h3>Version constraints</h3><p>This is a repeat from the first Terraform blog, but it is equally important with modules</p><pre>version = &quot;1.0.0&quot;         # Exact version<br>version = &quot;~&gt; 1.0&quot;        # 1.0 or later, but not 2.0<br>version = &quot;&gt;= 1.0, &lt; 2.0&quot; # Range<br>version = &quot;&gt;= 1.0&quot;        # 1.0 or later</pre><p>Pin versions to avoid surprises. Lock files track exact versions used.</p><h3>Some advanced module patterns</h3><h3>1. Conditional resources with count</h3><p>Create your resources conditionally:</p><pre>resource &quot;aws_nat_gateway&quot; &quot;main&quot; {<br>  count = var.enable_nat_gateway ? 1 : 0<br>  <br>  # ...<br>}<br><br># Reference:<br>output &quot;nat_gateway_ip&quot; {<br>  value = var.enable_nat_gateway ? aws_nat_gateway.main[0].public_ip : null<br>}</pre><h3>2. Looping with for_each</h3><p>This allows you to create multiple similar resources. A great use case is creating both dev and prod VPCs from one and the same module, using just one terraform apply...</p><pre># variables.tf<br>variable &quot;environments&quot; {<br>  type = map(object({<br>    cidr  = string<br>    azs   = list(string)<br>  }))<br>}<br><br># main.tf<br>module &quot;vpc&quot; {<br>  for_each = var.environments<br>  <br>  source = &quot;./modules/vpc&quot;<br>  <br>  cidr_block         = each.value.cidr<br>  availability_zones = each.value.azs<br>  environment        = each.key<br>}<br># terraform.tfvars<br>environments = {<br>  dev = {<br>    cidr = &quot;10.0.0.0/16&quot;<br>    azs  = [&quot;us-east-1a&quot;]<br>  }<br>  prod = {<br>    cidr = &quot;10.100.0.0/16&quot;<br>    azs  = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>  }<br>}</pre><h3>3. Dynamic blocks</h3><p>Generate nested blocks programmatically. Not something I have applied in my terraform files, but worth a mention.</p><pre># variables.tf<br>variable &quot;ingress_rules&quot; {<br>  type = list(object({<br>    from_port = number<br>    to_port   = number<br>    protocol  = string<br>    cidr      = string<br>  }))<br>}<br><br># main.tf<br>resource &quot;aws_security_group&quot; &quot;main&quot; {<br>  name = &quot;dynamic-sg&quot;<br>  dynamic &quot;ingress&quot; {<br>    for_each = var.ingress_rules<br>    content {<br>      from_port   = ingress.value.from_port<br>      to_port     = ingress.value.to_port<br>      protocol    = ingress.value.protocol<br>      cidr_blocks = [ingress.value.cidr]<br>    }<br>  }<br>}<br># terraform.tfvars<br>ingress_rules = [<br>  { from_port = 80, to_port = 80, protocol = &quot;tcp&quot;, cidr = &quot;0.0.0.0/0&quot; }<br>  { from_port = 443, to_port = 443, protocol = &quot;tcp&quot;, cidr = &quot;0.0.0.0/0&quot; }<br>  { from_port = 22, to_port = 22, protocol = &quot;tcp&quot;, cidr = &quot;10.0.0.0/8&quot; }<br>]</pre><h3>Module README</h3><p>This should be self-evident, but it is often missing. Every module needs a README so everyone on the team knows what it does!</p><pre># VPC Module<br><br>Creates an AWS VPC with public/private subnets, Internet Gateway, and optional NAT Gateway.<br>## Usage<br>\`\`\`hcl<br>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;<br>  cidr_block         = &quot;10.0.0.0/16&quot;<br>  availability_zones = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>  enable_nat_gateway = true<br>  environment        = &quot;prod&quot;<br>}<br>\`\`\`<br>## Inputs<br>| Name | Type | Default | Required |<br>|------|------|---------|----------|<br>| cidr_block | string | - | yes |<br>| availability_zones | list(string) | [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;] | no |<br>| enable_nat_gateway | bool | false | no |<br>| environment | string | - | yes |<br>## Outputs<br>| Name | Description |<br>|------|-------------|<br>| vpc_id | VPC ID |<br>| public_subnet_ids | Public subnet IDs |<br>| private_subnet_ids | Private subnet IDs |</pre><h3>Finishing up: real-world scenario: A multi-environment, multi-cloud setup</h3><p>All of these use the same module code, but apply different inputs. Just imagine one (1) set of modules, five (5) environments, two (2) cloudsm and no (0) code duplication.</p><pre>my-infrastructure/<br>├── modules/<br>│   ├── vpc/<br>│   ├── database/<br>│   ├── compute/<br>│   └── security/<br>│<br>├── environments/<br>│   ├── dev-aws/<br>│   │   ├── main.tf (uses modules)<br>│   │   ├── terraform.tfvars<br>│   │   └── versions.tf<br>│   │<br>│   ├── staging-aws/<br>│   │   ├── main.tf (same modules, different vars)<br>│   │   ├── terraform.tfvars<br>│   │   └── versions.tf<br>│   │<br>│   ├── prod-aws/<br>│   │   ├── main.tf (same modules, production-grade vars)<br>│   │   ├── terraform.tfvars<br>│   │   └── versions.tf<br>│   │<br>│   ├── prod-azure/<br>│   │   ├── main.tf (same modules with azure provider)<br>│   │   ├── terraform.tfvars<br>│   │   └── versions.tf<br>│   │<br>│   └── dr-azure/<br>│       ├── main.tf (disaster recovery in Azure)<br>│       ├── terraform.tfvars<br>│       └── versions.tf<br>│<br>├── .gitignore<br>└── README.md</pre><pre># deploying DEV<br><br>cd environments/dev-aws &amp;&amp; terraform apply</pre><pre># Deploying PROD on AWS<br><br>cd environments/prod-aws &amp;&amp; terraform apply</pre><pre># Deploying PROD on Azure<br><br>cd environments/prod-azure &amp;&amp; terraform apply</pre><h3>Takeaways</h3><ol><li><strong>Modules are code organization.</strong> Simple directories with inputs and outputs.</li><li><strong>Build modules for reusability.</strong> VPC, database, compute. These are the building blocks you use everywhere in your infrastructure.</li><li><strong>Module inputs make them flexible.</strong> You can use the same module, have different inputs, and get different results.</li><li><strong>Use conditional blocks (count, for_each) to handle optionality.</strong></li><li><strong>Dynamic blocks generate nested configurations programmatically.</strong></li><li><strong>Multi-cloud modules work — abstract cloud differences behind inputs.</strong></li><li><strong>Source modules locally, from Git, or from the Terraform Registry.</strong></li><li><strong>Version modules like any code — use semantic versioning.</strong></li><li><strong>Document modules thoroughly — README, variable descriptions, output details.</strong></li><li><strong>One set of modules, multiple environments, zero duplication.</strong></li></ol><p><em>In the </em><a href="https://medium.com/@gkinthaert/terraform-primer-4-hcp-483dd65f73ee"><em>final installment in this Terraform primer series</em></a><em>, I will go over HCP Terraform. This is the enterprise platform that turns local Terraform into a governed, audited system for teams. If modules are the code, HCP Terraform is the execution engine. At least it is described as such. HCP Terraform is new to me so I am really eager to dive into this one.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632aec4ac23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform primer 2: Scaling up]]></title>
            <link>https://medium.com/@gkinthaert/terraform-primer-2-scaling-up-ef8d62051d36?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8d62051d36</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-terraform-tutorial]]></category>
            <category><![CDATA[terraform-azure]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 20:01:57 GMT</pubDate>
            <atom:updated>2026-09-22T23:08:58.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5emeGm_H6l5pAPmvESyCA.png" /></figure><h3>Managing State, organizing code &amp; collab at scale</h3><p>In yesterday’s <a href="https://medium.com/@gkinthaert/terraform-primer-1-core-concepts-58bbe981ec7c">post</a>, I covered Terraform basics and I briefly talked about that local terraform.tfstate file sitting in your working directory. It works fine when you&#39;re the only person running Terraform on your laptop.</p><p>But most of us work in teams, and then that file becomes a liability.</p><p>How do we go about moving from hobbyist to running production infrastructure as a team?</p><h3>What is the issue with keeping State local?</h3><p>Just imagine you and another team member both run terraform apply at the same time…</p><ol><li>You run terraform apply → Terraform starts creating some resources</li><li>Your colleague runs terraform apply → His Terraform starts creating resources too</li><li>Both read different cached versions of terraform.tfstate</li><li>Both create resources independently</li><li>Both write to terraform.tfstate</li><li>One person’s changes overwrite the other’s</li><li>Terraform’s view of infrastructure is now out of sync with reality, and you no longer have a single source of truth.</li></ol><p>CloudFormation solved this by making AWS the source of truth — stacks are stored in the AWS service. <strong>Terraform leaves it to you.</strong> You are responsible for centralizing state.</p><h3>Remote State is the solution</h3><p><strong>Remote state</strong> means storing terraform.tfstate on a <strong>shared backend, </strong>which should be a location everyone can access.</p><ul><li><strong>Now you again have a single source of truth: </strong>Everyone works from the same state file</li><li><strong>State locking: </strong>Only one person can modify infrastructure at a time</li><li><strong>Auditability: </strong>You can track who changed what and when</li><li><strong>Security: </strong>Credentials are stored separately, and could/should be encrypted</li><li><strong>Collaboration: </strong>Teams finally work as teams!</li></ul><h3>How It Works</h3><p>Instead of local terraform.tfstate, Terraform stores state remotely, and while you and other team members have access to the same backend, Terraform will enforce locking so simultaneous writes do not happen.</p><pre>Your laptop              Remote Backend<br>    |                         |<br>    |  terraform apply        |<br>    +--Write Plan + Apply---&gt; S3 Bucket<br>    |  &lt;--Read state file----&gt;|<br>    |                         |<br>Other person laptop           |<br>    |                         |<br>    |  terraform apply        |<br>    +--Wait for lock-------&gt; S3 Bucket<br>    |  (resource locked)      |<br>    |  &lt;--Lock released-------|<br>    |  Read new state file    |<br>    +--Write Plan + Apply----&gt;|</pre><h3>AWS scenario</h3><h3>AWS S3 Backend (with State locking)</h3><p>For AWS, you can use S3 with state locking. You create an S3 bucket to hold the state file (You can use whichever means, use CLI or the AWS Console)</p><pre># AWS CLI<br>aws s3api create-bucket \<br>  --bucket my-terraform-state \<br>  --region us-east-1<br><br># Enable versioning<br>aws s3api put-bucket-versioning \<br>  --bucket my-terraform-state \<br>  --versioning-configuration Status=Enabled<br># Block public access<br>aws s3api put-public-access-block \<br>  --bucket my-terraform-state \<br>  --public-access-block-configuration &quot;BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true&quot;<br># Enable encryption<br>aws s3api put-bucket-encryption \<br>  --bucket my-terraform-state \<br>  --server-side-encryption-configuration &#39;{<br>    &quot;Rules&quot;: [{<br>      &quot;ApplyServerSideEncryptionByDefault&quot;: {<br>        &quot;SSEAlgorithm&quot;: &quot;AES256&quot;<br>      }<br>    }]<br>  }&#39;</pre><h3>AWS: configure Terraform</h3><p>In your Terraform configuration, add a backend block:</p><pre># providers.tf<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.5.0&quot;<br>    }<br>  }<br><br>backend &quot;s3&quot; {<br>    bucket         = &quot;my-terraform-state&quot;<br>    key            = &quot;prod/terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    encrypt        = true<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><h3>AWS: migrating any existing State</h3><p>If you have local state and want to move to S3:</p><pre># Terraform will prompt to migrate<br>terraform init<br># Do you want to copy existing state to the new backend?<br># (yes/no) yes</pre><h3>AWS recap: how does this work?</h3><p>When you run terraform apply, Terraform writes a lock file to S3 with a unique ID and timestamp. Next, the plan gets executed. When that is done, the lock file is deleted</p><p>If someone else tries to apply <strong>while the lock exists</strong>, they see:</p><pre>Error: Error acquiring the state lock<br><br>Error message: resource temporarily unavailable<br>Terraform will retry this lock for 5 minutes...</pre><h3>AWS multi-environment S3 backend</h3><p>If this is your setup, say with a dev/staging/prod config, then you can use different state files for these different environments. The locking, if needed, will be independent for each environment.</p><pre># prod/providers.tf<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-state&quot;<br>    key    = &quot;prod/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>  }<br>}<br><br># staging/providers.tf<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-state&quot;<br>    key    = &quot;staging/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>  }<br>}<br># dev/providers.tf<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-state&quot;<br>    key    = &quot;dev/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>  }<br>}</pre><h3>Azure scenario</h3><h3>Azure Storage Account backend</h3><p>Working in Azure, you can use a Storage Account with blob storage. Don’t forget that a resource group, as is typical in Azure, is needed</p><pre># Create resource group<br>az group create \<br>  --name rg-terraform \<br>  --location eastus<br><br># Create storage account<br>az storage account create \<br>  --resource-group rg-terraform \<br>  --name stterraformstate \<br>  --sku Standard_LRS \<br>  --kind StorageV2<br># Create container<br>az storage container create \<br>  --name tfstate \<br>  --account-name stterraformstate<br># Enable soft delete for recovery<br>az storage blob service-properties delete-policy update \<br>  --account-name stterraformstate \<br>  --days-retained 30<br>  --enable true</pre><h3>Azure: configure Terraform</h3><pre># providers.tf<br>terraform {<br>  required_providers {<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 3.50&quot;<br>    }<br>  }<br><br>backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-terraform&quot;<br>    storage_account_name = &quot;stterraformstate&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;prod.tfstate&quot;<br>  }<br>}<br>provider &quot;azurerm&quot; {<br>  features {}<br>}</pre><h3>Azure: authentication</h3><p>Azure Storage state locking uses a managed approach. Terraform authenticates via credentials in ~/.azure/credentials (from az login), environment variables you set(AZURE_SUBSCRIPTION_ID, AZURE_CLIENT_ID, etc.), or a Managed Identity (if running on an Azure VM)</p><h3>Azure multi-environment backend</h3><p>Similar to what I set up for AWS:</p><pre># prod/providers.tf<br>terraform {<br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-terraform&quot;<br>    storage_account_name = &quot;stterraformstate&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;prod.tfstate&quot;<br>  }<br>}<br><br># staging/providers.tf<br>terraform {<br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-terraform&quot;<br>    storage_account_name = &quot;stterraformstate&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;staging.tfstate&quot;<br>  }<br>}<br><br># dev/providers.tf<br>terraform {<br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-terraform&quot;<br>    storage_account_name = &quot;stterraformstate&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;dev.tfstate&quot;<br>  }<br>}</pre><h3>Multi-cloud approach</h3><p>With Terraform, you can mix backends. Have S3 for AWS and Azure Storage for Azure, and other setups for other cloud environments. For example:</p><pre>prod-us (AWS)           → S3 + state locking<br>prod-eu (Azure)         → Azure Storage + state locking<br>staging (both clouds)   → S3 (or Azure Storage)<br>dev (both clouds)       → Local state (for developers)</pre><h3>Organizing your Terraform code</h3><p>State management is half the battle. The other half is organization — how you structure files and directories so your team can navigate them without confusion. A file naming convention helps too. Example:</p><pre>my-infrastructure/<br>├── environments/<br>│   ├── dev/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   ├── outputs.tf<br>│   │   ├── terraform.tfvars<br>│   │   └── providers.tf<br>│   ├── staging/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   ├── outputs.tf<br>│   │   ├── terraform.tfvars<br>│   │   └── providers.tf<br>│   └── prod/<br>│       ├── main.tf<br>│       ├── variables.tf<br>│       ├── outputs.tf<br>│       ├── terraform.tfvars<br>│       └── providers.tf<br>├── modules/<br>│   ├── vpc/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   └── outputs.tf<br>│   ├── database/<br>│   │   ├── main.tf<br>│   │   ├── variables.tf<br>│   │   └── outputs.tf<br>│   └── compute/<br>│       ├── main.tf<br>│       ├── variables.tf<br>│       └── outputs.tf<br>├── .gitignore<br>└── README.md</pre><p>Each environment has its own backend, variables, and state file. Common components live in modules/. (which I will cover in some detail in the next post!)</p><h3>File Naming Convention</h3><ul><li>main.tf: Primary resources</li><li>variables.tf: Input variables</li><li>outputs.tf: Output values</li><li>terraform.tfvars: Environment-specific variable values</li><li>providers.tf or versions.tf: Provider requirements and backend config</li></ul><h3><strong>Example</strong></h3><p>Development Environment. To manage prod or staging, switch directories. Each has its own backend, state file, and variables.</p><pre># environments/dev/providers.tf<br>terraform {<br>  required_version = &quot;&gt;= 1.7&quot;<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br><br>backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-state&quot;<br>    key    = &quot;dev/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><pre># environments/dev/variables.tf<br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region&quot;<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;Environment name&quot;<br>  type        = string<br>}<br>variable &quot;instance_count&quot; {<br>  description = &quot;Number of instances&quot;<br>  type        = number<br>}</pre><pre># environments/dev/main.tf<br>module &quot;vpc&quot; {<br>  source = &quot;../../modules/vpc&quot;<br><br>cidr_block  = &quot;10.0.0.0/16&quot;<br>  environment = var.environment<br>}<br>module &quot;compute&quot; {<br>  source = &quot;../../modules/compute&quot;<br>  vpc_id             = module.vpc.vpc_id<br>  instance_count     = var.instance_count<br>  environment        = var.environment<br>  instance_type      = &quot;t3.micro&quot;  # Dev uses cheaper instances<br>}</pre><pre># environments/dev/terraform.tfvars<br>aws_region    = &quot;us-east-1&quot;<br>environment   = &quot;dev&quot;<br>instance_count = 1</pre><pre># environments/dev/outputs.tf<br>output &quot;vpc_id&quot; {<br>  value = module.vpc.vpc_id<br>}<br><br>output &quot;instance_ids&quot; {<br>  value = module.compute.instance_ids<br>}</pre><p>And you would manage and build your infrastructure with the following Terraform commands:</p><pre>cd environments/dev<br>terraform init<br>terraform plan<br>terraform apply</pre><h3>Variables and configuration management</h3><p>Terraform variables allow different values per environment without code duplication.</p><h3>Variable precedence: high to low</h3><ol><li><strong>CLI flags: </strong>terraform apply -var=&quot;key=value&quot;</li><li><strong>Auto.tfvars files: </strong>*.auto.tfvars</li><li><strong>Tfvars files: </strong>-var-file=prod.tfvars</li><li><strong>Environment variables: </strong>TF_VAR_key=value</li><li><strong>Variable block defaults: </strong>default = &quot;value&quot;</li></ol><p>CLI flags always trump other variable types , which can be useful for CI/CD pipelines</p><pre># CI/CD pipeline<br>terraform apply \<br>  -var=&quot;environment=prod&quot; \<br>  -var=&quot;version=${CI_COMMIT_SHA}&quot;</pre><h3>Sensitive variables</h3><p>Some variables contain secrets (database passwords, API keys). You can assign a flag of sensitive = true</p><pre>variable &quot;db_password&quot; {<br>  description = &quot;Database password&quot;<br>  type        = string<br>  sensitive   = true<br>}</pre><p>Terraform masks the value in logs and UI (&lt;sensitive&gt;). Know that<strong> these are stored in state (so that is why your state file must be encrypted). </strong>Sensitive variable values are never printed in terraform output</p><p><strong>IMPORTANT: Add extra caution and treat these secrets as if your life depended on it. Store them in a secrets manager, not in code</strong></p><pre># NO NO NO NO!!!<br>variable &quot;db_password&quot; {<br>  type    = string<br>  default = &quot;supersecret123&quot;  # come on are you kidding me?<br>}</pre><pre># MUCH BETTER!!<br>variable &quot;db_password&quot; {<br>  type      = string<br>  sensitive = true<br>  # Default is omitted; pass via -var or environment variable<br>}<br># Or fetch from a secret manager<br>data &quot;aws_secretsmanager_secret_version&quot; &quot;db_password&quot; {<br>  secret_id = &quot;prod/db-password&quot;<br>}<br>variable &quot;db_password&quot; {<br>  type      = string<br>  sensitive = true<br>  default   = data.aws_secretsmanager_secret_version.db_password.secret_string<br>}</pre><h3>More complex variable types</h3><p>Beyond strings and numbers, Terraform also supports structured data</p><pre># List of strings<br>variable &quot;availability_zones&quot; {<br>  type = list(string)<br>  default = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>}<br><br># Map (key-value pairs, all values same type)<br>variable &quot;instance_types&quot; {<br>  type = map(string)<br>  default = {<br>    dev  = &quot;t3.micro&quot;<br>    prod = &quot;t3.xlarge&quot;<br>  }<br>}<br># Object (mixed types, fixed structure)<br>variable &quot;database_config&quot; {<br>  type = object({<br>    engine   = string<br>    version  = string<br>    instance = number<br>  })<br>  default = {<br>    engine   = &quot;postgres&quot;<br>    version  = &quot;15.1&quot;<br>    instance = 3<br>  }<br>}</pre><p>You can use these in your .tfvars files</p><pre># terraform.tfvars<br>availability_zones = [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;, &quot;us-east-1c&quot;]<br><br>instance_types = {<br>  dev     = &quot;t3.micro&quot;<br>  staging = &quot;t3.small&quot;<br>  prod    = &quot;t3.xlarge&quot;<br>}<br>database_config = {<br>  engine   = &quot;postgres&quot;<br>  version  = &quot;15.1&quot;<br>  instance = 5<br>}</pre><p>And then reference them throughout the rest of your HCL files, i.e. in a resource block in your main.tf file…</p><pre>resource &quot;aws_instance&quot; &quot;example&quot; {<br>  # Use map lookup<br>  instance_type = var.instance_types[var.environment]<br>  <br>  # Use object attribute<br>  # ...<br>}<br><br>resource &quot;aws_db_instance&quot; &quot;example&quot; {<br>  engine               = var.database_config.engine<br>  engine_version       = var.database_config.version<br>  allocated_storage    = var.database_config.instance<br>}</pre><h3>Outputs and cross-stack communication</h3><p>Terraform has outputs, which I suppose are akin to CloudFormation exports, which allow you to expose infrastructure data that can be applied for downstream use</p><pre># modules/vpc/outputs.tf<br>output &quot;vpc_id&quot; {<br>  description = &quot;VPC ID&quot;<br>  value       = aws_vpc.main.id<br>}<br><br>output &quot;private_subnets&quot; {<br>  description = &quot;Private subnet IDs&quot;<br>  value       = aws_subnet.private[*].id<br>}</pre><p>This can then be called from another .tf file, even in another module…</p><pre># modules/compute/main.tf<br>module &quot;vpc&quot; {<br>  source = &quot;../vpc&quot;<br>}<br><br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  subnet_id = module.vpc.private_subnets[0]<br>  # ...<br>}</pre><p>After terraform apply, query the outputs:</p><pre>$ terraform output vpc_id<br>&quot;vpc-0123456789abcdef0&quot;<br><br>$ terraform output private_subnets<br>[<br>  &quot;subnet-aabbccdd&quot;,<br>  &quot;subnet-eeffgghh&quot;<br>]</pre><h3>Version control and collaboration</h3><h3>.gitignore</h3><p>Never commit sensitive data or generated files</p><pre># .gitignore<br>terraform.tfstate*<br>.terraform/<br>.terraform.lock.hcl  # Lock file; some debate on this, but recommended<br>crash.log<br>override.tf<br>override.tf.json<br>*_override.tf<br>*_override.tf.json<br>.terraformrc<br>terraform.rc<br>.env<br>*.tfvars  # Often contains sensitive data<br><br># IDE<br>.vscode/<br>.idea/<br>*.swp</pre><h3>BUT should you commit .terraform.lock.hcl?</h3><p><strong>Yes, commit it.</strong> Lock files ensure your team uses the same provider versions. It prevents version issues.</p><pre># DO commit<br>.terraform.lock.hcl<br><br># DON&#39;T commit<br>terraform.tfstate*</pre><h3>Typical GitHub pull request workflow</h3><ol><li>Create a branch and make the changes you want</li><li>Push to GitHub</li><li>Create a pull request</li><li>Run terraform plan in CI (not terraform apply)</li><li>Review the plan in the pull request</li><li>Get approvals</li><li>Merge</li><li>The main branch triggers terraform apply in CI</li></ol><pre># .github/workflows/terraform.yml<br>name: Terraform<br>on:<br>  pull_request:<br>  push:<br>    branches: [main]<br>jobs:<br>  terraform:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      <br>      - uses: hashicorp/setup-terraform@v2<br>        with:<br>          terraform_version: 1.7.0<br>      <br>      - name: Terraform Init<br>        run: terraform -chdir=environments/prod init<br>      <br>      - name: Terraform Plan<br>        run: terraform -chdir=environments/prod plan -out=tfplan<br>      <br>      - name: Upload Plan<br>        uses: actions/upload-artifact@v3<br>        with:<br>          name: tfplan<br>          path: environments/prod/tfplan<br>      <br>      - name: Comment Plan on PR<br>        if: github.event_name == &#39;pull_request&#39;<br>        uses: actions/github-script@v6<br>        with:<br>          script: |<br>            # Parse tfplan and post summary as PR comment<br>            ...<br>      <br>      - name: Apply (main only)<br>        if: github.ref == &#39;refs/heads/main&#39;<br>        run: terraform -chdir=environments/prod apply tfplan</pre><p>What does this accomplish?</p><ul><li>All changes are reviewed before applying</li><li>CI tests every plan</li><li>The Main branch auto-applies (no manual terraform apply from your laptop needed)</li><li>The history is tracked in Git</li></ul><h3>Debugging and inspection</h3><h3>Terraform state commands</h3><p>These let you inspect state without having to read the JSON directly:</p><pre># List all resources in state<br>terraform state list<br><br># Show specific resource details<br>terraform state show aws_instance.web<br><br># Move or rename a resource (rarely needed)<br>terraform state mv aws_instance.web aws_instance.web_old<br><br># Remove a resource from state (careful!)<br>terraform state rm aws_instance.temporary</pre><h3>Terraform console</h3><p>Interactive REPL (Read-Eval-Print-Loop) for testing expressions. You launch this via the CLI and you can test code snippets. It is basically a command-line scratchpad that allows you to safely test expressions, evaluate built-in functions, and inspect your infrastructure’s current state in real time.</p><pre>$ terraform console<br>&gt; var.environment<br>&quot;prod&quot;<br><br>&gt; module.vpc.vpc_id<br>&quot;vpc-0123456789abcdef0&quot;<br>&gt; local.common_tags<br>{<br>  &quot;Environment&quot; = &quot;prod&quot;<br>  &quot;ManagedBy&quot;   = &quot;Terraform&quot;<br>}</pre><h3>Verbose logging</h3><p>You can also enable detailed logs for debugging. There are different levels of information returned: TRACE, DEBUG, INFO, WARN, ERROR</p><pre>export TF_LOG=DEBUG<br>terraform apply</pre><pre># Creates terraform.log<br>cat terraform.log | grep &quot;aws_instance&quot;</pre><h3>Importing existing infrastructure into Terraform</h3><p>If you have infrastructure created manually (via Console or CLI), you can import it into Terraform state. You can bring existing resources under IaC control (for AWS engineers: CloudFormation has ImportIntoStack to do something similar)</p><pre># Tell Terraform about an existing resource<br>terraform import aws_instance.existing i-0123456789abcdef0<br><br># Add to code<br>resource &quot;aws_instance&quot; &quot;existing&quot; {<br>  # Terraform will manage this from now on<br>}<br># terraform plan shows what Terraform thinks vs reality<br># Adjust code until plan is empty</pre><h3>Treating Dev and Prod differently?</h3><p>Why would you do that? You let your developers iterate quickly locally on their laptop, but production and team work is locked down.</p><pre>dev/                  (Local state for developers)<br>├── main.tf<br>├── variables.tf<br>├── terraform.tfvars<br>└── .gitignore</pre><pre>prod/                 (S3 backend with locking)<br>├── main.tf<br>│   backend &quot;s3&quot; {<br>│     bucket = &quot;my-terraform-state&quot;<br>│     key    = &quot;prod/terraform.tfstate&quot;<br>│   }<br>├── variables.tf<br>├── terraform.tfvars<br>└── .gitignore</pre><pre># DEV workflow<br>cd dev<br>terraform apply<br># Local state, just me tinkering</pre><pre># PROD workflow<br>cd prod<br>terraform apply<br># S3 backend, locking, team-safe<br># Probably run via CI/CD, not manually</pre><h3>Takeaways</h3><ol><li>Local state is fine for learning; remote state is mandatory for teams.</li><li>AWS S3 with native locking is simple and effective.</li><li>Azure Storage is the Azure equivalent.</li><li>Organize your code by environment with separate backends.</li><li>Use variables to parameterize configs; pass different values per environment.</li><li>Outputs expose infrastructure data for downstream consumption.</li><li>Commit lock files; never commit state files or secrets.</li><li>CI/CD pipelines run terraform plan, teams review, CI runs terraform apply.</li><li>State locking prevents concurrency corruption.</li><li>Import existing infrastructure to bring it under IaC control.</li></ol><p><em>In the </em><a href="https://medium.com/@gkinthaert/terraform-primer-3-all-about-modules-632aec4ac23f"><em>next post</em></a><em> (3) I will provide more detail on modules, which is how Terraform allows you to reuse code. Build a module once and deploy it across dev, staging, and prod without duplicating anything.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8d62051d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform primer 1: Core concepts]]></title>
            <link>https://medium.com/@gkinthaert/terraform-primer-1-core-concepts-58bbe981ec7c?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/58bbe981ec7c</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraform-azure]]></category>
            <category><![CDATA[aws-terraform-tutorial]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 01:14:22 GMT</pubDate>
            <atom:updated>2026-10-14T14:27:49.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KmlDRZu2OhXR97u7pEhPg.png" /></figure><h3>From CloudFormation/ARM to Terraform</h3><p>You might be managing infrastructure with AWS CloudFormation or Azure Resource Manager (ARM) templates, or you deal with several platforms all at once, and then you already know what Terraform does, hopefully, which means this will just be a light refresher for you.</p><h3>Cloud-agnostic vs. cloud-specific</h3><p><strong>CloudFormation</strong> is AWS’s native IaC tool. Your YAML or JSON templates describe AWS resources, and CloudFormation manages them. You think in AWS constructs such as stacks.</p><p><strong>ARM templates</strong> are Azure’s native IaC tool. You describe Azure resources in JSON and ARM manages them. You think in Azure constructs. You might be using <strong>Bicep</strong>, an abstraction layer on top of ARM templates, which consolidates resource types and API versions into single lines while removing schemas, content versions, and nested resource arrays.</p><p><strong>Terraform</strong>, on the other hand,<strong> </strong>is a cloud-agnostic provisioning tool. You write infrastructure code once, in HashiCorp Configuration Language (HCL), and Terraform abstracts away the cloud provider differences through “providers.”</p><p>Want to spin up an EC2 instance? Use the AWS provider. Want to create an Azure Virtual Machine? Use the Azure (azurerm) provider. Want both in the same configuration? Write both, and Terraform handles the orchestration.</p><pre># AWS resource<br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type = &quot;t3.micro&quot;<br>}</pre><pre># Azure resource<br>resource &quot;azurerm_virtual_machine&quot; &quot;app&quot; {<br>  name                  = &quot;app-vm&quot;<br>  location              = &quot;eastus&quot;<br>  resource_group_name   = azurerm_resource_group.main.name<br>  vm_size               = &quot;Standard_B1s&quot;<br>  # ... more config<br>}</pre><h3>Why the fuss?</h3><p>If your organization is multi-cloud, which seems to be a growing segment of enterprises, (AWS for some workloads, Azure for others, maybe GCP in the future), Terraform eliminates having to switch between three different IaC languages and workflows. You can hire cloud engineers (like myself) who know Terraform, who do not need to be specialists in CloudFormation vs ARM or Bicep.</p><p>If you’re pure AWS or pure Azure today, this might feel abstract, of course…</p><h3>Declarative, also…</h3><p>Terraform is declarative, just like CloudFormation and ARM.</p><pre># Terraform: &quot;Here&#39;s what I want&quot;<br>resource &quot;aws_security_group&quot; &quot;web&quot; {<br>  name = &quot;web-sg&quot;<br>  # ... rules ...<br>}</pre><pre># ClodFormation: &quot;Here&#39;s what I want&quot;<br>Resources:<br>  WebSecurityGroup:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: Web traffic<br>      # ... rules ...</pre><p>Both say “create a security group with these properties.” Neither says “first create a VPC, then attach a security group, then configure rules in this order.” The tools are declarative in that they figure out the order.</p><p>For comparison, an alternative, imperative approach, would be tools like Ansible or shell scripts: These want you to write “first create the VPC, then check if it exists, then create the security group” logic. You’d handle the state yourself.</p><h3>State: tracking what is in the real world</h3><p>Both CloudFormation and Terraform rely on <strong>state</strong> to track what was created.</p><p>In <strong>CloudFormation</strong>, state is implicit. You create a stack, CloudFormation stores the stack definition and resource metadata in AWS. You don’t need to think about it.</p><p>In <strong>Terraform</strong>, state is explicit. You create resources, Terraform stores state in a file (you decide whether you want to keep it local or remote in S3 or blob storage). You have to think about it, manage it, and secure it..</p><h3>Local State (ideal for development environments)</h3><p>When you <strong>first create infrastructure </strong>in Terraform, it creates a terraform.tfstate file in your working directory</p><ul><li><strong>terraform init (No state file is created):</strong> This step only downloads the required provider plugins (like AWS or Azure) and initializes the backend settings. It <strong>does not touch your actual infrastructure</strong>.</li><li><strong>terraform plan (No state file is created):</strong> This step reads your code and compares it against existing infrastructure to show you what <em>will</em> happen. If you haven&#39;t applied anything yet, no state file is created.</li><li><strong>terraform apply (State file is created):</strong> Once you approve the plan, Terraform provisions the resources. As soon as the first resource is successfully created, Terraform writes the metadata and tracking information into a new terraform.tfstate file.</li></ul><pre>$ terraform apply<br># Creates terraform.tfstate and terraform.tfstate.backup</pre><p>This file is JSON. It contains:</p><ul><li>Every resource you’ve created</li><li>Resource IDs and metadata</li><li>Attribute values (public IPs, DNS names, etc.)</li><li>Dependency tracking</li></ul><p>It’s a cache of the real world. Terraform reads this file to know what resources already exist, what has changed between your code and reality, and what order to create/update/delete resources.</p><p><strong>IMPORTANT: Do not commit this to Git.</strong> It contains secrets (database passwords, API keys).</p><pre># .gitignore<br>terraform.tfstate*<br>.terraform/</pre><p>For local development, that’s fine. In teams, you will find that everyone has a different state file, and you be able to collaborate.</p><h3>Remote State (preferred and a must on teams)</h3><p>CloudFormation solved this by storing state in AWS (S3). ARM solved it by storing state in Azure (blob storage). Terraform requires you to explicitly configure a remote backend, and you need it shared so your team can coordinate.</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;my-terraform-state&quot;<br>    key    = &quot;prod/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>  }<br>}</pre><h3>HashiCorp Configuration Language (HCL)</h3><p>HashiCorp Configuration Language (HCL) is designed to be human-readable, JSON-compatible, and simpler than YAML and most definitely JSON.</p><h3>Blocks and arguments</h3><p>HCL’s core building blocks are blocks and arguments:</p><pre>resource &quot;aws_instance&quot; &quot;example&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type = &quot;t3.micro&quot;<br><br>tags = {<br>    Name = &quot;web-server&quot;<br>  }<br>}</pre><p>Compare this to CloudFormation’s syntax and you can immediately see that HCL is more concise and somewhat easier to read:</p><pre>Resources:<br>  Example:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      ImageId: ami-0c55b159cbfafe1f0<br>      InstanceType: t3.micro<br>      Tags:<br>        - Key: Name<br>          Value: web-server</pre><h3>Nesting can be done, but use is sparingly!</h3><p>HCL supports nested blocks for complex configurations, but I am personally a proponent of keeping the blocks separate. Terraform will figure out the order of execution and dependencies, and it makes your files much less complex</p><pre>resource &quot;aws_security_group&quot; &quot;web&quot; {<br>  name = &quot;web-sg&quot;<br>ingress {<br>    from_port   = 80<br>    to_port     = 80<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>A CloudFormation’s JSON, compared:</p><pre>{<br>  &quot;Type&quot;: &quot;AWS::EC2::SecurityGroup&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;GroupDescription&quot;: &quot;Web traffic&quot;,<br>    &quot;SecurityGroupIngress&quot;: [<br>      {<br>        &quot;IpProtocol&quot;: &quot;tcp&quot;,<br>        &quot;FromPort&quot;: 80,<br>        &quot;ToPort&quot;: 80,<br>        &quot;CidrIp&quot;: &quot;0.0.0.0/0&quot;<br>      },<br>      {<br>        &quot;IpProtocol&quot;: &quot;tcp&quot;,<br>        &quot;FromPort&quot;: 443,<br>        &quot;ToPort&quot;: 443,<br>        &quot;CidrIp&quot;: &quot;0.0.0.0/0&quot;<br>      }<br>    ]<br>  }<br>}</pre><h3>String interpolation and References</h3><p>In Terraform, you reference other resources like this, very akin to using a variable reference:</p><pre>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  # ...<br>}<br><br>resource &quot;aws_security_group&quot; &quot;web&quot; {<br>  name = &quot;web-sg&quot;<br>  vpc_id = aws_instance.web.vpc_id  # Reference another resource<br>}</pre><p>In CloudFormation, you would be using !Ref or !GetAtt:</p><pre>Resources:<br>  Web:<br>    Type: AWS::EC2::Instance<br>  WebSG:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      VpcId: !GetAtt Web.VpcId</pre><h3>Providers: the glue</h3><p>A <strong>provider</strong> is a plugin that connects to an API of AWS, Azure, GCP, or anything else.</p><p>When you write resource &quot;aws_instance&quot;, the AWS provider handles:</p><ul><li>Authentication (reading your AWS credentials)</li><li>API calls to create/update/delete EC2 instances</li><li>Parsing responses and updating state</li></ul><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br><br>provider &quot;azurerm&quot; {<br>  features {}<br>  subscription_id = var.azure_subscription_id<br>}</pre><h3>Provider versioning</h3><p>Providers get updated all the time. You should pin versions to avoid unwanted issues</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;  # 5.0 or later, but not 6.0<br>    }<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 3.50&quot;<br>    }<br>  }<br>}</pre><p>When you run terraform init, Terraform downloads the specified provider versions into .terraform/providers/ and creates a lock file: .terraform.lock.hcl.</p><p>This lock file ensures everyone on your team uses the same provider versions!</p><pre># .terraform.lock.hcl<br>provider &quot;registry.terraform.io/hashicorp/aws&quot; {<br>  version     = &quot;5.10.0&quot;<br>  constraints = &quot;~&gt; 5.0&quot;<br>  hashes = [<br>    &quot;h1:...&quot;,<br>  ]<br>}</pre><p>CloudFormation doesn’t require this because it’s AWS-managed and always up to date. ARM is similar.</p><h3>The core Terraform workflow</h3><ol><li><strong>Write: </strong>Author .tf configuration files</li><li><strong>Init: </strong>Download providers and initialize the backend</li><li><strong>Plan: </strong>Preview what will change (like CloudFormation change sets)</li><li><strong>Apply: </strong>Execute the plan (like CloudFormation stack create/update)</li><li><strong>Destroy:</strong>Delete all managed resources</li></ol><p>And here are some additional useful commands:</p><ul><li><strong>terraform validate</strong>Checks whether your configuration files are syntactically valid and internally consistent. This can only be run after terraform init was run</li><li><strong>terraform fmt</strong>Automatically reformats your .tf files to follow standard Terraform canonical layout and spacing rules. This can be run as soon as you have a .tf file created</li><li><strong>terraform output</strong>Extracts and displays the values of output variables from your state file (e.g., pulling a newly created public IP address).</li></ul><h3>Step 1: Write the configuration</h3><p>Create a directory and some .tf files. While you can put everything in one (1) file with a .tf extension, there are some conventions used among cloud engineers. Common files are:</p><ul><li><strong>providers.tf</strong>: Declares which cloud providers your code relies on (like AWS, Azure, GCP, or Kubernetes) and their specific versions. It is also where you configure the backend block to store your state file remotely.</li><li><strong>main.tf</strong>: Contains the actual cloud resources you want to deploy, such as virtual machines, databases, networks, or storage buckets. In smaller projects, this might be the only file used.</li><li><strong>variables.tf</strong>: Acts like a function’s parameters, allowing you to parameterize your code. You define the variable names, types (e.g., string, number), descriptions, and default values here. It does <em>not</em> set the secret or environment-specific values; it just defines that they exist.</li><li><strong>outputs.tf</strong>: Exposes information about the infrastructure after a successful terraform apply. Common examples include database connection strings, public IP addresses, or resource IDs that other developers or automation tools might need.</li><li><strong>terraform.tfvars and .tfvars files</strong>: Unlike the other files, this is used specifically to supply concrete values (e.g., environment = &quot;production&quot; or instance_count = 3) to the variables declared in variables.tf. <em>Note: While written in HCL (HashiCorp Configuration Language), it uses the </em><em>.tfvars extension rather than </em><em>.tf.</em></li></ul><pre># providers.tf<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><pre># main.tf<br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;  # Ubuntu 22.04 LTS<br>  instance_type = &quot;t3.micro&quot;<br>  tags = {<br>    Name = &quot;my-web-server&quot;<br>  }<br>}</pre><h3>Step 2: Initialize</h3><pre>$ terraform init<br>Initializing the backend...<br>Downloading aws provider...<br>Terraform has been successfully configured!</pre><p>When you run terraform init, based on the example files above, Terraform will do the following:</p><ol><li>Read your required_providers block</li><li>Download the AWS provider (version 5.x) to .terraform/providers/</li><li>Create .terraform.lock.hcl with exact versions used</li><li>Initialize the backend (defaults to local state)</li></ol><h3>Step 3: Plan</h3><pre>$ terraform plan<br>Terraform will perform the following actions:</pre><pre>  # aws_instance.web will be created<br>  + resource &quot;aws_instance&quot; &quot;web&quot; {<br>      + ami                    = &quot;ami-0c55b159cbfafe1f0&quot;<br>      + arn                    = (known after apply)<br>      + id                     = (known after apply)<br>      + instance_type          = &quot;t3.micro&quot;<br>      + public_ip              = (known after apply)<br>      + tags                   = {<br>          + &quot;Name&quot; = &quot;my-web-server&quot;<br>        }<br>    }</pre><pre>Plan: 1 to add, 0 to change, 0 to destroy.</pre><p>This is like the CloudFormation change set, offering a preview of what will happen (without actually doing it).</p><h3>Step 4: Apply</h3><pre>$ terraform apply<br># Shows the same plan, then prompts for confirmation<br>Do you want to perform these actions?<br>Type &quot;yes&quot; to confirm.</pre><pre>yes</pre><pre>aws_instance.web: Creating...<br>aws_instance.web: Still creating... [10s elapsed]<br>aws_instance.web: Creation complete after 15s</pre><pre>Apply complete! Resources: 1 added.</pre><p>Terraform will now:</p><ol><li>Create the EC2 instance via AWS API</li><li>Store the instance ID and metadata in terraform.tfstate</li><li>Report success</li></ol><p>If you run terraform apply again, without changing code, Terraform compares your configuration to the real world (via what it sees in State), and does nothing. This is idempotency at work.</p><pre>$ terraform apply<br>No changes. Your infrastructure matches the configuration.</pre><h3>Step 5: Destroy</h3><pre>$ terraform destroy<br># Shows what will be deleted<br>aws_instance.web: Destroying...<br>aws_instance.web: Destruction complete after 5s</pre><pre>Destroy complete!</pre><p>Terraform deletes all managed resources. Compare to CloudFormation’s delete-stack.</p><h3>Variables and outputs: parameterization</h3><p>Like CloudFormation parameters and ARM template parameters, Terraform uses variables for dynamic values.</p><h3>Variables</h3><p>While not required (any .tf file will do), you can create a variables.tf file:</p><pre># variables.tf<br><br>variable &quot;instance_type&quot; {<br>  description = &quot;EC2 instance type&quot;<br>  type        = string<br>  default     = &quot;t3.micro&quot;<br>}<br><br>variable &quot;aws_region&quot; {<br>  description = &quot;AWS region&quot;<br>  type        = string<br>  default     = &quot;us-east-1&quot;<br>}<br>variable &quot;environment&quot; {<br>  description = &quot;Environment name&quot;<br>  type        = string<br>  validation {<br>    condition     = contains([&quot;dev&quot;, &quot;staging&quot;, &quot;prod&quot;], var.environment)<br>    error_message = &quot;Environment must be dev, staging, or prod.&quot;<br>  }<br>}</pre><p>Use them in your configuration:</p><pre># providers.tf<br><br>provider &quot;aws&quot; {<br>  region = var.aws_region<br>}</pre><pre># main.tf<br><br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type = var.instance_type<br>  tags = {<br>    Environment = var.environment<br>  }<br>}</pre><p>You can also pass the variable values via command line:</p><pre>terraform apply \<br>  -var=&quot;instance_type=t3.small&quot; \<br>  -var=&quot;environment=prod&quot;</pre><p>Or, use a .tfvars file (which are like CloudFormation parameter files):</p><pre># terraform.tfvars<br>instance_type = &quot;t3.small&quot;<br>aws_region    = &quot;us-west-2&quot;<br>environment   = &quot;prod&quot;</pre><pre>terraform apply<br># Automatically reads terraform.tfvars</pre><h3>Outputs</h3><p>Like CloudFormation outputs, Terraform outputs expose infrastructure data:</p><pre># outputs.tf<br><br>output &quot;instance_id&quot; {<br>  description = &quot;EC2 instance ID&quot;<br>  value       = aws_instance.web.id<br>}<br><br>output &quot;public_ip&quot; {<br>  description = &quot;Public IP address&quot;<br>  value       = aws_instance.web.public_ip<br>}</pre><p>After you run terraform apply:</p><pre>$ terraform output<br>instance_id = &quot;i-0123456789abcdef0&quot;<br>public_ip = &quot;203.0.113.42&quot;</pre><p>You can query specific outputs:</p><pre>$ terraform output instance_id<br>&quot;i-0123456789abcdef0&quot;</pre><p>This is identical to CloudFormation outputs conceptually: exposing values for downstream consumption.</p><h3>Multi-cloud example</h3><p>Let’s put it together with a multi-cloud example with AWS and Azure</p><pre># providers.tf<br><br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 3.50&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br>provider &quot;azurerm&quot; {<br>  features {}<br>  subscription_id = var.azure_subscription_id<br>}</pre><pre># main.tf<br><br># AWS: EC2 instance<br>resource &quot;aws_instance&quot; &quot;web_aws&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;  # Ubuntu<br>  instance_type = var.instance_type<br>  <br>  tags = {<br>    Name = &quot;web-server-aws&quot;<br>  }<br>}<br># Azure: Virtual Machine<br>resource &quot;azurerm_resource_group&quot; &quot;main&quot; {<br>  name     = &quot;rg-web-servers&quot;<br>  location = &quot;eastus&quot;<br>}<br>resource &quot;azurerm_virtual_machine&quot; &quot;web_azure&quot; {<br>  name                  = &quot;web-vm-azure&quot;<br>  location              = azurerm_resource_group.main.location<br>  resource_group_name   = azurerm_resource_group.main.name<br>  vm_size               = &quot;Standard_B1s&quot;<br>  # ... more Azure config<br>}</pre><p><strong>One code repo</strong>, one workflow (terraform plan → terraform apply), <strong>two cloud infrastructures</strong>.</p><h3>Takeaways</h3><ol><li><strong>Terraform is cloud-agnostic: </strong>You write it once, and then deploy to AWS, Azure, GCP, or any cloud.</li><li><strong>HashiCorp Configuration Language (HCL) is simpler than JSON/YAML.</strong></li><li><strong>State is explicit:</strong> You manage it. Keep it secure and back it up.</li><li><strong>The workflow is straightforward: </strong>Init → Plan → Apply → Destroy</li><li><strong>Providers do a lot of the work: </strong>You write declarative code, and the providers handle the details.</li><li><strong>Multi-cloud can be achieved with 1 repo: </strong>Take care of<strong> </strong>multiple clouds, in one workflow.</li></ol><p><em>In </em><a href="https://medium.com/@gkinthaert/terraform-primer-2-scaling-up-ef8d62051d36"><em>tomorrow’s follow up post</em></a><em>, I will look at state management, team collaboration, and organizing Terraform for production environments. I will have a more detailed look at moving from local state to a remote backend like S3 or Azure Storage.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58bbe981ec7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Storage for AWS Engineers: Services, redundancy, and region pairs]]></title>
            <link>https://medium.com/@gkinthaert/azure-storage-for-aws-engineers-services-redundancy-and-region-pairs-0fd6f12e8194?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd6f12e8194</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[aws-storage]]></category>
            <category><![CDATA[azure-storage]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 02:11:19 GMT</pubDate>
            <atom:updated>2026-09-01T02:24:00.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx916tHsARWDDQb1YqNg0w.png" /></figure><p>When it comes to cloud I have a good amount of experience with AWS, but I was curious about those other cloud players, especially Azure. I am also seeing a considerable number of job descriptions that require multi-cloud exposure/experience, and Azure seems to be a popular platform with larger companies, government and municipalities.</p><p>No big deal, right? The console is pretty self explanatory after navigating it for a few days, and there are many like for like services, seemingly just branded differently. On top of that, I use Terraform, so it should just be a case of switching out a provider in my versions.tf file.</p><p>Not so fast! Azure is architected differently, and that affects how you build your infrastructure and what you put in your files. There are things like subscriptions, resource groups, and other subtle and less subtle differences, but I found <strong>Azure Storage </strong>to be the aspect that<strong> </strong>SEEMS familiar, but is surprisingly different at its core. I am going to spend some time unraveling some of that.</p><h3>The familiar…</h3><p>At a high level, the concepts are the same: You have object/file/block storage, queues, NOSQL storage. They both have regions, availability zones, replication, and disaster recovery.</p><h3>Then again…</h3><p>Azure architected these things a bit differently than AWS.</p><p>One of the biggest examples is <strong>storage redundancy</strong>. In Azure, you will see redundancy options such as <strong>LRS, ZRS, GRS, RA-GRS, GZRS, and RA-GZRS</strong> when configuring a Storage Account (and yes, you need to set up a Storage Account in Azure before you can even do anything). These options do not map directly to AWS S3 storage classes or replication configurations.</p><h3>Part 1: Azure Storage Services</h3><h4>Start with the service</h4><p><strong>Ask what kind of data is being stored?</strong></p><p>Azure’s primary storage services include <strong>Blob Storage</strong>, <strong>Azure Files</strong>, <strong>Managed Disks</strong>, <strong>Queue Storage</strong>, and <strong>Table Storage</strong>. Additional specialized services such as Azure NetApp Files, Azure Elastic SAN, Azure Container Storage, and Azure Managed Lustre, are also options.</p><p>These are NOT identical products with a different brand label, but rather architectural equivalents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*exesVe75IVhW-Pa3jgmMUA.png" /><figcaption>services comparison</figcaption></figure><h3>Azure Blob Storage ≈ Amazon S3</h3><p>Blob Storage is Azure’s <strong>object storage service</strong> and is designed for massive amounts of unstructured data (images, videos, documents, backups and logs, app data, data lake workloads, etc.</p><pre>Azure Storage Account                  <br>    │<br>    └── Blob Container    <br>            │<br>            ├── image1.jpg<br>            ├── report.pdf<br>            ├── video.mp4<br>            └── data.json<br><br>S3<br> │<br> └── Bucket<br>       │<br>       ├── image1.jpg<br>       ├── report.pdf<br>       ├── video.mp4<br>       └── data.json</pre><p>There are differences in terminology and capabilities, but conceptually Azure Blob Storage is equivalent to Amazon S3.</p><h4>One VERY important difference</h4><p>Azure Blob Storage sits within an <strong>Azure Storage Account</strong>. This is worth noting because many configuration decisions (including redundancy) are made at the Storage Account level.</p><pre>Storage Account<br>│<br>├── Blob containers<br>├── File shares<br>├── Queues<br>└── Tables</pre><p>That becomes especially important when we get to LRS, ZRS, and GRS.</p><h3>Azure Files ≈ Amazon EFS / FSx</h3><p><strong>Azure Files</strong> provides managed file shares that can be accessed using protocols such as SMB, NFS, and REST API. The shares can be mounted from Azure VMs, on-premises systems, and other environments.</p><pre>Azure Files<br>              │<br>   ┌──────────┼──────────┐<br>   │          │          │<br>VM #1       VM #2      VM #3<br>   │          │          │<br>   └──────────┼──────────┘<br>              │<br>         Shared Files</pre><p>The comparison has a few avenues, depending on what the goal is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*UelGLTM4abZPBFBBfYzINg.png" /><figcaption>Azure and AWS options for different file system requirements</figcaption></figure><h3>Azure Managed Disks ≈ Amazon EBS</h3><p>If you have an Azure Virtual Machine and need a persistent disk, you’re looking at <strong>Azure Managed Disks</strong>. AWS engineers will immediately think Amazon EBS, and the basic architecture is very similar:</p><pre>Azure VM                    EC2 Instance<br>   │                            │<br>   ├── OS Disk                  ├── Root EBS Volume<br>   ├── Data Disk                ├── Data EBS Volume<br>   └── Data Disk                └── Data EBS Volume</pre><p>Azure Managed Disks are block-level storage volumes designed for Azure VMs. Microsoft manages the underlying storage infrastructure.</p><p><strong>Amazon EC2 + EBS → Azure VM + Managed Disk</strong></p><h3>Azure Queue Storage ≈ Amazon SQS</h3><p>Azure Queue Storage is designed to allow application components to communicate asynchronously. For example, you have an app that needs to generate thumbnails whenever users upload images. You can introduce a queue as such:</p><pre>User<br> │<br> ▼<br>Web Application<br> │<br> ├── Store image<br> └── Send message<br>        │<br>        ▼<br>   Azure Queue<br>        │<br>        ▼<br>  Worker / Function<br>        │<br>        ▼<br> Generate thumbnail</pre><p>The AWS equivalent is: <strong>Amazon SQS</strong></p><p>Azure Queue Storage is useful for straightforward asynchronous messaging. Microsoft also has Azure Service Bus, which provides richer enterprise messaging capabilities.</p><ul><li><strong>Azure Queue Storage ≈ SQS</strong></li><li><strong>Azure Service Bus ≈ a more feature-rich messaging platform</strong></li></ul><h3>Azure Table Storage ≈ Amazon DynamoDB</h3><p>Azure Table Storage provides a schema-less NoSQL key/attribute store, which can hold data like user information, device info, metadata, application states, simple structured datasets, etc.</p><p><strong>Azure Table Storage ≈ Amazon DynamoDB</strong></p><p>There is also <strong>Azure Cosmos DB for Table</strong>, providing capabilities such as global distribution and throughput optimization.</p><pre>Simple NoSQL<br>     │<br>     ▼<br>Azure Table Storage<br>     │<br>     ▼<br>More advanced / globally distributed<br>     │<br>     ▼<br>Azure Cosmos DB for Table</pre><h3>Recap of the Azure Storage model</h3><p>As an AWS engineer, you can consider the following Azure service mapping:</p><pre>Azure Storage<br>                        │<br>      ┌─────────────────┼─────────────────┐<br>      │                 │                 │<br>   Objects             Files             Disks<br>      │                 │                 │<br>    Blob               Files       Managed Disks<br>      │                 │                 │<br>      ▼                 ▼                 ▼<br>     S3               EFS/FSx            EBS</pre><pre>      ┌─────────────────┴─────────────────┐<br>      │                                   │<br>   Messaging                           NoSQL<br>      │                                   │<br>    Queue                               Table<br>      │                                   │<br>      ▼                                   ▼<br>     SQS                              DynamoDB</pre><h3>Part 2: Azure Storage Redundancy</h3><h3>LRS, ZRS, GRS, GZRS, etc. What do these actually mean?</h3><p>When setting up the Azure Storage Account, you will notice the <strong>Redundancy</strong> setting.</p><p>You can choose options such as LRS, ZRS, GRS, RA-GRS, GZRS, and RA-GZRS</p><p>These are <strong>not six different storage services</strong>. These are different ways of determining: <strong>Where does Azure keep copies of the data?</strong></p><p>The best way to approach this is to increase the scope of the failure you are planning for…</p><h3>LRS = Locally Redundant Storage</h3><p>This is the simplest and least expensive redundancy option. Multiple copies are synchronously maintained within the local infrastructure.</p><p>LRS protects against things such as drive failures, server failures, and rack-level failures</p><p>Note that it is NOT designed to protect you from a larger datacenter-level disaster.</p><pre>Azure Region<br>     │<br>     └── Local Storage Infrastructure<br>             │<br>             ├── Copy 1<br>             ├── Copy 2<br>             └── Copy 3</pre><h4>AWS comparison</h4><p>Azure LRS has no direct equivalent in standard S3 because S3’s standard regional architecture already provides multi-AZ redundancy.</p><h3>ZRS = Zone-Redundant Storage</h3><p>Azure synchronously replicates the data across three availability zones in the primary region.</p><p>The important distinction is:</p><ul><li><strong>LRS protects against local infrastructure failures.</strong></li><li><strong>ZRS protects against an Availability Zone failure.</strong></li></ul><pre>Azure Region<br>                │<br>    ┌───────────┼───────────┐<br>    │           │           │<br>  Zone 1      Zone 2      Zone 3<br>    │           │           │<br>  Copy        Copy        Copy</pre><h4>AWS comparison</h4><p>Azure ZRS is conceptually similar to the normal architecture of Amazon S3 Standard, which stores objects redundantly across multiple Availability Zones.</p><p><strong>ZRS is an explicit Azure redundancy configuration.</strong> AWS S3 Standard’s multi-AZ architecture is essentially built into the service.</p><h3>GRS = Geo-Redundant Storage</h3><p>GRS replicates your data <strong><em>asynchronously</em></strong> to a <strong>secondary Azure region</strong>.</p><pre>PRIMARY REGION<br>                   │<br>                   ▼<br>                  LRS<br>               ┌───┼───┐<br>               │   │   │<br>             Copy Copy Copy<br>                   │<br>                   │<br>              Asynchronous<br>               replication<br>                   │<br>                   ▼<br>            SECONDARY REGION<br>                   │<br>                  LRS<br>               ┌───┼───┐<br>               │   │   │<br>             Copy Copy Copy</pre><p><strong>IMPORTANT: Asynchronous is the key term here!</strong></p><p>This secondary copy may lag behind the primary. Geo-redundancy is not the same thing as zero-data-loss replication.</p><h4>AWS comparison</h4><p>AWS has<strong> S3 Cross-Region Replication (CRR): </strong>AWS CRR copies objects from an S3 bucket in one region to another S3 bucket in a different region.</p><p>But there is a very important architectural difference: The secondary bucket is picked by Azure, you do not control the destination. AWS gives you control over the destination bucket an replication configuration</p><pre>Azure:<br><br>Storage Account<br>      │<br>      └── GRS<br>           │<br>           └── Azure-managed secondary</pre><pre>AWS:<br><br>S3 Bucket A<br>     │<br>     │ CRR<br>     ▼<br>S3 Bucket B</pre><h3>RA-GRS = Read-Access Geo-Redundant Storage</h3><p>The application can access the secondary endpoint for reads even though the secondary isn’t the active primary.</p><p>This can be valuable when you have applications that need to continue serving read operations during a primary-region outage.</p><pre>Start with GRS and add Read access:<br><br>Primary<br>   │<br>   │ replication<br>   ▼<br>Secondary<br>   │<br>   └── READ ACCESS</pre><h4>AWS equivalent</h4><p>There is no single AWS setting, and you would have to construct this architecture using:</p><pre>S3 Bucket - Region A<br>        │<br>        │ CRR<br>        ▼<br>S3 Bucket - Region B<br>        │<br>        └── Application reads</pre><p>The application is responsible for understanding which bucket it should read from.</p><h3>GZRS = Geo-Zone-Redundant Storage</h3><p>Azure combines <strong>ZRS + GRS: Zone redundancy in the primary region + geo-replication to a secondary region</strong></p><pre>PRIMARY REGION<br>         ┌─────────┼─────────┐<br>         │         │         │<br>       Zone 1    Zone 2    Zone 3<br>         │         │         │<br>       Copy      Copy      Copy<br>         └─────────┼─────────┘<br>                   │<br>                   │<br>              Asynchronous<br>               replication<br>                   │<br>                   ▼<br>            SECONDARY REGION<br>                   │<br>                  LRS<br>              ┌────┼────┐<br>              │    │    │<br>            Copy Copy Copy</pre><p>This gives you protection from local infrastructure failures, availability zone failures, as well as regional failures</p><h3><strong>RA-GZRS = Read-Access Geo-Zone-Redundant Storage</strong></h3><p><strong>This is the most resilient option</strong></p><pre>PRIMARY REGION<br>    ┌────────┬────────┬────────┐<br>    │        │        │        │<br>   AZ-1     AZ-2     AZ-3<br>    │        │        │<br>    └────────┴────────┘<br>             │<br>             │<br>         Replication<br>             │<br>             ▼<br>      SECONDARY REGION<br>             │<br>             │<br>        READ ACCESS</pre><p>You get it all!</p><ul><li>Zone redundancy</li><li>Geographic redundancy</li><li>Secondary-region read access</li></ul><p><strong>RA-GZRS is recommended when maximum availability and durability are required.</strong></p><h3>Azure Redundancy: Summary</h3><pre>                     LRS<br>                      │<br>              &quot;Keep it local&quot;<br>                      │<br>                      ▼<br>                     ZRS<br>                      │<br>               &quot;Across AZs&quot;<br>                      │<br>                      ▼<br>                     GRS<br>                      │<br>             &quot;Across regions&quot;<br>                      │<br>                      ▼<br>                   RA-GRS<br>                      │<br>         &quot;Read from secondary&quot;<br>                      │<br>                      ▼<br>                    GZRS<br>                      │<br>        &quot;AZ + geographic redundancy&quot;<br>                      │<br>                      ▼<br>                  RA-GZRS<br>                      │<br>     &quot;AZ + geo + secondary reads&quot;</pre><h3>Comparison Table:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*XLdCh1N_mSRPvpRSWAKRiw.png" /><figcaption>Redundancy options comparison</figcaption></figure><p><strong>IMPORTANT: GRS/GZRS don’t mean synchronous, zero-loss replication between regions.</strong> Geo-replication is asynchronous, so your disaster-recovery design still needs to consider RPO and failover behavior.</p><h3>Part 3: Azure Region Pairs</h3><p>As an AWS engineer, you are blessed with some flexibility in terms of which regions you want to deploy to. We are accustomed to thinking: “I’m deploying in us-east-1, and if I want another region, I’ll select us-west-2.”</p><p>Azure has a similar concept of regions, but the difference is that it also introduces <strong>region pairs</strong>.</p><h3>What Is an Azure Region Pair?</h3><p>Microsoft designates certain Azure regions as pairs.</p><pre>West US<br>   │<br>   │ paired with<br>   ▼<br>East US</pre><pre>West Europe<br>      │<br>      │ paired with<br>      ▼<br>North Europe</pre><pre>UK South<br>    │<br>    │ paired with<br>    ▼<br>UK West</pre><p><strong>You do not choose the pair yourself. </strong>Microsoft maintains the region-pair relationship for supported paired regions.</p><h3>Why Does Azure Have Region Pairs?</h3><p>Region pairs provide several platform-level benefits:</p><p><strong>1. Recovery sequencing: </strong>During a very large-scale outage, Azure can prioritize recovery between the regions in a pair.</p><p><strong>2. Staggered updates: </strong>Microsoft strives to stagger planned platform updates across paired regions to reduce the chance of a problematic update affecting both regions simultaneously.</p><p><strong>3. Data residency considerations: </strong>Many paired regions are within the same geographic area, which can help with data-residency requirements.</p><p><strong>A region pair is not simply “two regions that I selected for disaster recovery. </strong>Microsoft defines the relationship that certain Azure services use.</p><h3>GRS and Region Pairs</h3><p>For storage accounts using GRS, Azure replicates data asynchronously to the <strong>paired region</strong> for supported paired-region scenarios. The secondary region is determined by Azure’s region-pairing model where supported.</p><pre>Primary: West US<br>   │<br>   │ GRS<br>   ▼<br>Secondary: East US</pre><p>You don’t configure: “West US → my custom GRS destination” in the same way you would configure an AWS S3 CRR destination bucket.</p><h3>Important modern Azure nuance</h3><p><strong>Not every Azure region has a paired region. </strong>Azure has expanded with newer regions that may be <strong>nonpaired</strong>.</p><p>Many newer regions use Availability Zones as their primary resiliency mechanism, and many Azure services can support geo-redundancy without relying on region pairs.</p><pre>Azure Regions<br>               │<br>     ┌─────────┴─────────┐<br>     │                   │<br>  Paired              Nonpaired<br>  Regions              Regions<br>     │                   │<br>     ▼                   ▼<br>Some services use      Use service-specific<br>predefined pairs       multiregion strategies</pre><p>Microsoft explicitly notes that many services support geo-redundancy across nonpaired regions, while other services require you to design your own multi-region approach.</p><p>NOTE: The Azure documentation has evolved considerably around region pairs and nonpaired regions, so I’d recommend checking the latest status and guidance.</p><h3>Region Pair ≠ Automatic Disaster Recovery</h3><p>Deploying resources into paired regions <strong>does not automatically make your application highly available. </strong>You still need to design the application for multi-region operation.</p><p>Microsoft explicitly states that simply deploying resources into a region pair doesn’t automatically provide high availability or disaster recovery.</p><p>A real multi-region architecture could be:</p><pre>Global Users<br>                   │<br>                   ▼<br>             Traffic Manager<br>              /          \<br>             /            \<br>            ▼              ▼<br>        West US           East US<br>           │                 │<br>        Web/App            Web/App<br>           │                 │<br>        Database          Database<br>           │                 │<br>           └───────┬─────────┘<br>                   │<br>             Data replication</pre><p>The region pair provides useful platform characteristics, but <strong>you still own the architecture</strong>.</p><h3>Part 4: Redundancy vs Access Tier</h3><p><strong>Redundancy answers: WHERE are copies of my data stored?</strong></p><p>Azure Blob Storage has <strong>access tiers, which addresses HOW FREQUENTLY I access my data</strong>:</p><ul><li>Hot</li><li>Cool</li><li>Cold</li><li>Archive</li></ul><pre>Azure Blob Storage<br>                 │<br>     ┌───────────┴───────────┐<br>     │                       │<br>Redundancy               Access Tier<br>     │                       │<br>   GZRS                    Cool</pre><p>AWS has a similar separation between replication architecture and S3 storage classes:</p><pre>S3<br> │<br> ├── Standard<br> ├── Intelligent-Tiering<br> ├── Standard-IA<br> ├── Glacier<br> └── Deep Archive</pre><h3>Part 5: Replication Is Not Backup</h3><p>Imagine this architecture:</p><pre>Primary<br>            │<br>            │ replication<br>            ▼<br>         Secondary</pre><p>Now someone accidentally deletes the data:</p><pre>DELETE<br>            │<br>    ┌───────┴───────┐<br>    ▼               ▼<br> Primary         Secondary<br>  DELETE           DELETE</pre><p>Replication protects you against certain <strong>infrastructure failures, </strong>but it doesn’t automatically protect you against: Accidental or malicious deletion, bugs, data corruption, faulty deployments, etc.</p><p>Azure therefore provides additional capabilities such as soft delete, versioning, snapshots and immutable storage, while AWS provides capabilities such as S3 Versioning and Object Lock.</p><h3>Closing thoughts</h3><p>Coming from AWS, it is easy to approach another cloud environment such as Azure with what you already know. The fact that there are many similar services may actually be a pitfall. Take a step back and take a look at where the concepts and architectural underpinnings differ.</p><p>I just went a bit deeper in one area, storage. Undoubtedly, there will be other areas that need some scrutiny. Don’t try to translate Azure terminology directly into AWS terminology. Translate the underlying architecture instead.</p><p>Once you understand <strong>what problem each piece is solving</strong>, moving between AWS and Azure becomes much easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd6f12e8194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AWS Logs are already in S3. But they belong in Splunk too!]]></title>
            <link>https://medium.com/@gkinthaert/your-aws-logs-are-already-in-s3-but-they-belong-in-splunk-too-9770fd8cf5ee?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9770fd8cf5ee</guid>
            <category><![CDATA[aws-cloudtrail]]></category>
            <category><![CDATA[aws-app-log]]></category>
            <category><![CDATA[aws-vpc-flow-logs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[splunk]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 20:32:10 GMT</pubDate>
            <atom:updated>2026-08-14T05:29:45.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejCr3i0OmMVEtUumagBeOA.png" /></figure><p>If you’re running any measure of infrastructure in AWS, you have an enormous amount of log data (CloudTrail, VPC Flow Logs, application logs) accumulating in S3 buckets.</p><p>AWS gives you native tools to look at these: CloudWatch Logs Insights, GuardDuty, Security Hub, Athena queries against S3. They work well.</p><p>But you might also have on-prem servers still, other identity providers, firewalls, or even other cloud platforms… That means you have your AWS logs sitting in a silo, disconnected from the rest of your security and operational picture.</p><p>And, perhaps, or likely, you are already running some SIEM tool, for the sake of argument it is Splunk (Enterprise or Cloud). So, why not pull that S3-archived AWS log data into Splunk, and get a full picture of your infrastructure…</p><p>I want to bring up some use cases that make it worth the (fairly minimal) effort, and show how to set up intake for the three AWS log sources that matter most: VPC Flow Logs (already discussed at length in a previous post), CloudTrail, and application logs.</p><h3>Why bother, since AWS already has tools</h3><p>That is more than a fair question. CloudWatch and its companion services are perfectly capable of monitoring AWS<strong> in isolation</strong>. The case for Splunk is not detracting from these AWS tools, far from it, but AWS tools can only help you with what is in AWS, and if you want context about all of your infrastructure, you will be left shortchanged or having to use a whole suite of other tools to address the individual infrastructure components…</p><p>Here’s what you gain by centralizing in Splunk:</p><ul><li><strong>You can finally connect the dots across your whole environment. </strong>GuardDuty tells you something suspicious happened in AWS. It can’t tell you that the same IAM credential was used five minutes later in a suspicious VPN login from your on-prem Okta logs. Splunk can do such a cross-source correlation: CloudTrail plus identity provider plus network logs plus endpoint data. This is the main reason security teams centralize logging in the first place.</li><li><strong>Retention and compliance get easier, not harder.</strong> CloudWatch Logs retention costs climb fast, and querying old data through CloudWatch Insights is limited. Since your logs are already landing in S3, you can index the hot, frequently-queried data in Splunk while cold data stays cheaply in S3 — or use Splunk SmartStore to keep storage costs down while everything stays searchable for audits like PCI, SOC 2, or HIPAA. Splunks own bucket concept uses the age of the ingested data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*kvLw2b87fDcGYlcN6QMidg.png" /><figcaption>Splunk bucket hierarchy</figcaption></figure><ul><li><strong>One query language, one set of dashboards, one team that isn’t context-switching.</strong> If you’re not 100% in AWS — and almost nobody is — having infrastructure, application, and cloud logs in a single search interface means your analysts aren’t hopping between CloudWatch Insights, Azure Monitor, and a slew of other consoles depending on which system messed up today.</li><li><strong>Dashboards and reporting that actually serve the business.</strong> Splunk’s dashboarding and SPL are more flexible than CloudWatch’s own dashboards, especially when the audience is a stakeholder who wants to see cost anomalies mapped against deployment timing, or error rates broken out by customer tier.</li><li><strong>Real analytics, not just log storage.</strong> With the Machine Learning Toolkit or ITSI, Splunk can do anomaly detection, predictive alerting, and service-health scoring in ways that go beyond what CloudWatch Anomaly Detection offers out of the box.</li></ul><h3>The use cases that make this worth your while</h3><p>Once the pipeline is built, here’s what it actually unlocks:</p><ul><li><strong>Security investigations that span your whole environment</strong> — not just AWS. Correlation searches that join CloudTrail, VPC Flow Logs, and non-AWS identity/network data catch things no single-source tool can.</li><li><strong>Long-term, cost-effective retention</strong> for audit and compliance needs, with the flexibility to keep only what’s operationally valuable hot in Splunk.</li><li><strong>Network forensics</strong> — spotting reconnaissance, unusual outbound data volume, or policy violations in VPC Flow Logs, then immediately pivoting to see what CloudTrail says about who changed the security group that let it happen.</li><li><strong>Privilege escalation and insider threat detection</strong> via CloudTrail — IAM changes, root account usage, logins without MFA, API calls from unexpected geographies.</li><li><strong>Application health and business KPIs</strong> surfaced from the same platform your security team already lives in, so engineering and security aren’t maintaining two separate monitoring stacks.</li></ul><p>The common thread: none of these are things CloudWatch can’t technically do. They’re things Splunk does<strong> <em>better</em></strong>, because it isn’t limited to seeing only AWS.</p><h3>How to set it up</h3><p>What is the pattern to have in place? <strong>S3 event notifications feeding an SQS queue, which Splunk polls via the Splunk Add-on for AWS.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Dsj6YuaVweUiPkfAfw_oHA.png" /></figure><p><em>NOTE: Don’t use plain S3 polling inputs, as these re-list the entire bucket repeatedly and don’t scale. The SQS-based approach is event-driven: the moment a new log object lands in S3, a notification goes to a dedicated SQS queue, and Splunk picks it up from there.</em></p><h3>A. Ingesting VPC Flow Logs</h3><p>VPC Flow Logs are the highest-volume and trickiest of the three sources to get right, but don’t skip thesse as they are also one of the most valuable for security use cases.</p><h3>AWS configuration</h3><p><strong>Choose a custom log format, not the default.</strong> As I discussed at length in an earlier post, the default 14-field format is easy to set up but leaves out fields you’ll want later — TCP flags, true packet source/destination for NAT gateway traffic, and flow direction. A custom format that includes<em> tcp-flags</em>, <em>pkt-srcaddr,</em> <em>pkt-dstaddr</em>, and <em>flow-direction </em>is much more valuable for security investigations.</p><ul><li><strong>Deliver straight to S3</strong> rather than routing through CloudWatch Logs first because it is lower latency and one less hop to manage. Use plain text with gzip compression for Splunk ingestion (Parquet is great for Athena but doesn’t play well with the Splunk Add-on).</li><li><strong>Watch your partitioning interval.</strong> Hourly aggregation is the default and generally the right call. A 5-minute interval dramatically increases object count and SQS message volume for a marginal timeliness gain.</li><li><strong>Set S3 lifecycle policies early.</strong> Flow logs are almost always your largest log volume by an order of magnitude, so plan for a transition to Infrequent Access after 30 days and Glacier after 90 (or whatever your compliance window requires).</li><li><strong>Give this source its own dedicated SQS queue.</strong> Don’t share a queue across log types. The volume and object creation rate here is high enough that you want independent scaling and easy troubleshooting.</li></ul><h3>Splunk configuration</h3><ul><li>Because a custom field format won’t match the Add-on’s default field extraction, you’ll need a <strong>custom sourcetype</strong> with your own <em>props.conf / transform/conf</em> extraction logic matching your field list.</li><li>Use a <strong>dedicated index</strong> (i.e. <em>aws_vpc_flow</em>) with tighter retention than your other AWS sources: 30–60 days hot is typical given the volume, with longer retention in a cheaper storage tier if compliance requires it.</li><li>Watch your timestamp parsing — the <em>start/end</em> fields are epoch seconds, and Splunk can misfire on auto-detecting purely numeric timestamp fields if <em>TIME_FORMAT</em> isn&#39;t set explicitly.</li><li>Map fields to Splunk’s <strong>Network Traffic data model — only available on Enterprise Splunk </strong>(<em>src, dest, src_port, dest_port, transport, action, bytes_in, bytes_out</em>) because this is what unlocks network-based correlation searches.</li></ul><h3>Managing volume</h3><p>This is the one source where cost discipline matters most:</p><ul><li>Consider ingesting only <em>REJECT</em> traffic into your primary security indictor: This can cut volume dramatically while preserving the highest-value signal (denied connections, potential scanning).</li><li>Keep full ALL-traffic logs in S3/Athena for occasional forensic deep-dives rather than indexing everything in Splunk.</li><li>Use index-time filtering to drop known-noisy internal health-check traffic before it consumes license.</li></ul><h3>Outcomes</h3><p>Denied-connection dashboards that surface reconnaissance attempts, top-talker analysis for spotting potential data exfiltration, baseline traffic profiles per subnet that alert on deviation, and — most powerfully — the ability to correlate a <em>REJECT</em> spike with a CloudTrail security group change that happened three minutes earlier.</p><h3>B. Ingesting CloudTrail</h3><p>CloudTrail is the easiest to set up. Splunk’s AWS Add-on has excellent out-of-the-box support.</p><h3>AWS configuration</h3><ul><li>Create an <strong>Organization trail</strong> if you’re using AWS Organizations, so activity across all accounts lands centrally. Otherwise, set up per-account trails.</li><li>Enable <strong>multi-region logging</strong> — this is non-negotiable. A single-region trail will silently miss activity happening anywhere else.</li><li>Turn on <strong>log file validation</strong> to get integrity hashes, which matters if you ever need to demonstrate chain of custody for a compliance audit or investigation.</li><li>Use a <strong>dedicated CloudTrail S3 bucket</strong> with a locked-down bucket policy (write access limited to the CloudTrail service principal), and consider S3 Object Lock or versioning for tamper-evidence.</li><li>Be selective about <strong>data events</strong> (S3 object-level, Lambda invocation logging) — they’re valuable but very high volume, so scope them to sensitive resources rather than enabling globally.</li><li>Same pattern as before: dedicated SQS queue, S3 event notifications feeding it.</li></ul><h3>Splunk configuration</h3><p>The Add-on does most of the work for you:</p><ul><li>Select the Add-on’s <strong>built-in CloudTrail input type</strong> rather than a generic S3 input — it already knows how to handle the gzip JSON structure and multi-record files.</li><li>Use the shipped <em>aws:cloudtrail</em> sourcetype as-is; there&#39;s rarely a need to override it.</li><li>Route to a dedicated index (i.e. <em>aws_cloudtrail</em>) with longer retention than your other sources: 1 year or more is common for SOC 2/PCI requirements.</li><li>CIM mapping to the <strong>Change Analysis</strong> and <strong>Authentication</strong> data models comes largely pre-built with the Add-on.</li></ul><h3>Outcomes</h3><p>This is your highest-value security source, and the alerts practically write themselves: root account usage (which should be near-zero), IAM policy or permission changes that could indicate privilege escalation, console logins without MFA, API activity from unexpected geographies, spikes in failed API calls that might indicate credential probing, and security group changes that you can immediately cross-reference against VPC Flow Log activity.</p><p>If you’re running Splunk Enterprise Security, most of its out-of-box correlation content assumes CloudTrail-shaped data — so this source is also your fastest path to getting real value out of ES.</p><h3>C. Ingesting Application Logs</h3><p>This is the most diverse source of logs so this is all about getting the data into a consistent shape before it hits Splunk.</p><h3>AWS configuration</h3><ul><li>For applications logging through <strong>CloudWatch Logs</strong> (typical for Lambda, ECS, EKS via Fluent Bit, or EC2 via the CloudWatch agent), the standard managed path is a <strong>CloudWatch Logs subscription filter feeding Kinesis Data Firehose, which delivers to S3</strong>. This is more reliable and lower-maintenance than hand-rolling a Lambda export function.</li><li>If some applications can write directly to S3 (via a sidecar or agent), skip CloudWatch Logs entirely for those and land straight in S3.</li><li>Organize your S3 prefixes by application or service so this becomes the natural basis for sourcetype and index routing on the Splunk side.</li><li>Use one SQS queue per application, or a shared queue with prefix-based filtering, depending on team ownership and volume.</li></ul><h3>Splunk configuration</h3><ul><li>Use the generic S3 (SQS-based) input type in the Add-on — there’s no specialized input for arbitrary app logs the way there is for CloudTrail.</li><li>Expect to build <strong>custom sourcetypes for each application</strong>, since formats vary widely. Pay particular attention to:</li><li>LINE_BREAKER / SHOULD_LINEMERGE settings if you have multi-line events like Java stack traces</li><li>TIME_FORMAT / TIME_PREFIX since app logs rarely match Splunk&#39;s auto-detected timestamp formats</li><li>KV_MODE = json if applications emit structured JSON</li><li>Index strategies usually follow team or business-domain boundaries, which conveniently also sets you up for role-based access control (each team sees only their own application’s index).</li></ul><p><em>NOTE: Ideally your company uses </em><strong><em>structured JSON logging with a standard schema (</em></strong><em>timestamp, level, service name, trace ID, message, at minimum). The difference in Splunk parsing effort, ongoing maintenance, and dashboard reusability between structured and unstructured app logs is enormous.</em></p><h3>Outcomes</h3><p>Error rate and exception dashboards per service, latency percentiles when duration is logged, correlation between error spikes and deployment timestamps, distributed trace correlation across microservices, and — eventually — business-level KPIs that can be surfaced to non-engineering stakeholders straight out of the same platform your SOC uses.</p><h3>How to tackle all of this sensibly</h3><p>Trying to onboard all three sources simultaneously is a good way to get stuck…</p><ol><li><strong>You could start with CloudTrail.</strong> There is minimal configuration, excellent out-of-box Add-on support, and immediate security value. This also validates your SQS/IAM pipeline pattern end-to-end with the least amount of friction, giving you a template to reuse.</li><li><strong>Move to VPC Flow Logs.</strong> Reuse the pipeline pattern you just built, but budget real time for custom field extraction and volume management. Start narrow — a single VPC, or REJECT-only traffic — before expanding organization-wide.</li><li><strong>Tackle application logs last.</strong> This is the highest-variability, highest-coordination source, since it depends on getting application teams aligned on log format. Pick one pilot application, get the parsing right, and use it as the template for onboarding the rest.</li></ol><p>A few decisions are worth making early, before you’re deep into all three pipelines:</p><ul><li>a consistent naming convention for indexes and sourcetypes</li><li>clear ownership of SQS queues and IAM policy changes (usually a shared platform or security team)</li><li>if you’re licensing Splunk by ingest volume: a cost model for VPC Flow Log filtering before you turn it on organization-wide. That last one in particular can be the difference between a sustainable pipeline and a license bill nobody saw coming.</li></ul><h3>Bottom line</h3><p>Your AWS logs are already in S3, which means the hardest part — getting the data to persist somewhere durable and cheap, is done.</p><p>The remaining work is building the bridge from S3 into Splunk, and that bridge pays for itself the moment you can answer a question that spans AWS and everything else in your environment in a single search. That’s the capability CloudWatch alone cannot give you…</p><h3>Extra: more on AWS Splunk apps</h3><p>The pipeline setup I talked about (SQS → S3 → Splunk) gets the data <em>in</em>, but the add-on is what enables the parsing, and the apps are what give you dashboards and premium correlation logic on top.</p><h3>The one you definitely need: Splunk Add-on for AWS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Dsj6YuaVweUiPkfAfw_oHA.png" /></figure><p>Definitely NOT optional, this is the foundation for everything in the setup steps above. It provides the modular inputs (including the SQS-based S3 input), the CIM field mappings, and the pre-built parsing for CloudTrail, VPC Flow Logs, Config, and other AWS sourcetypes. Install this on your heavy forwarder as described earlier. As of version 7.0+, it also absorbed the old <strong>Splunk Add-on for Amazon Security Lake and Splunk Add-on for Amazon Kinesis Firehose</strong>, so you don’t need those separately anymore and these have been deprecated and merged.</p><h3>The dashboard layer: Splunk App for AWS Security Dashboards</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*PckCxc55-NnFmxsDE5YyQg.png" /></figure><p>This is optional but worth adding once data is flowing. It gives you pre-built dashboards, reports, and alerts — Security Overview, IAM insights, Security Group insights, resource activity — without you having to hand-build every panel from scratch. It sits on top of the Add-on rather than replacing it: <strong>you need both installed</strong>, and specifically Add-on version 6.0.0 or later. Worth using as your starting point for the CloudTrail/VPC Flow use cases we outlined, then customize from there.</p><h3>The Security Hub piece — a bit different from the others</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*7Yn2yegDZupheziIJYtRGw.png" /></figure><p>AWS Security Hub findings normally flow into Splunk via a <em>different</em> path — EventBridge → HTTP Event Collector (HEC), not the SQS/S3 route.</p><ul><li><strong>Splunk Add-on for AWS Security Hub</strong> — ingests real-time Security Hub findings and converts them into findings/notable events specifically for <strong>Splunk Enterprise Security</strong>. Note: this is a premium add-on requiring a separate subscription (via “AWS Security Hub Extended”), not a free Splunkbase download.</li></ul><h3>Wrap-up</h3><p>OK, this was a quick view into ingesting your AWS logs into Splunk, where it can be analyzed and evaluated together with the rest of your infrastructure logs.</p><p>I evaluated these capabilities in Splunk Enterprise edition, and not in the Cloud version, which I also use. I assume there will be a lot of similarities but that the functionality will differ in some important areas. Please consult the Splunk documentation. Apps and capabilities are likely to evolve over time, as happened to me over the short 10 days I was evaluating and testing this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9770fd8cf5ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VPC Flow Logs: Eyes on your VPC]]></title>
            <link>https://medium.com/@gkinthaert/vpc-flow-logs-eyes-on-your-vpc-736355e6d15a?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/736355e6d15a</guid>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[vpc-flow-logs]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 21:58:09 GMT</pubDate>
            <atom:updated>2026-07-23T21:58:09.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIr7LumRfCBT1tzTg6OVcA.png" /></figure><p>In today’s post I take a look at VPC Flow Logs, and why they matter for security and monitoring, how to actually put them to work, which AWS services fit into the pipeline, and, most crucial, what to actually look for once the logs start compiling.</p><p>How about an analogy, for starters: Imagine VPC Flow Logs as the security camera providing footage in your apartment building. You see all the comings and goings, and although the recording does not tell you what was said in a conversation, it will show you who talked to whom, when, how much, and whether they were let through the door to begin with. For anyone in the business of securing and monitoring a VPC, that type of info is of high value.</p><h3>So, what are VPC Flow Logs?</h3><p>VPC Flow Logs is an AWS feature that captures metadata about the IP traffic flowing to and from network interfaces in your VPC. You can enable it at three levels of granularity:</p><ul><li>the entire VPC</li><li>a specific subnet</li><li>an individual elastic network interface (ENI)</li></ul><p>Enable it at the VPC level and every interface underneath, such as EC2 instances, load balancers, NAT gateways, RDS instances, Lambda ENIs, and more, gets covered automatically.</p><p>A few properties that make VPC Flow Logs valuable to you:</p><ul><li><strong>Out-of-band.</strong> Flow Logs are captured outside the actual data path, so enabling or disabling them has no effect on network throughput or latency.</li><li><strong>Metadata, not payload.</strong> You get source/destination IPs and ports, protocol, byte and packet counts, and accept/reject decisions — not the contents of the packets. This makes it useful for pattern and anomaly detection without the privacy and storage overhead of full packet capture.</li><li><strong>Cheap and durable (relative to the alternative).</strong> Compared to standing up your own packet-capture infrastructure, Flow Logs are essentially free to enable, with costs scaled to log volume and destination.</li></ul><p>Each VPC Flow Log record represents traffic aggregated over a capture window (The default is 10 minutes but you could set it to 1 minute understanding that you will get a much higher volume of flow records) and is written as a space-delimited string.</p><p>The initial version 2 format gave you the fundamentals: account ID, interface ID, source/destination IP and port, protocol, packet and byte counts, start/end time, and the action field (ACCEPT or REJECT).</p><p>Since then, AWS has significantly expanded what’s available through custom format fields (we are at version 11 as of today’s date). Check out the latest: <a href="https://docs.aws.amazon.com/vpc/latest/userguide/flow-log-records.html">https://docs.aws.amazon.com/vpc/latest/userguide/flow-log-records.html</a></p><p>Some noteworthy format fields:</p><ul><li><strong><em>vpc-id, subnet-id, instance-id</em></strong>: for mapping traffic directly to resources</li><li><strong><em>tcp-flags</em></strong>: for identifying SYN, SYN-ACK, FIN, and RST packets</li><li><strong><em>flow-direction, traffic-path</em></strong>: for understanding whether traffic is ingress/egress and what next-hop it took (NAT gateway, internet gateway, peering connection, transit gateway, etc.)</li><li><strong><em>pkt-src-aws-service / pkt-dst-aws-service</em></strong>: identifying when traffic is going to/from an AWS-managed service like S3 or CloudFront</li><li>Newer fields extend visibility into ECS container-level traffic (task IDs, cluster ARNs, service names) and EC2 resource tags, reducing the need to manually correlate flow data with other AWS metadata</li></ul><p>NOTE: For security and monitoring work, it’s almost always worth moving off the default format and onto a custom format that includes <strong><em>tcp-flags, pkt-srcaddr, pkt-dstaddr </em></strong>(the &quot;real&quot; IPs behind NAT), and the AWS service fields.</p><h3>Why Flow Logs matter: Security, monitoring, $$</h3><p>Flow Logs sit at the intersection of security, operations, and cost insights. From a security and monitoring lens specifically, they support these core use cases:</p><p><strong>1. Threat detection and network forensics.</strong> Flow Logs let you see connection patterns that indicate reconnaissance, lateral movement, data exfiltration, and command-and-control activity — <strong><em>without needing an agent on every host</em></strong>. When an incident happens, Flow Logs are frequently the first place you should look to reconstruct a timeline: what did the compromised instance talk to, when, and how much data moved.</p><p><strong>2. Validating security group and NACL behavior.</strong> Security groups and network ACLs define what <em>should</em> happen, but Flow Logs show what <em>actually</em> occurred. The <strong><em>REJECT</em></strong> action is direct evidence of traffic your security controls are blocking. which confirms that controls are working, but also good to find any misconfigured rules that block legitimate traffic.</p><p><strong>3. Compliance and audit evidence.</strong> Many compliance frameworks (PCI-DSS, HIPAA, SOC 2, FedRAMP) expect network traffic logging and retention. Flow Logs, shipped to an immutable, access-controlled destination, provide durable evidence of what traffic traversed the environment.</p><p><strong>4. Anomaly and baseline monitoring.</strong> Once you know what “normal” traffic volume and patterns look like for a workload, Flow Logs become the raw material for detecting deviations — a database suddenly talking to the internet, a spike in outbound byte counts, or a burst of connections from an unfamiliar IP range.</p><h3>How Flow Logs are used</h3><p>Enabling Flow Logs is only step one. The real value comes from the pipeline you should build around them, addressing the action steps of <strong>capture, delivery, storage, query, and alerting.</strong></p><h3>Step 1: Capture</h3><p>Enable Flow Logs on the VPC, subnet, or ENI, choosing a custom format that includes the security-relevant fields mentioned earlier, and set the traffic type to capture (ACCEPT, REJECT, or ALL)</p><p><strong>NOTE: for security purposes, ALL is usually the right call</strong></p><h3>Step 2: Deliver and store</h3><p>Flow Logs can be published to several destinations, each suited to different needs:</p><ul><li><strong>Amazon CloudWatch Logs: </strong>good for almost real-time querying via <strong>CloudWatch Logs Insights</strong>, and for wiring up <strong>CloudWatch Alarms</strong> and <strong>metric filters</strong> for near-real-time alerting on specific patterns (e.g., a spike in REJECT traffic to a sensitive port).</li><li><strong>Amazon S3: </strong>the most cost-effective option for long-term retention and large-scale historical analysis, especially when paired with Parquet output format (which reduces storage cost and speeds up query performance versus plain text).</li><li><strong>Amazon Data Firehose: </strong>for streaming Flow Log data to third-party SIEMs (Splunk, Sumo Logic, Datadog, Elastic) or into a custom near-real-time processing pipeline.</li></ul><h3>Step 3: Query (+analyze)</h3><ul><li><strong>Amazon Athena: </strong>querying Flow Logs stored in S3 with standard SQL. Athena is great for retrospective investigation and ad hoc threat hunting across large volumes of historical data.</li><li><strong>CloudWatch Logs Insights: </strong>for fast queries against logs stored in CloudWatch Logs, well suited to recent-window investigation during an active incident.</li><li><strong>Amazon OpenSearch Service: </strong>when you want full-text search, visual dashboards, and more flexible exploration at scale.</li><li><strong>Amazon QuickSight: </strong>for building traffic dashboards on top of Athena or OpenSearch data for ongoing visibility rather than one-off investigation.</li></ul><h3>Step 4: Alert: detect and correlate</h3><p>This is where Flow Logs start becoming a security control:</p><ul><li><strong>Amazon GuardDuty: </strong>natively ingests VPC Flow Logs (along with DNS logs and CloudTrail) as one of its core data sources for threat detection. GuardDuty can identify things like communication with known-malicious IPs, cryptocurrency-mining traffic patterns, and port-scanning behavior, without you needing to write your own detection logic.</li><li><strong>AWS Security Hub: </strong>aggregates GuardDuty findings (and other services’) derived from Flow Log analysis into a centralized security posture view.</li><li><strong>Amazon Detective: </strong>uses Flow Logs alongside CloudTrail and GuardDuty findings to build interactive visualizations for investigating the root cause of a security finding — tracing an alert back through the actual network activity that triggered it.</li><li><strong>AWS Lambda: </strong>often triggered on log delivery or via Firehose, for custom parsing, and routing of specific patterns to alerting systems like Amazon SNS or a SIEM.</li></ul><h3>What to look for in the VPC Logs</h3><p>A VPC (and you likely have many of these running) can generate an enormous number of flow records, so knowing what patterns to look for/care about is important to separate effective monitoring from collecting noise. Some of the highest-signal things to look for:</p><p><strong>REJECT patterns that indicate scanning or probing.</strong> A single source IP generating REJECT records against many different destination ports on the same host, or against many different hosts on the same port, is an identifiable scanning signature. A sudden burst of REJECTs against a specific instance can indicate an attacker probing for open services.</p><p><strong>Unexpected ACCEPT traffic.</strong> Traffic that is accepted but should not be (i.e. a database instance accepting inbound connections directly from the internet rather than only from application-tier security groups) is often a sign of a security group or NACL misconfiguration rather than an active attack, but it’s exactly the kind of thing Flow Logs surface that other tools miss.</p><p><strong>Traffic to/from known-malicious or unexpected external IPs.</strong> Correlating destination IPs against threat intelligence feeds (which GuardDuty does automatically) can catch command-and-control beaconing or connections to IPs associated with malware distribution.</p><p><strong>Abnormal byte/packet volume, especially outbound.</strong> A large, sustained spike in outbound bytes from an instance that normally has minimal outbound traffic is a strong exfiltration indicator, especially if the destination is an unfamiliar external IP rather than another AWS service or known partner.</p><p><strong>TCP flag anomalies.</strong> A high ratio of SYN packets to completed connections (SYN without corresponding SYN-ACK/ACK) can indicate a SYN flood or scanning activity. A cluster of RST flags on connections to a specific host can indicate a service being probed or repeatedly refusing connections.</p><p><strong>Traffic between security zones that should not be talking.</strong> If you’ve segmented your VPC into tiers (web, app, data) or by trust level, Flow Logs let you verify that traffic actually respects those boundaries (i.e. a web-tier instance directly reaching the data tier, bypassing the application tier, is a lateral-movement red flag).</p><p><strong>Unusual traffic timing.</strong> Connections and data transfers occurring well outside normal business hours or usage patterns for a given workload are worth a second look, particularly combined with volume anomalies.</p><p><strong>Traffic to non-standard ports for known protocols, or high-risk ports in general.</strong> Outbound connections on ports associated with remote access tools, or traffic on ports that have no legitimate business reason to be open in your environment, are worth flagging for review.</p><p><strong>NODATA and SKIPDATA records.</strong> These indicate periods where no traffic occurred or where the Flow Logs system had internal capacity issues and couldn’t fully log activity — worth being aware of so gaps in your data aren’t mistaken for gaps in traffic.</p><h3>Putting it all together</h3><p>VPC Flow Logs by themselves just an artifact: The value comes from the pipeline you build around them: Architect your approach: Decide on a custom format that captures the fields that matter, route the logs to the right destination for your query patterns, layering in GuardDuty and Security Hub for automated detection, and know the specific traffic patterns worth looking at.</p><p>Flow Logs can be a great, cost-effective, low-overhead source of network visibility available in, and it is well worth incorporating it in your environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=736355e6d15a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[And now for something different: Hosting a static site, but with AWS Amplify and CDK]]></title>
            <link>https://medium.com/@gkinthaert/and-now-for-something-different-hosting-a-static-site-but-with-aws-amplify-and-cdk-56d05d2121d3?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d05d2121d3</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 14:14:58 GMT</pubDate>
            <atom:updated>2026-07-21T19:41:24.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNEOZbYCbfT4bQWCz8Ir2g.png" /></figure><p>When it came time to host a static website that I had built in VS Code and stored in a GitHub repository, I chose AWS Amplify, orchestrated through the AWS CDK, rather than what I usually do, implementing this with an S3 + CloudFront setup.</p><p>Here’s how that decision played out, and how it stacks up against the more traditional approach.</p><h3>The setup</h3><p>The architecture is amazingly straightforward: The content lives in a GitHub repository, and the AWS CDK defines an Amplify App resource that points at that repo. Amplify handles the build (running whatever build commands the static site generator needs, such as Next.js export, or a plain npm build), then deploys the output to its own managed hosting layer, (which actually sits on top of S3 and CloudFront under the hood but is invisible to you).</p><p>Because the whole thing is defined in CDK, the Amplify app, branch configuration, build settings, and even custom domain associations live as code alongside the rest of my infrastructure. <strong><em>cdk deploy</em></strong> stands up the app and wires it to GitHub; from then on, any pushes to the tracked branch trigger a build and deploy automatically.</p><h3>Pros of Amplify + CDK</h3><p><strong>There is minimal infrastructure to manage.</strong> You don’t need to provision a bucket, configure static website hosting properties, set up an Origin Access Identity (OAI) or Origin Access Control (OAC), write a CloudFront distribution, or manage cache invalidations. Amplify does all of that internally.</p><p><strong>You get a built-in CI/CD.</strong> Connecting to GitHub gives you automatic builds on push, preview environments for pull requests, and build logs in the console — no separate CodePipeline or GitHub Actions workflow required.</p><p><strong>Sensible defaults.</strong> HTTPS, a CDN, and cache behavior are configured out of the box. You get a <strong><em>*.amplifyapp.com</em></strong> URL immediately, and attaching a custom domain with a managed certificate is a few more lines of CDK.</p><p><strong>Infrastructure as code, but declarative and compact.</strong> The CDK construct for Amplify is a handful of lines compared to the multiple constructs (bucket, OAC, distribution, Route 53 records, ACM certificate) needed for a hand-built S3/CloudFront stack. Mine was under 60 lines, including comments…</p><p><strong>Good fit for teams that want “push to deploy.”</strong> Non-infrastructure folks can merge a PR and see it live without touching AWS.</p><h3>Cons of Amplify + CDK</h3><p><strong>There is less control over caching and headers.</strong> Amplify’s CDN behavior is configurable, but not to the same granularity as a CloudFront distribution you own directly.</p><p>Custom cache policies, origin request policies, or Lambda@Edge/CloudFront Functions for things like URL rewrites or A/B testing are more difficult to do.</p><p><strong>Hidden underlying resources.</strong> Because Amplify manages the S3 bucket and CloudFront distribution for you, you can’t easily reference or modify them directly in other parts of your CDK stack. If you later need fine-grained bucket policies or a shared distribution across multiple apps, you’re fighting the abstraction.</p><p><strong>Build environment quirks.</strong> Amplify’s build containers have their own image and Node/runtime versions. Reproducing an odd local build issue can mean more back-and-forth than debugging a build you run yourself in CodeBuild.</p><p><strong>Different cost model.</strong> Amplify charges for build minutes and hosting/data transfer, which is usually competitive for small-to-medium sites but is a separate pricing structure from raw S3 storage and CloudFront transfer costs, so it’s worth checking at scale.</p><p><strong>Vendor lock-in to the Amplify service, not just AWS.</strong> Migrating off Amplify later (say, to self-managed S3/CloudFront) means recreating the pipeline, since the deploy history and internal resource wiring aren’t portable.</p><h3>How this compares to S3 + CloudFront</h3><p>The S3 + CloudFront approach is the “build it yourself” alternative: an S3 bucket stores the static assets, a CloudFront distribution serves them via CDN with an Origin Access Control locking the bucket down to CloudFront-only access, and a separate CI/CD pipeline (GitHub Actions, CodePipeline, or aws s3 sync) handles builds and deploys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*OLh0CI_44RE9DHBBj0vR0w.png" /><figcaption>comparison chart</figcaption></figure><h3>Which should you use?</h3><p>If the goal is to get a static site live quickly, with automatic deploys from GitHub and minimal ongoing infrastructure work, Amplify via CDK is ideal. However, if you need precise control over caching behavior, edge logic, multi-origin routing, or you’re already managing a broader CloudFront-based architecture that this site should plug into, going straight to S3 and CloudFront gives you the flexibility Amplify abstracts away.</p><p>For this latest project, which was a single page content site, with low anticipated traffic, no complexity, and a developer team of 1 who wanted “merge and it’s live”, Amplify was the right tool. But it’s worth knowing what you’re giving up in exchange for that simplicity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d05d2121d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Re-Building Better — Improving Cloud Infrastructure Iteratively]]></title>
            <link>https://medium.com/@gkinthaert/re-building-better-improving-cloud-infrastructure-iteratively-ed741db8efd4?source=rss-5a0278d79bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed741db8efd4</guid>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Geert Kinthaert]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 18:21:59 GMT</pubDate>
            <atom:updated>2026-07-09T18:21:59.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScizKOUa0xgjikllNdrVEw.png" /><figcaption>Infrastructure diagram</figcaption></figure><p>I just finished the first phase of a project where a start-up health services provider had its infrastructure on AWS already, but it was implemented in a less than ideal fashion: All of the infrastructure was created manually via the AWS Console, and there was no version control of any infrastructure changes made. Their application was running on EC2 instances and patient (test — this company is just getting started) data was held in a MySQL RDS database. Pretty typical on the surface, but the VPC had only public subnets, and there was no proper network segmentation built in.</p><p>When you’re handling patient data, “it works” is not sufficient — “secure, repeatable, and explainable” is the standard I wanted to bake in.</p><h3>Starting with the Network Foundation</h3><p>Every system needs a secure perimeter, and this one starts with a VPC split across two Availability Zones for redundancy. Inside that VPC, I carved out two kinds of subnets with very different jobs:</p><ul><li><strong>Public subnets</strong> host the company’s EC2 application instance — and this is the only part of this architecture that talks to the internet. (an Internet Gateway is assumed and provisioned when you set up a subnet as PUBLIC)</li><li><strong>Private isolated subnets</strong> is where the RDS database lives — with no route in or out except from resources inside the VPC.</li></ul><p>This is the “secure facility perimeter” model: nothing reaches the data vault without first passing through the application layer.</p><h3>Splitting the Code the Way We Split the Network</h3><p>There are many ways to split the code into logical segments, but I like to mirror the architecture. Mind you there is no “best” approach, but as I get lost when code scrolls off the page, I avoid big monolith files, and have the set of files follow the architectural design to some degree. Don’t go overboard either, as you can also lose track of things when there are too many items</p><ul><li>infrastructure-stack.ts — owns the VPC and nothing else</li></ul><pre>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br><br>export class InfrastructureStack extends cdk.Stack {<br>  public readonly vpc: ec2.Vpc;<br><br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br><br>    this.vpc = new ec2.Vpc(this, &#39;MyVpc&#39;, {<br>      maxAzs: 2, // 2 azs for high availability<br>      subnetConfiguration: [<br>        {<br>          name: &#39;Public-SN&#39;,<br>          subnetType: ec2.SubnetType.PUBLIC,<br>          cidrMask: 24,<br>        },<br>        {<br>          name: &#39;Private-SN&#39;,<br>          subnetType: ec2.SubnetType.PRIVATE_ISOLATED, // isolated subnet for security<br>          cidrMask: 24,<br>        },<br>      ],<br>    });<br><br>    new cdk.CfnOutput(this, &#39;VpcId&#39;, {<br>      value: this.vpc.vpcId,<br>      description: &#39;VPC ID&#39;,<br>    });<br>  }<br>}</pre><ul><li>sg.ts — a <strong>construct</strong> dedicated to security group rules for both EC2 and RDS</li></ul><pre>import { Construct } from &#39;constructs&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br><br>export interface SecurityGroupsProps {<br>  vpc: ec2.IVpc;<br>}<br><br>export class SecurityGroups extends Construct {<br>  public readonly ec2SecurityGroup: ec2.SecurityGroup;<br>  public readonly rdsSecurityGroup: ec2.SecurityGroup;<br><br>  constructor(scope: Construct, id: string, props: SecurityGroupsProps) {<br>    super(scope, id);<br><br>    // Security Group for EC2 (Allows SSH &amp; App Traffic)<br>    this.ec2SecurityGroup = new ec2.SecurityGroup(this, &#39;EC2SecurityGroup&#39;, {<br>      vpc: props.vpc,<br>      allowAllOutbound: true,<br>      description: &#39;Security group for EC2 instance&#39;,<br>    });<br>    // SSH access is intentionally not opened here — the instance has the SSM managed<br>    // policy and is reached via Session Manager instead of a public port 22.<br>    // this.ec2SecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), &#39;Allow SSH&#39;);<br>    this.ec2SecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(443), &#39;Allow HTTPS&#39;);<br><br>    // Security Group for RDS (Allows traffic from EC2)<br>    this.rdsSecurityGroup = new ec2.SecurityGroup(this, &#39;RDSSecurityGroup&#39;, {<br>      vpc: props.vpc,<br>      allowAllOutbound: true,<br>      description: &#39;Security group for RDS instance&#39;,<br>    });<br>    this.rdsSecurityGroup.addIngressRule(<br>      this.ec2SecurityGroup,<br>      ec2.Port.tcp(3306),<br>      &#39;Allow MySQL from EC2&#39;,<br>    );<br>  }<br>}</pre><ul><li>iam.ts — a <strong>construct</strong> scoped to the EC2 instance&#39;s IAM role</li></ul><pre>import { Construct } from &#39;constructs&#39;;<br>import * as iam from &#39;aws-cdk-lib/aws-iam&#39;;<br><br>export class Ec2IamRole extends Construct {<br>  public readonly role: iam.Role;<br><br>  constructor(scope: Construct, id: string) {<br>    super(scope, id);<br><br>    // IAM Role for EC2 Instance<br>    this.role = new iam.Role(this, &#39;EC2IAMRole&#39;, {<br>      assumedBy: new iam.ServicePrincipal(&#39;ec2.amazonaws.com&#39;),<br>    });<br>    this.role.addManagedPolicy(<br>      iam.ManagedPolicy.fromAwsManagedPolicyName(&#39;AmazonSSMManagedInstanceCore&#39;),<br>    );<br>  }<br>}</pre><ul><li>ec2-stack.ts — wires the EC2 instance and RDS instance together, consuming the constructs above and the VPC passed in from the infrastructure stack</li></ul><pre>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br>import * as rds from &#39;aws-cdk-lib/aws-rds&#39;;<br>import { SecurityGroups } from &#39;./sg&#39;;<br>import { Ec2IamRole } from &#39;./iam&#39;;<br><br>export interface Ec2StackProps extends cdk.StackProps {<br>  vpc: ec2.IVpc;<br>}<br><br>export class Ec2Stack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props: Ec2StackProps) {<br>    super(scope, id, props);<br><br>    const { vpc } = props;<br><br>    // Security groups (EC2 + RDS)<br>    const { ec2SecurityGroup, rdsSecurityGroup } = new SecurityGroups(this, &#39;SecurityGroups&#39;, {<br>      vpc,<br>    });<br><br>    // IAM role for EC2<br>    const { role: ec2Role } = new Ec2IamRole(this, &#39;Ec2IamRole&#39;);<br><br>    // Launch EC2 Instance in Public Subnet<br>    new ec2.Instance(this, &#39;MigrationEC2&#39;, {<br>      vpc,<br>      vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },<br>      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),<br>      machineImage: ec2.MachineImage.latestAmazonLinux2023(),<br>      securityGroup: ec2SecurityGroup,<br>      role: ec2Role,<br>    });<br><br>    // Create RDS Instance in Private Subnet<br>    new rds.DatabaseInstance(this, &#39;MigrationRDS&#39;, {<br>      engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0 }),<br>      vpc,<br>      vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },<br>      securityGroups: [rdsSecurityGroup],<br>      instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO),<br>      allocatedStorage: 20,<br>      storageEncrypted: true, // encrypts data at rest per TechHealth security requirements<br>      multiAz: true, // note: doubles RDS cost — confirm this tradeoff is intentional<br>      removalPolicy: cdk.RemovalPolicy.DESTROY, // WARNING: Deletes DB on stack removal<br>    });<br>  }<br>}</pre><p>That separation makes it easier for someone else after me to see what is going on. If they need to change access rules at some point, they can just look at the security group rules without having to wade through IAM policy or EC2 instance configuration to understand the blast radius of the change: the file boundary <em>is</em> the review boundary.</p><p>Oh yeah, there is one more file you need to think about, and this one lives in the bin directory. This one synthesizes all of the Stack elements</p><pre>#!/usr/bin/env node<br>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import { InfrastructureStack } from &#39;../lib/infrastructure-stack&#39;;<br>import { Ec2Stack } from &#39;../lib/ec2-stack&#39;;<br><br>const app = new cdk.App();<br>const vpcStack = new InfrastructureStack(app, &#39;InfrastructureStack&#39;, {<br>  <br>});<br><br>new Ec2Stack(app, &#39;EC2Stack&#39;, {<br>  vpc: vpcStack.vpc, // Pass the VPC from the InfrastructureStack to the EC2Stack<br>});<br><br>app.synth();</pre><h3>Data Flow</h3><ol><li>I first built this with SSH in mind, as the engineers were familiar with the protocol to reach bastion hosts in their previous environment. In addition, NAT Gateways were not wanted (for cost considerations foremost). I did it a bit different this time, and connected the EC2 instance through Session Manager, <strong>not SSH — no key pair, no port 22 exposed to the world</strong>, just an IAM-authenticated session.</li><li>From that instance, we retrieved database credentials from <strong>Secrets Manager</strong>, where CDK had already stored the auto-generated RDS master password.</li><li>We connected to RDS over port 3306 — a path that only works because the RDS security group explicitly trusts traffic from the EC2 security group, not from a raw CIDR range.</li></ol><p>The result is identity-based access in, security-group-to-security-group trust in the middle, encrypted secrets throughout.</p><h3>Where Infrastructure as Code is paying dividends</h3><ul><li>When the EC2 instance in place turned out to be running a 5-year-old, unsupported AMI, I made the change to <em>machineImage</em> in <em>ec2-stack.ts</em>, and it is deployed the same way every other change is deployed.</li><li>Organizing the code into multiple file artifacts does not affect what is built, but it sure makes things a lot more legible, especially for the folks running this infrastructure after me.</li></ul><p>Traceability and consistency across the board: the infrastructure’s history lives in commits, and you don’t have to recall what you clicked in the console the last time a change was needed.</p><h3>Iterative build</h3><p>Good architecture is tightened over time, and there should be follow-ups and ongoing conversations. In the first phase of this project (which promises to become series of multi week engagements), there were already some changes along the way from the initial requirements.</p><p><strong>HTTPS, not just HTTP.</strong> Patient connections are secured via HTTPS, but the original security group also opened port 80. I removed that and only kept the rule with port 443.</p><p><strong>Important Note: a TLS certificate and a web server or load balancer configured to terminate HTTPS still need to be in place before this is actually end-to-end encrypted.) More on this in a bit!</strong></p><p><strong>Removing open SSH.</strong> The original EC2 security group allowed SSH from anywhere on the internet. The customer wanted this tightened to just one or two IPs, but I thought we could do better with least-privilege access controls. Since we’re already connecting through Session Manager, which requires no inbound port at all, we removed the SSH rule entirely rather than trying to narrow it.</p><p><strong>Encrypting the database at rest.</strong> It was specified that RDS should implement encryption and access controls, but <em>storageEncrypted</em> wasn&#39;t set at all, meaning it defaulted to off. I turned it on and added this to the IaC code.</p><p><strong>Making the database Multi-AZ.</strong> The VPC was already spread across two Availability Zones, but the database itself was single-AZ which meant it was a single point of failure that could jeopardize the data persistence and reliability requirement the customer set. I enabled Multi-AZ, with the tradeoff noted directly in the code: this roughly doubles RDS cost, so I had confirmation that was indeed what was needed here. (remember the customer is cost conscious and did not want to use NAT Gateways). Patient data trumps at least some of the $ concerns. And additional HIPAA requirements will need some additional investments, as I will lay out in the next section…</p><p>I also want to point out that these scope changes were not hard to implement, as each was a one- or two-line change, made possible by the facts that a. we are now using IaC, and b. that the security groups, the IAM role, and the compute/database resources all live in their own files.</p><h3>Project: The next phase — additional HIPAA related security measures</h3><p>This project was done for a start-up entity in the health services domain, so there are some compliance considerations that need to be put in place. The HIPAA Security Rule (45 CFR §164.312(e)) requires all PHI be encrypted in transit.</p><p>We can pick one of two ways to add a load balancer here:</p><ul><li><strong>Network Load Balancer (NLB) with TLS passthrough</strong> — the NLB forwards raw TCP on port 443 straight to the EC2 instance without ever decrypting it. The EC2 instance holds the certificate and terminates TLS itself. This is core end-to-end encryption as the load balancer never sees plaintext.</li><li><strong>Application Load Balancer (ALB) with TLS termination</strong> — the ALB decrypts HTTPS at the edge (using an ACM cert), then optionally re-encrypts a new HTTPS connection to the EC2 instance. This gives you nice Layer-7 features (host/path routing, AWS WAF integration, easier cert management via ACM), but the ALB itself holds plaintext traffic in memory, so it is not quite strictly end-to-end.</li></ul><p>In practice, most HIPAA-compliant AWS reference architectures lean toward <strong>ALB with TLS termination/re-encryption</strong>, because it’s still fully compliant and gets you WAF plus centralized cert management, which are themselves valuable technical safeguards under the Security Rule (access control, audit logging, and reducing attack surface at the edge).</p><p>Strict passthrough (NLB) is really only worth the operational overhead if your organization’s own risk assessment or a client contract specifically requires that no intermediary — even an AWS-managed, BAA-covered one — ever holds decrypted PHI, even momentarily.</p><p>This is not something you yourself might actually be working on, but if not in place, you can remind your customer/AWS account holder that they might need to make sure there is an<strong> executed AWS BAA on the account</strong>, since a service being HIPAA-eligible only matters once the account has an executed BAA and the service is configured appropriately.</p><h3>What is this BAA?</h3><p>A BAA (Business Associate Agreement) is a contract required under HIPAA between a “covered entity” (like a healthcare provider or health plan) and any “business associate” that creates, receives, maintains, or transmits PHI (protected health information) on their behalf. AWS, as your cloud infrastructure provider, is a business associate in this relationship.</p><p><strong>What it actually is on the AWS side:</strong></p><ul><li>AWS offers a standardized BAA that you accept electronically through the <strong>AWS Artifact</strong> console — no negotiation, no cost, just an acceptance click by an authorized signer on the account.</li><li>Once accepted, your AWS account becomes a “HIPAA account,” and you’re contractually allowed to put PHI on AWS <strong>only</strong> using services from AWS’s published list of “HIPAA-eligible services.” EC2, RDS, ALB, S3, KMS, etc. are all on that list. Something like Lightsail or certain AI/ML features might not be, depending on configuration.</li></ul><p><strong>What it is NOT:</strong></p><ul><li>Signing the BAA doesn’t make your deployment compliant by itself. It’s a legal precondition, not a technical guarantee. AWS secures the underlying infrastructure (physical security, hypervisor, network backbone); you’re still responsible for configuring encryption, access control, audit logging, etc. correctly on top of that — the “shared responsibility model.”</li><li>It’s account-scoped. If your org has multiple AWS accounts, each one that will touch PHI needs its own signed BAA.</li><li>There’s no technical enforcement — AWS won’t stop you from sending PHI to a non-eligible service even after you’ve signed. Compliance is on you to verify.</li></ul><h3>Practical considerations, CDK-wise:</h3><ul><li><strong>lib/alb.ts:</strong> An additional file that creates the Application Load Balancer, an HTTPS:443 listener using an ACM certificate, and a target group that talks HTTPS:443 to the instances (the re-encrypt hop).</li></ul><pre>import { Construct } from &#39;constructs&#39;;<br>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br>import * as elbv2 from &#39;aws-cdk-lib/aws-elasticloadbalancingv2&#39;;<br>import * as acm from &#39;aws-cdk-lib/aws-certificatemanager&#39;;<br><br>export interface LoadBalancerProps {<br>  vpc: ec2.IVpc;<br>  albSecurityGroup: ec2.ISecurityGroup;<br>  // ARN of an ACM certificate that is already issued/validated in this region.<br>  // e.g. &#39;arn:aws:acm:us-east-1:123456789012:certificate/xxxxxxxx-xxxx-...&#39;<br>  certificateArn: string;<br>}<br><br>export class LoadBalancer extends Construct {<br>  public readonly loadBalancer: elbv2.ApplicationLoadBalancer;<br>  public readonly targetGroup: elbv2.ApplicationTargetGroup;<br><br>  constructor(scope: Construct, id: string, props: LoadBalancerProps) {<br>    super(scope, id);<br><br>    const { vpc, albSecurityGroup, certificateArn } = props;<br><br>    // Internet-facing ALB in the public subnets.<br>    this.loadBalancer = new elbv2.ApplicationLoadBalancer(this, &#39;Alb&#39;, {<br>      vpc,<br>      internetFacing: true,<br>      vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },<br>      securityGroup: albSecurityGroup,<br>    });<br><br>    // Target group re-encrypts to the EC2 instances on 443 (HTTPS), preserving<br>    // encryption for the ALB -&gt; instance hop. The instances must terminate TLS<br>    // themselves — a self-signed certificate is fine<br>    this.targetGroup = new elbv2.ApplicationTargetGroup(this, &#39;Ec2TargetGroup&#39;, {<br>      vpc,<br>      port: 443,<br>      protocol: elbv2.ApplicationProtocol.HTTPS,<br>      targetType: elbv2.TargetType.INSTANCE,<br>      healthCheck: {<br>        path: &#39;/&#39;, // adjust to a real health check path on your app<br>        protocol: elbv2.Protocol.HTTPS,<br>      },<br>    });<br><br>    this.loadBalancer.addListener(&#39;HttpsListener&#39;, {<br>      port: 443,<br>      protocol: elbv2.ApplicationProtocol.HTTPS,<br>      certificates: [acm.Certificate.fromCertificateArn(this, &#39;AlbCertificate&#39;, certificateArn)],<br>      defaultTargetGroups: [this.targetGroup],<br>    });<br><br>    new cdk.CfnOutput(this, &#39;AlbDnsName&#39;, {<br>      value: this.loadBalancer.loadBalancerDnsName,<br>      description: &#39;Public DNS name of the Application Load Balancer&#39;,<br>    });<br>  }<br>}</pre><ul><li>On <strong>lib/sg.ts</strong>: Addition of an <em>albSecurityGroup</em> (443 open to the internet). The EC2 security group&#39;s ingress rule now only accepts traffic <strong>from the ALB&#39;s security group</strong>, making the ALB is the only public entry point now.</li></ul><pre>import { Construct } from &#39;constructs&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br><br>export interface SecurityGroupsProps {<br>  vpc: ec2.IVpc;<br>}<br><br>export class SecurityGroups extends Construct {<br>  public readonly albSecurityGroup: ec2.SecurityGroup;<br>  public readonly ec2SecurityGroup: ec2.SecurityGroup;<br>  public readonly rdsSecurityGroup: ec2.SecurityGroup;<br><br>  constructor(scope: Construct, id: string, props: SecurityGroupsProps) {<br>    super(scope, id);<br><br>    // Security Group for the ALB (public-facing HTTPS entry point)<br>    this.albSecurityGroup = new ec2.SecurityGroup(this, &#39;AlbSecurityGroup&#39;, {<br>      vpc: props.vpc,<br>      allowAllOutbound: true,<br>      description: &#39;Security group for the Application Load Balancer&#39;,<br>    });<br>    this.albSecurityGroup.addIngressRule(<br>      ec2.Peer.anyIpv4(),<br>      ec2.Port.tcp(443),<br>      &#39;Allow HTTPS from the internet&#39;,<br>    );<br><br>    // Security Group for EC2 (Allows App Traffic only from the ALB)<br>    this.ec2SecurityGroup = new ec2.SecurityGroup(this, &#39;EC2SecurityGroup&#39;, {<br>      vpc: props.vpc,<br>      allowAllOutbound: true,<br>      description: &#39;Security group for EC2 instances&#39;,<br>    });<br>    // SSH access is intentionally not opened here — the instances have the SSM managed<br>    // policy and are reached via Session Manager instead of a public port 22.<br>    // this.ec2SecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), &#39;Allow SSH&#39;);<br><br>    // Traffic now arrives via the ALB, not directly from the internet, so we scope<br>    // this down from anyIpv4() to only the ALB&#39;s security group.<br>    this.ec2SecurityGroup.addIngressRule(<br>      this.albSecurityGroup,<br>      ec2.Port.tcp(443),<br>      &#39;Allow HTTPS from ALB&#39;,<br>    );<br><br>    // Security Group for RDS (Allows traffic from EC2)<br>    this.rdsSecurityGroup = new ec2.SecurityGroup(this, &#39;RDSSecurityGroup&#39;, {<br>      vpc: props.vpc,<br>      allowAllOutbound: true,<br>      description: &#39;Security group for RDS instance&#39;,<br>    });<br>    this.rdsSecurityGroup.addIngressRule(<br>      this.ec2SecurityGroup,<br>      ec2.Port.tcp(3306),<br>      &#39;Allow MySQL from EC2&#39;,<br>    );<br>  }<br>}</pre><ul><li>On <strong>lib/ec2-stack.ts</strong>: implement an <em>AutoScalingGroup</em> (min 2 / max 4, spread across both AZs by CDK automatically since the VPC has 2 AZs), attached to the ALB&#39;s target group. RDS and IAM role are unchanged.</li></ul><pre>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import * as ec2 from &#39;aws-cdk-lib/aws-ec2&#39;;<br>import * as autoscaling from &#39;aws-cdk-lib/aws-autoscaling&#39;;<br>import * as rds from &#39;aws-cdk-lib/aws-rds&#39;;<br>import { SecurityGroups } from &#39;./sg&#39;;<br>import { Ec2IamRole } from &#39;./iam&#39;;<br>import { LoadBalancer } from &#39;./alb&#39;;<br><br>export interface Ec2StackProps extends cdk.StackProps {<br>  vpc: ec2.IVpc;<br>  certificateArn: string;<br>}<br><br>export class Ec2Stack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props: Ec2StackProps) {<br>    super(scope, id, props);<br><br>    const { vpc, certificateArn } = props;<br><br>    // Security groups (ALB + EC2 + RDS)<br>    const { albSecurityGroup, ec2SecurityGroup, rdsSecurityGroup } = new SecurityGroups(<br>      this,<br>      &#39;SecurityGroups&#39;,<br>      { vpc },<br>    );<br><br>    // IAM role for EC2<br>    const { role: ec2Role } = new Ec2IamRole(this, &#39;Ec2IamRole&#39;);<br><br>    // Application Load Balancer — terminates public HTTPS, re-encrypts to instances<br>    const { targetGroup } = new LoadBalancer(this, &#39;LoadBalancer&#39;, {<br>      vpc,<br>      albSecurityGroup,<br>      certificateArn,<br>    });<br><br>    // Auto Scaling Group spanning both AZs in the public subnets (replaces the<br>    // single ec2.Instance so both AZs are actually used for HA)<br>    const asg = new autoscaling.AutoScalingGroup(this, &#39;MigrationAsg&#39;, {<br>      vpc,<br>      vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },<br>      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),<br>      machineImage: ec2.MachineImage.latestAmazonLinux2023(),<br>      securityGroup: ec2SecurityGroup,<br>      role: ec2Role,<br>      minCapacity: 2,<br>      maxCapacity: 4,<br>      desiredCapacity: 2,<br>    });<br><br>    asg.attachToApplicationTargetGroup(targetGroup);<br><br>    // Create RDS Instance in Private Subnet<br>    new rds.DatabaseInstance(this, &#39;MigrationRDS&#39;, {<br>      engine: rds.DatabaseInstanceEngine.mysql({ version: rds.MysqlEngineVersion.VER_8_0 }),<br>      vpc,<br>      vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },<br>      securityGroups: [rdsSecurityGroup],<br>      instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO),<br>      allocatedStorage: 20,<br>      storageEncrypted: true, // encrypts data at rest per TechHealth security requirements<br>      multiAz: true, // note: doubles RDS cost — confirm this tradeoff is intentional<br>      removalPolicy: cdk.RemovalPolicy.DESTROY, // WARNING: Deletes DB on stack removal<br>    });<br>  }<br>}</pre><ul><li>On <strong>lib/infrastructure.ts:</strong> additional line that passes a new <em>certificateArn </em>prop through to <em>Ec2Stack</em>.</li></ul><pre>#!/usr/bin/env node<br>import * as cdk from &#39;aws-cdk-lib/core&#39;;<br>import { InfrastructureStack } from &#39;../lib/infrastructure-stack&#39;;<br>import { Ec2Stack } from &#39;../lib/ec2-stack&#39;;<br><br>const app = new cdk.App();<br>const vpcStack = new InfrastructureStack(app, &#39;InfrastructureStack&#39;, {<br><br>});<br><br>new Ec2Stack(app, &#39;EC2Stack&#39;, {<br>  vpc: vpcStack.vpc, // Pass the VPC from the InfrastructureStack to the EC2Stack<br>  // Replace with an ACM certificate ARN that is already issued &amp; DNS-validated<br>  // in the same region as this stack.<br>  certificateArn: &#39;arn:aws:acm:us-east-2:REPLACE-WITH-YOUR-ACCOUNT-ID:certificate/REPLACE-ME&#39;,<br>});<br><br>app.synth();</pre><p>And last but not least, there are a few more things I might need to handle before this deploys:</p><ol><li><strong>ACM certificate: </strong>The ARN in <em>bin/infrastructure.ts</em> is not showing a real one on this blog post, but if you want to replicate this code make sure you have one issued and DNS-validated in the<strong> same region as the stack</strong>. Alternatively you could also implement a <em>route53.Certificate + ARecord</em> construct for a fully automated DNS-validated cert instead of a manual ARN. Decision on this TBD.</li><li><strong>TLS on the instances: </strong>Since the ALB re-encrypts to the backend, each EC2 instance needs to terminate HTTPS on port 443 (a self-signed cert is fine here since the ALB doesn’t validate the backend chain by default.</li></ol><p>Alright, this is all I have on this project. Keep iterating! Keep improving!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed741db8efd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>