<?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 Software Is Just Lego on Medium]]></title>
        <description><![CDATA[Stories by Software Is Just Lego on Medium]]></description>
        <link>https://medium.com/@softwareisjustlego?source=rss-f7ab4876748e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BR8a6I8Yi23u9fcjl2sYEg.jpeg</url>
            <title>Stories by Software Is Just Lego on Medium</title>
            <link>https://medium.com/@softwareisjustlego?source=rss-f7ab4876748e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:19:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@softwareisjustlego/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[Exploring Diabetes Readmission Rates with Databricks Dashboarding]]></title>
            <link>https://medium.com/@softwareisjustlego/exploring-diabetes-readmission-rates-with-databricks-dashboarding-3d603b18c31b?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d603b18c31b</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 11:36:28 GMT</pubDate>
            <atom:updated>2026-04-20T11:36:28.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0V6VcE1RtuNM1qq6vVeLQ.png" /><figcaption>The flow from raw ingestion → cleaned entities → analytics-ready aggregates</figcaption></figure><h3>Introduction</h3><p>I covered a simple <a href="https://medium.com/@softwareisjustlego/a-practical-databricks-dashboarding-workflow-3b6aa3b81736?postPublishedType=initial">zero-to-dashboard databricks workflow</a> in a prior article — we will now apply it to a very interesting use case — the <a href="https://archive.ics.uci.edu/dataset/296/diabetes+130-us+hospitals+for+years+1999-2008">UCI Diabetes dataset</a>.</p><p>The dataset represents 10 years of clinical care at 130 US hospitals and integrated delivery networks.</p><ul><li>diabetic_data.csv - Each row in this table is a hospital record of a patient diagnosed with diabetes, who underwent labs and medications and stayed for up to 14 days.</li><li>IDS_mapping.csv - Some categorical variables have been stored as IDs in the diabetic_data table. This table contains text values for those fields.</li></ul><p>Intended outcome — hypothetical scenario</p><p>The “target variable” (i.e variable of highest interest) in this dataset is named readmission_30d - this column in the diabetic_data table tells us whether a patient was readmitted to hospital within 30 days of their initial encounter.</p><p>Most uses of this dataset are centered around predicting readmission rates — but we want to focus on data modeling problems, not data science ones. So we will imagine the following hypothetical scenario: <em>We need to produce one dashboard to display a clear clinical story to senior stakeholders that would immediately highlight the largest risk factors for readmission within 30 days.</em></p><p>Note: We are not establishing causation here, only highlighting correlations that may warrant further clinical investigation.</p><p>As previously discussed, dashboarding is actually a data modeling problem, so let’s create a medallion architecture for the diabetes dataset.</p><h3>Bronze layer</h3><p>Once I downloaded the dataset, I realized it was too large to quickly preview on my mac (using the spacebar) because doing so requires loading the entire thing into memory.</p><p>Luckily it was easy to upload to the Unity Catalog using the UI. Databricks tried to infer the structure of the tables and was largely correct except for a small issue with the unusual structure IDS_mapping table. Nothing we can’t clean up though.</p><h3>Exploratory Data Analysis</h3><p>The next step is to quickly get familiar with the dataset using Jupyter notebooks running PySpark queries on our data. Bronze tables from Unity Catalog are directly accessible within Databricks notebooks and can be read into memory by providing a filesystem-like path.</p><p>In this step, we want to quickly answer a few key questions about our dataset to build up an inherent understanding of the data.</p><ul><li>What is the shape of the table (rows and columns)</li><li>Are there any columns with an unusually large number of NULL or missing values?</li><li>What does each column mean?</li><li>For categorical columns, how many distinct values are there?</li></ul><p>What I found was that the dataset contains information on &gt;71k patients across &gt;101k encounters (hospital admissions). There were 50 columns per patient — a patient number, 47 “features”, a readmission_30d column and a description . One immediate finding was that the description column was entirely NULL and could be dropped early, reducing noise in downstream transformations.</p><p>Understanding the column names was a little more tedious:</p><ul><li>Most of them, such as age, race, gender were self explanatory</li><li>A few columns required cross referencing across tables — e.g discharge_disposition_id</li><li>The UCI dataset contained a description of each column, handy for esoteric ones like max_glu_serum</li><li>Others required cross-referencing against online sources, such as diag_1 : these are ICD9 Codes: <a href="https://en.wikipedia.org/wiki/List_of_ICD-9_codes_240%E2%80%93279:_endocrine,_nutritional_and_metabolic_diseases,_and_immunity_disorders">https://en.wikipedia.org/wiki/List_of_ICD-9_codes_240–279:_endocrine,_nutritional_and_metabolic_diseases,_and_immunity_disorders</a></li></ul><h3>Working Backwards</h3><p>As described in the prior article, the key is to be laser-focused on the final output. We want one dashboard to highlight the largest risk factors for readmission within 30 days.</p><p>How do we know what the largest risk factors are? This is a hard question to answer without significant analysis investigating the causative link between factors and readmission rates. In the absence of time, let’s assume that we have already performed this analysis and found the five strongest indicators of readmission.</p><p>Combining these with high-level summary statistics, we arrive at 7 charts:</p><ol><li>Dataset overview: Total patients, total encounters, average length of stay, overall readmission rate (&lt; 30d)</li><li>Readmission distribution: No vs &lt; 30 vs &gt;30</li><li>Readmission by primary diagnosis</li><li>Readmission by length of stay</li><li>Readmission by admission type</li><li>Readmission by discharge disposition</li><li>Readmission by age</li></ol><p>Each chart is intentionally designed to answer a single stakeholder question (e.g. “Which discharge outcomes are most associated with readmission?”), which prevents overloading the dashboard.</p><h3>Gold Layer Tables</h3><p>Each of these above charts will be backed by one Gold layer table, which we will design to be as “ready for charting” as possible. Here is the schema of each Gold layer table:</p><pre>1. Dataset Overview: healthcare.gold.readmission_summary<br>total_patients              BIGINT<br>total_encounters            BIGINT<br>avg_length_of_stay          DOUBLE<br>readmission_rate_30d        DOUBLE<br><br>2. Readmission distribution: healthcare.gold.readmission_distribution<br>readmitted                  STRING   -- values: &#39;NO&#39;, &#39;&lt;30&#39;, &#39;&gt;30&#39;<br>total_cases                 BIGINT<br>percentage                  DOUBLE<br><br>3. Readmission by Primary Diagnosis: healthcare.gold.readmission_by_diagnosis<br>diag_1                      STRING<br>total_cases                 BIGINT<br>readmitted_cases            BIGINT<br>readmission_rate            DOUBLE<br><br>4. Readmission by Length of Stay: healthcare.gold.readmission_by_los<br>los_bucket                  STRING   -- &#39;1-3 days&#39;, &#39;4-7 days&#39;, &#39;8+ days&#39;<br>total_cases                 BIGINT<br>readmitted_cases            BIGINT<br>readmission_rate            DOUBLE<br><br>5. Readmission by Admission Type: healthcare.gold.readmission_by_admission_type<br>admission_type              STRING   -- &#39;Emergency&#39;, &#39;Urgent&#39;, etc.<br>total_cases                 BIGINT<br>readmitted_cases            BIGINT<br>readmission_rate            DOUBLE<br><br>6. Readmission by Discharge Disposition: healthcare.gold.readmission_by_discharge<br>discharge_disposition       STRING   -- &#39;Home&#39;, &#39;Rehab&#39;, etc.<br>total_cases                 BIGINT<br>readmitted_cases            BIGINT<br>readmission_rate            DOUBLE<br><br>7. Readmission by Age: healthcare.gold.readmission_by_age<br>age_bucket                  STRING   -- e.g. &#39;[0-10)&#39;, &#39;[10-20)&#39;, etc.<br>total_cases                 BIGINT<br>readmitted_cases            BIGINT<br>readmission_rate            DOUBLE</pre><h3>Silver Layer Schema</h3><p>We can design our Silver layer table such that it contains the minimal cleaned dataset required to power all downstream aggregations — i.e one row per patient encounter with just the columns we are interested in.</p><pre>Patient encounters: healthcare.silver.patient_encounters<br><br>patient_id                  STRING<br>encounter_id                STRING<br>age                         STRING<br>time_in_hospital            INT<br>readmitted                  STRING   -- &#39;NO&#39;, &#39;&lt;30&#39;, &#39;&gt;30&#39;<br>diag_1                      STRING<br>admission_type_id           INT<br>discharge_disposition_id    INT</pre><h3>Transformations for the Silver and Gold layers</h3><p>For this quick PoC workflow, I used a databricks hosted Jupyter notebook with PySpark to create the silver table, and simple SQL scripts to create the gold. A production setup would probably use databricks Jobs or Pipelines to constalty refresh data in these tables and perform transformations with observability built in.</p><p>A couple of SQL patterns emerged that were useful to observe:</p><ul><li>readmission_rate was computed by assigning an integer value of 1 where readmitted was &lt;30 and 0 otherwise. Then readmission_rate calculated with CAST(SUM(CASE WHEN readmitted = &#39;&lt;30&#39; THEN 1 ELSE 0 END) AS DOUBLE) / CAST(COUNT(*) AS DOUBLE) AS readmission_rate</li><li>A continuous variable like length of stay can be discretized using buckets. A new column called los_bucket was created using conditional logic:</li></ul><pre>WHEN time_in_hospital BETWEEN 1 AND 3 THEN &#39;1-3 days&#39;      <br>WHEN time_in_hospital BETWEEN 4 AND 7 THEN &#39;4-7 days&#39;       <br>ELSE &#39;8+ days&#39;     <br>END AS los_bucket</pre><h3>Dashboarding</h3><p>Working with the Databricks AI/BI dashboard UI is quite straightforward — first select all the tables that you want to use as data sources, then start creating charts. Here’s what my final dashboard looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*VriLjbsRTp22bhhwXy9nUA.png" /><figcaption>It’s a start..</figcaption></figure><p>One really useful feature was the ability to run SQL queries on the gold tables before rendering charts. This was helpful to reduce the amount of “noise” in the chart — e.g the number of categorical variables plotted on the x axis.For example, in the “readmission by diagnosis” chart, filtering to diagnoses with ≥3000 cases and ≥8% readmission rate reduced noise and surfaced a clear outlier: ICD-9 code 426 (conduction disorders), with ~14% readmission.</p><p>The experience of creating a chart via the UI was smooth and easy — I can see how BI analysts would be able to come up with something insightful quickly using databricks.</p><p>There are a couple of drawbacks though:</p><ol><li>Smaller variety of charts and less customizability compared to Metabase, another BI tool I have personal experience with</li><li>Not publicly shareable</li></ol><h3>Insights and Conclusion</h3><p>That brings us to the end of our quick experiment with databricks and this dataset. It was a nice break from the usually cloud and Linux heavy content, and I come out with a few interesting takeaways:</p><ul><li>This exercise was my introduction to both the databricks environment as well as healthcare datasets. Working with healthcare data is interesting because there is so much context to learn about — one small example of this was the <a href="https://en.wikipedia.org/wiki/List_of_ICD-9_codes">ICD9 codes</a>. In hindsight of course it makes sense to organize and codify the various types of diagnoses, but it’s not something the average layperson would be aware of.</li><li>Interestingly, many intuitive factors (e.g. age) showed weaker correlation with readmission than expected, while discharge disposition and certain diagnoses stood out more clearly.</li></ul><p>That’s it for this article — in the next one we will shift gears from analysis back to engineering and shed some light on how to leverage Cursor Agents + Databricks Skills and Databricks Asset Bundles to automate most of this work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d603b18c31b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Databricks Dashboarding Workflow]]></title>
            <link>https://medium.com/@softwareisjustlego/a-practical-databricks-dashboarding-workflow-3b6aa3b81736?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b6aa3b81736</guid>
            <category><![CDATA[databricks-dashboard]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[tech-consulting]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-modeling]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 14:39:16 GMT</pubDate>
            <atom:updated>2026-04-18T14:39:16.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkIy2c3VCH5paZcQGZ1hiw.png" /></figure><h3>About Databricks</h3><p>Databricks is an all-in-one data platform, built by the founders of Apache Spark. It combines storage, compute, and analytics into a single environment, allowing you to go from raw data to dashboards without managing infrastructure.</p><p>Having previously built and deployed data pipelines from scratch, I found this “no-infrastructure” approach to data engineering both efficient and refreshing.</p><h3>The Unity Catalog</h3><p>This is where all your data lives in Databricks.</p><p>Data is organized into three levels: Catalog → Schema → Table.</p><ul><li>Catalog: top-level container</li><li>Schema: logical grouping (similar to a database)</li><li>Table: where the actual data is stored</li></ul><p>This is enough to get started. The official Databricks Unity Catalog documentation goes deeper, but is mostly focused on governance and permissions.</p><h3>Exploration and Transformations</h3><p>Once data is in the catalog (easily done via the UI), Databricks provides two main ways to work with it:</p><ul><li><strong>Notebooks</strong> (Python / PySpark / SQL)</li><li><strong>SQL Editor</strong></li></ul><p>These are used to explore schema, validate data, generate summary statistics and test out transformations.</p><p>After exploration, transformations can be implemented using SQL queries or notebooks. These transformations write results back as new tables in the catalog. For production workflows, Databricks also supports jobs and pipelines to make these transformations repeatable and scheduled.</p><h3>Medallion Architecture</h3><p>A core design pattern in Databricks is the Medallion Architecture: Bronze → Silver → Gold. Here’s what each layer represents:</p><ul><li>Bronze: raw ingested data</li><li>Silver: cleaned, structured data</li><li>Gold: aggregated, business-ready data</li></ul><p>The idea is to incrementally improve the quality and specificity of a dataset as it moves through the layers. The final layer (gold) contains only the data required by business analysts, operational or executive teams. In practice, layers usually map to schemas (a collection of tables).</p><p>From online sources, the recommended approach is to have dashboards query only the gold tables. This keeps analytics simple and avoids exposing raw or inconsistent data.</p><h3>Dashboarding</h3><p>Once the necessary tables Gold tables are setup, dashboards can be built using the Databricks SQL UI, which is quite basic but does the job.</p><p>Each chart on the dashboard has to be backed by an SQL query and reads from a (usually gold) table. Charts are tightly coupled to queries and tables.</p><p>This has a few implications:</p><ul><li>dashboards are easy to build once data is modeled correctly</li><li>they are harder to generate programmatically</li><li>exported Dashboard JSON objects depend on internal query and dataset references</li></ul><p>Dashboards can be shared within a Databricks workspace, but are not designed for public distribution.</p><h3>Conclusion</h3><p>The key takeaway here is that building dashboards on Databricks is primarily a data modeling problem. Once your data is structured correctly (Bronze → Silver → Gold), dashboards become trivial to create. This also means that we usually need to work backwards from the dashboard — i.e first ask yourself what you want to chart, then figure out the Gold and Silver tables, then write the transformations. Easy peasy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b6aa3b81736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform lifecycle meta- argument]]></title>
            <link>https://medium.com/@softwareisjustlego/terraform-lifecycle-meta-argument-92068c4b973a?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/92068c4b973a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 14:11:56 GMT</pubDate>
            <atom:updated>2026-03-12T14:11:56.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Super important meta argument for production.</p><h3>The What and the Why</h3><p>Terraform manages resources through a lifecycle of creation, update, and destruction. When a resource must be replaced, Terraform typically destroys the existing resource before creating the new one.</p><p>But we don’t always want to play by these rules. In fact, there are three specific problems that this basic lifecycle introduces, which we can mitigate with the lifecycle meta-argument. Let’s get into it.</p><h3>1. Downtime</h3><p>If a resource is serving production traffic, we don’t want it to be deleted before the new one is created. Ideally, we want the new resource to be created before the old one is destroyed.</p><pre>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami           = &quot;ami-123&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  lifecycle {<br>      create_before_destroy = true<br>    }<br>}</pre><p>This ensures that terraform creates the new instance first, then destroys the old one. This option is commonly used for EC2 instances, load balancers and DNS targets.</p><h3>2. Accidental deletion</h3><p>Some resources should never be accidentally deleted. For example:</p><pre>resource &quot;aws_db_instance&quot; &quot;prod&quot; {<br>  identifier = &quot;prod-db&quot;<br>  lifecycle {<br>      prevent_destroy = true<br>    }<br>}</pre><p>terraform apply will fail if the user attempts to destroy this database.</p><p>In case the production database actually needs to be destroyed, two rounds of apply are required — the first would remove the lifecycle block and the second would destroy the database.</p><h3>3. Unnecessary drift correction</h3><p>Sometimes infrastructure is modified outside terraform (e.g manually, through a cloud console UI) and we don’t want terraform to revert those changes or recreate resources unnecessarily. For example if someone manually adds a couple of tags to an EC2 instance, we don’t want terraform to update the instance (and undo the additional tagging) later on.</p><pre>resource &quot;aws_instance&quot; &quot;app&quot; {<br>  ami = &quot;ami-123&quot;<br>  lifecycle {<br>      ignore_changes = [tags]<br>    }<br>}</pre><p>Some other EC2 attributes we <strong>might</strong> want to ignore_changes for (though this is very situationally dependent):</p><ul><li>user_data (if it is manually updated or templated elsewhere)</li><li>ebs_block_device (if volume sizes are dynamically modified after launch)</li></ul><p>In practice though, ignore_changes is most commonly used for attributes like tags that may be modified by external automation or cloud tooling. If only terraform manages an attribute, we don’t usually want to ignore changes to it.</p><h3>Conclusion</h3><p>The lifecycle block gives us some flexibility in handling resource creation/destruction. Another useful example not mentioned in this article is replace_triggered_by, which allows us to create “event-driven” infrastructure architectures such that, for example, an EC2 instance is redeployed when a launch template resource changes.</p><p>Catch you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92068c4b973a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform meta-arguments]]></title>
            <link>https://medium.com/@softwareisjustlego/terraform-meta-arguments-20df1900f5e3?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20df1900f5e3</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 13:40:09 GMT</pubDate>
            <atom:updated>2026-03-12T13:40:09.087Z</atom:updated>
            <content:encoded><![CDATA[<p>The three most important ones: count, for_each, depends_on.</p><h3>The What and the Why</h3><p>Meta-arguments are special arguments that all terraform resources support, independent of provider. They control how terraform creates or manages resources, instead of configuring resources themselves.</p><p>Why? Meta-arguments just make your life easier. An example of this would be when you want terraform to create multiple copies of a resource. Why declare the same resource three times when you can use a meta argument to automate this for you?</p><p>Here are the 3 most commonly used ones.</p><h3>count</h3><p>The count meta-argument creates identical copies of resources. The index property of the count argument index of the current resource.</p><pre>module &quot;ec2&quot; {<br>  count         = 3<br>  name = &quot;demo_instance_${count.index}&quot;<br>  ami           = &quot;ami-123&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  ...<br>}</pre><p>The above definition will create 3 instances, each named demo_instance_0, demo_instance_1 and demo_instance_2.</p><p>In a previous article, I set up a terraform output that prints the IP address of the EC2 to screen. We need to update these outputs slightly because module.ec2 is now a list of objects, indexed by integer, instead of a single object. Now that we have 3 EC2 instances, lets update the output command to now return a map using a for expression:</p><pre>output &quot;ec2_public_ips&quot; {<br>    description = &quot;Public IP of each EC2 instance&quot;<br>    value = { for i, ip in module.ec2[*].public_ip : &quot;instance_${i}&quot; =&gt; ip }<br>}<br><br>output &quot;ssh_commands&quot; {<br>    description = &quot;SSH command for each EC2 instance&quot;<br>    value = { for i, ip in module.ec2[*].public_ip : &quot;instance_${i}&quot; =&gt; &quot;ssh -i ~/.ssh/aws-priv-key.pem ec2-user@${ip}&quot; }<br>}</pre><p>The [*] is called a splat - it returns a collection of objects (only works when the collection is indexed by an integer).</p><h3>for_each</h3><p>for_each allows us to iterate over collections - kind of similar to what we did with the value map in the output above. for_each is best used when resources have distinct identities. Here’s an example:</p><pre>module &quot;ec2&quot; {<br>  for_each = toset([&quot;app_instance&quot;, &quot;web_instance&quot;, &quot;db_instance&quot;])<br>  name = each.value<br>  ami           = &quot;ami-123&quot;<br>  instance_type = &quot;t2.micro&quot;<br>}</pre><p>Note, the [*] splat operator no longer works here, because module.ec2 is now a map indexed by <em>string</em>, not integers. We now iterate through this like a regular map:</p><pre>output &quot;ec2_public_ips&quot; {<br>    description = &quot;Public IP of each EC2 instance&quot;<br>    value = { for name, instance in module.ec2 : name =&gt; instance.public_ip }<br>}<br>output &quot;ssh_commands&quot; {<br>    description = &quot;SSH command for each EC2 instance&quot;<br>    value = { for name, instance in module.ec2 : name =&gt; &quot;ssh -i ~/.ssh/aws-priv-key.pem ec2-user@${instance.public_ip}&quot; }<br>}</pre><p>This produces the following output:</p><pre>ec2_public_ips = {<br>      app_instance = (known after apply)<br>      db_instance  = (known after apply)<br>      web_instance = (known after apply)<br>    }</pre><p>for_each is sometimes preferred because it produces resources that are keyed by meaningful names instead of arbitrary integers, giving them distinct identities. count is preferred when we want to instantiate identical resources.</p><h3>depends_on</h3><p>Terraform is usually good at inferring dependencies between resources and instantiating them in the correct order, except for some edge cases. Two examples of such cases:</p><ol><li>Hidden dependency — Resource B depends on resource A, but it’s not explicitly called out in the configuration so terraform tries to create them both in parallel. Example:</li></ol><pre>resource &quot;aws_s3_bucket&quot; &quot;logs&quot; {<br>  bucket = &quot;my-demo-bucket-123&quot;<br>}<br>resource &quot;aws_s3_bucket_policy&quot; &quot;logs_policy&quot; {<br>  bucket = &quot;my-demo-bucket-123&quot;<br>  policy = jsonencode({...})<br>}</pre><p>2. Propagation delay — Terraform creates an IAM role and a few seconds later tries to attach it to an EC2, but AWS hasn’t finished creating the role yet.</p><p>In both cases, adding a depends_on makes the dependency explicit and forces terraform to create one resource before another. In the first example, this would look like adding the attribute depends_on = [aws_s3_bucket.logs] to the bucket policy resource.</p><h3>Conclusion</h3><p>That’s it for this one. TLDR: count and for_each help scale infrastructure, use for_each when you need to uniquely identify resources, and depends_on handles the rare cases where Terraform cannot infer dependencies automatically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20df1900f5e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform templating]]></title>
            <link>https://medium.com/@softwareisjustlego/terraform-templating-897fc9130bc1?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/897fc9130bc1</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[templating]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 04:36:11 GMT</pubDate>
            <atom:updated>2026-03-11T04:36:11.093Z</atom:updated>
            <content:encoded><![CDATA[<p>Improve IaC readability, maintainability.</p><h3>The what and the why</h3><p>In a previous article, I deployed an EC2 to AWS to demonstrate terraform modules. In the EC2 block, I defined a user_data script inline:</p><pre>module &quot;ec2&quot; {<br>    ...<br>    user_data = &lt;&lt;EOF<br>#!/bin/bash<br>SECRET_ARN=${data.aws_secretsmanager_secret.db_password.arn}<br>echo &quot;DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id $SECRET_ARN --query SecretString --output text)&quot; &gt;&gt; /etc/app.env<br>EOF<br>	...<br>}</pre><p>This works, but looks messy and becomes hard to understand or maintain as userdata scripts grow.</p><p>Terraform templating exists to solve this problem. It allows us to keep scripts and variables separate at runtime.</p><h3>Using terraform templating</h3><h4>.tfpl file</h4><p>We extract the inline contents of the userdata script into a new file named userdata.sh.tftpl. The .tftpl file extension is a useful convention that tells us this is a template file. This file only contains one variable to be substituted: the secret ARN.</p><pre>#!/bin/bash<br>echo &quot;DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id ${secret_arn} --query SecretString --output text)&quot; &gt;&gt; /etc/app.env</pre><p>As before, the ${} syntax implies the variable will be substituted by terraform.</p><h4>Usage with templatefile()</h4><pre>module &quot;ec2&quot; {<br>    ...<br>    user_data = templatefile(&quot;${path.module}/userdata.sh.tftpl&quot;, {<br>        secret_arn = data.aws_secretsmanager_secret.db_password.arn<br>    })<br>    ...<br>}</pre><p>Notes:</p><ul><li>$path.module is a builtin terraform expression that returns the path of the directory containing the current .tf file.</li><li>The templatefile function outputs a string, it doesn’t actually change the template file on the filesystem.</li><li>The first argument to templatefile is the file itself</li><li>The second argument is a map of variables</li></ul><h3>Conclusion</h3><p>Terraform templating is incredibly useful to make your IaC projects more readable and maintainable, especially when you want to configure infrastructure differently across environments. Use well!</p><p>Catch you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897fc9130bc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform secret management]]></title>
            <link>https://medium.com/@softwareisjustlego/terraform-secret-management-4949e9bfd9ca?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4949e9bfd9ca</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 03:17:40 GMT</pubDate>
            <atom:updated>2026-03-11T03:17:40.457Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR: Terraform should only provision access, applications should fetch at runtime.</p><h3>Why secrets are tricky in Terraform</h3><p>Let’s use a simplified example from a <a href="https://medium.com/@softwareisjustlego/terraform-variables-23b77c9a0f0b">previous article</a>: injecting a db_password into my EC2 user_data script.</p><p>Resource definition:</p><pre>module &quot;ec2&quot; {<br>		....<br>    user_data = &lt;&lt;EOF<br>#!/bin/bash<br>echo &quot;DB_PASSWORD=${var.db_password}&quot; &gt;&gt; /etc/app.env<br>EOF<br>		....<br>}</pre><p>When I run terraform plan and supply a password, the secret leaks in two places. First, in the CLI output:</p><pre># module.ec2.aws_instance.this[0] will be created<br>  + resource &quot;aws_instance&quot; &quot;this&quot; {<br>	  ...<br>      + user_data                            = &lt;&lt;-EOT<br>            #!/bin/bash<br>            echo &quot;DB_PASSWORD=password123&quot; &gt;&gt; /etc/app.env<br>        EOT<br>      ...<br>    }</pre><p>And next, once we run terraform apply and check the state file, we see:</p><pre>{<br>      &quot;module&quot;: &quot;module.ec2&quot;,<br>	...<br>        &quot;user_data&quot;: &quot;#!/bin/bash\\necho \\&quot;DB_PASSWORD=password123\\&quot; \\u003e\\u003e /etc/app.env\\n&quot;,<br>        &quot;user_data_base64&quot;: null,<br>        ...<br>}</pre><p>Even if the user data script was base64 encoded, we could simply decode it to recover the secret value.</p><h4>Using the sensitive attribute</h4><p>Adding sensitive=true to the variable can conceal it from terraform CLI output, but not the state file. Here’s the output of terraform plan:</p><pre># module.ec2.aws_instance.this[0] will be created<br>  + resource &quot;aws_instance&quot; &quot;this&quot; {<br>		  ...<br>      + user_data                            = (sensitive value)<br>      ...<br>    }</pre><p>But it’s still visible in the state file as before. Terraform needs to store the password in the state file so it can detect drift.</p><pre>{<br>  &quot;module&quot;: &quot;module.ec2&quot;,<br>    ...<br>    &quot;user_data&quot;: &quot;#!/bin/bash\\necho \\&quot;DB_PASSWORD=password123\\&quot; \\u003e\\u003e /etc/app.env\\n&quot;,<br>    &quot;user_data_base64&quot;: null,<br>    ...<br>}</pre><h4>So what?</h4><p>What’s the risk of accidentally exposing a secret in Terraform CLI or state? Anyone with access to logs, CI output, or the Terraform state backend could retrieve the secret.</p><h3>2 possible solutions</h3><p>We want to hide the secret value from both terraform plan output as well as the state file. There are 2 ways to do this, both involving the AWS Secrets manager. TLDR: Method 2 is recommended.</p><h4>Method 1 — Terraform reads the secret and injects it</h4><ol><li>Store the secret in AWS Secrets Manager (usually manually).</li><li>Terraform reads the secret value using a <strong>data source</strong>.</li><li>Terraform passes the value into user_data.</li></ol><p>Example:</p><pre>data &quot;aws_secretsmanager_secret&quot; &quot;db&quot; {<br>  name = &quot;prod/ec2/dbpassword&quot;<br>}</pre><pre>data &quot;aws_secretsmanager_secret_version&quot; &quot;db_password&quot; {<br>    secret_id = data.aws_secretsmanager_secret.db_password.id<br>}</pre><pre>resource &quot;aws_instance&quot; &quot;app&quot; {<br>  user_data = &lt;&lt;EOF<br>#!/bin/bash<br>echo &quot;DB_PASSWORD=${data.aws_secretsmanager_secret_version.db_password.secret_string}&quot; &gt;&gt; /etc/app.env<br>EOF<br>}</pre><p><strong>Consequences</strong></p><ul><li>The secret is obscured in terraform plan / CI logs (AWS secret versions are sensitive by default).</li><li>The secret is still visible in the state file.</li></ul><p>This method is easy but still leaks the secret value. To mitigate the risk of a human viewing the secret, we configure remote state storage (e.g to S3) with strict IAM policies — though it would still be readable by anyone with the right permissions.</p><h4>Method 2 — Runtime secret retrieval (recommended)</h4><ol><li>Store the secret in AWS Secrets Manager (usually manually).</li><li>Terraform passes only the secret ARN to userdata.</li><li>Grant the EC2 access to the secret using an IAM instance profile.</li><li>Refactor the userdata script to retrieve the secret at runtime.</li></ol><p>Example:</p><p>Terraform:</p><pre>resource &quot;aws_secretsmanager_secret&quot; &quot;db&quot; {<br>  name = &quot;prod/db/password&quot;<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ec2_secrets_role&quot; {<br>    name = &quot;ec2-secrets-manager-role&quot;<br>    assume_role_policy = jsonencode({<br>        Version = &quot;2012-10-17&quot;<br>        Statement = [{<br>            Effect    = &quot;Allow&quot;<br>            Principal = { Service = &quot;ec2.amazonaws.com&quot; }<br>            Action    = &quot;sts:AssumeRole&quot;<br>        }]<br>    })<br>}<br>resource &quot;aws_iam_role_policy&quot; &quot;ec2_read_db_secret&quot; {<br>    name = &quot;ec2-read-db-secret&quot;<br>    role = aws_iam_role.ec2_secrets_role.id<br>    policy = jsonencode({<br>        Version = &quot;2012-10-17&quot;<br>        Statement = [{<br>            Effect   = &quot;Allow&quot;<br>            Action   = &quot;secretsmanager:GetSecretValue&quot;<br>            Resource = data.aws_secretsmanager_secret.db.arn<br>        }]<br>    })<br>}<br>resource &quot;aws_iam_instance_profile&quot; &quot;ec2_secrets_profile&quot; {<br>    name = &quot;ec2-secrets-manager-profile&quot;<br>    role = aws_iam_role.ec2_secrets_role.name<br>}<br>resource &quot;aws_instance&quot; &quot;app&quot; {<br> iam_instance_profile   = aws_iam_instance_profile.ec2_secrets_profile.name<br>  user_data = &lt;&lt;EOF<br>#!/bin/bash<br>SECRET_ARN=${data.aws_secretsmanager_secret.db.arn}<br>echo &quot;DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id $SECRET_ARN --query SecretString --output text)&quot; &gt;&gt; /etc/app.env<br>EOF<br>}</pre><p><strong>Consequences</strong></p><p>Terraform only stores the secret ARN. Since terraform never sees the secret value, it never appears in plan, state or logs. This is thus the preferred architecture.</p><h3>Conclusion</h3><p>The general pattern to remember for handling secrets in Terraform is that terraform provisions access to secrets and applications fetch them at runtime. (As opposed to Terraform fetching and injecting them.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4949e9bfd9ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Variables]]></title>
            <link>https://medium.com/@softwareisjustlego/terraform-variables-23b77c9a0f0b?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b77c9a0f0b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 16:38:47 GMT</pubDate>
            <atom:updated>2026-03-09T16:38:47.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Zero to one plus a couple of pro tips.</p><h3>The what and the why</h3><p>Terraform variables are input parameters that allow us to:</p><ol><li>Reuse the same code across environments with different values</li><li>Keep env-specific or mutable values out of the IaC files</li><li>Make modules configurable and portable across projects</li></ol><h3>Structure</h3><p>Variables in terraform are defined in blocks:</p><pre>variable &quot;instance_type&quot; {<br> description = &quot;EC2 instance family and size&quot;<br> type = string<br> default = &quot;t3.micro&quot;<br>}<br><br>variable &quot;open_ports&quot; {<br> description = &quot;EC2 ports to open&quot;<br> type = list(number)<br> default = [22, 443]<br>}</pre><h3>Data types</h3><p>These are the most commonly used attributes:</p><ul><li>type → data type</li><li>description → documentation</li><li>default → default value. If supplied, variable is optional.</li></ul><p>Terraform supports primitive types string, number, bool, collection types such as list(string), map(string) as well as a complex type known as object.</p><h3>Validation</h3><p>Terraform can enforce validations on input variables too — this is performed using a validation block and prevents invalid configurations from being applied. A variable can contain multiple validations if necessary.</p><pre>variable &quot;instance_type&quot; {<br>    type = string<br>    description = &quot;Instance type to use for the EC2 instance&quot;<br>    default = &quot;t3.micro&quot;<br><br>    validation {<br>        condition = length(var.instance_type) &gt; 0<br>        error_message = &quot;Instance type must be provided and cannot be empty&quot;<br>    }<br><br>    validation {<br>        condition = contains([&quot;t3.micro&quot;, &quot;t3.small&quot;], var.instance_type)<br>        error_message = &quot;Instance type must be one of the following: t3.micro, t3.small&quot;<br>    }<br>}</pre><h3>Supplying variable values</h3><p>There are a few ways to supply values to your terraform variables. In my personal order of preference:</p><h4>1. tfvars files</h4><p>Variables can be stored in .tfvars files:</p><pre>instance_type = &quot;t3.micro&quot;<br>region = &quot;ap-southeast-1&quot;</pre><p>Terraform automatically loads variables from terraform.tfvars and *.auto.tfvars files.</p><h4>2. Environment variables</h4><p>Variables can also be set in the environment. If we want to set the region variable, we could do it as follows:</p><pre>export TF_VAR_region=ap-southeast-1</pre><h4>3. CLI</h4><p>My least favorite way to do it (because I like clean, simple commands) is via the CLI:</p><pre>terraform apply -var=&quot;instance_type=t3.micro&quot;</pre><h4>Variable precedence</h4><p>When variables are defined in multiple places, terraform resolves them in roughly this order:</p><ol><li>CLI -var</li><li>.tfvars files</li><li>Environment variables (TF_VAR_*)</li><li>Defaults in variable blocks</li></ol><h3>Tricks of the trade</h3><p>Here are some handy patterns for using variables in your terraform projects, above and beyond the basics.</p><h4>Sensitive variables</h4><p>Sometimes the output of a terraform plan command can leak sensitive information. Take this simplified example where I need to pass a db_password to my EC2 userdata script:</p><pre>module &quot;ec2&quot; {<br>    ...<br>    user_data = &lt;&lt;EOF<br>#!/bin/bash<br>echo &quot;DB_PASSWORD=${var.db_password}&quot; &gt;&gt; /etc/app.env<br>EOF<br>}</pre><p>Here’s the output of my terraform plan command, after supplying a value for db_password.</p><pre>...<br># module.ec2.aws_instance.this[0] will be created<br>  + resource &quot;aws_instance&quot; &quot;this&quot; {<br>      ...<br>      + user_data                            = &lt;&lt;-EOT<br>            #!/bin/bash<br>            echo &quot;DB_PASSWORD=password123&quot; &gt;&gt; /etc/app.env<br>        EOT<br>      ...</pre><p>We have now leaked my super sensitive database password. To reduce the risk of accidental exposure, we can mark the variable as sensitive:</p><pre>variable &quot;db_password&quot; {<br>  type      = string<br>  sensitive = true<br>}</pre><p>Terraform plan now looks like this:</p><pre>...<br># module.ec2.aws_instance.this[0] will be created<br>  + resource &quot;aws_instance&quot; &quot;this&quot; {<br>      ...<br>      + user_data                            = (sensitive value)<br>      ...</pre><p>The sensitive attribute hides secret values in terraform output (though it may still be visible in terraform state files).</p><h4>Structured configuration using object</h4><p>Group related variables together using terraform’s object type. Instead of two separate variables for instance_type and ami, combine them into a single ec2_instance variable:</p><pre>variable &quot;ec2_instance&quot; {<br>    type = object({<br>        ami = string<br>        instance_type = string<br>    })<br>    description = &quot;EC2 instance configuration&quot;<br>    default = {<br>        ami = &quot;ami-05fd46f12b86c4a6c&quot;<br>        instance_type = &quot;t3.micro&quot;<br>    }<br>}</pre><p>And reference them in configuration by “going through” the new variable:</p><pre>module &quot;ec2&quot; {<br>    ami           = var.ec2_instance.ami<br>    instance_type = var.ec2_instance.instance_type<br>}</pre><p>A couple of quick notes:</p><ul><li>Complex variables are usually supplied through the .tfvars files rather than the CLI (for readability)</li><li>Terraform can’t mark individual fields inside an object as sensitive. Secrets are usually passed as separate sensitive variables.</li></ul><h4>Using locals to derive values</h4><p>locals in terraform are named expressions used to compute reusable values inside a module, often derived from variables. They’re scoped to the module (“local” to the module) for easy reusability and better readability.</p><p>The simplest example of using locals is for tags:</p><pre>locals {<br>    tags = merge(var.tags, {<br>        Module = &quot;Network Basic with modules&quot;<br>    })<br>    instance_name = &quot;app-${var.environment}&quot;<br>}</pre><h4>Use different tfvars files across environments</h4><p>Finally, supply different .tfvars files to terraform plan and apply to simplify CI pipelines.</p><p>For example, if we have these variables:</p><pre>variable &quot;instance_type&quot; {<br>  type = string<br>}</pre><pre>variable &quot;environment&quot; {<br>  type = string<br>}</pre><p>And these .tfvars files:</p><p>dev.tfvars</p><pre>environment   = &quot;dev&quot;<br>instance_type = &quot;t3.micro&quot;</pre><p>prod.tfvars</p><pre>environment   = &quot;prod&quot;<br>instance_type = &quot;t3.large&quot;</pre><p>We can then run Terraform apply for each environment simply by changing the .tfvars file referenced:</p><pre>terraform apply -var-file=dev.tfvars<br>terraform apply -var-file=prod.tfvars</pre><h3>Conclusion</h3><p>Terraform variables make infrastructure flexible and environment-aware. Combined with modules, they allow Terraform code to be deployed across multiple environments with different inputs. Catch you in the next one, where I’ll be discussing Terraform Secrets as well as meta-arguments (count and for_each).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b77c9a0f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Up and Running with Terraform Modules]]></title>
            <link>https://medium.com/@softwareisjustlego/up-and-running-with-terraform-modules-8f2947f90975?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f2947f90975</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 06:07:07 GMT</pubDate>
            <atom:updated>2026-03-09T06:07:07.608Z</atom:updated>
            <content:encoded><![CDATA[<p>A key building block of Terraform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*Q5842eyjo_rrQphJcXCJLQ.png" /></figure><h3>The What and the Why</h3><p>Very simply, a module is a directory containing .tf files. When Terraform runs, the configuration in the working directory becomes the <strong>root module</strong> and any modules referenced with the module block becomes <strong>child modules</strong>. Modules are a core abstraction — terraform treats every configuration as a module.</p><p>On a high level, modules are like functions:</p><ul><li>They accept input variables</li><li>They produce outputs</li><li>They encapsulate infrastructure logic</li></ul><p>Why do we need modules? They solve three problems:</p><ol><li>Reuse of configuration</li><li>Composition of infrastructure (compose larger systems from smaller pieces)</li><li>Encapsulation</li></ol><h3>Quick demo</h3><h4>Directory Structure</h4><p>The root module orchestrates infrastructure by calling smaller child modules.</p><pre>aws-basic-network/<br>  main.tf             # root module — calls child modules<br>  variables.tf<br>  outputs.tf<br>  modules/<br>    networking/       # VPC, subnets, IGW, route tables<br>      main.tf<br>      variables.tf<br>      outputs.tf</pre><p>Notes:</p><ul><li>variables.tf define the inputs to a module. In many projects this includes a shared tags variable to ensure consistent tagging of all resources. Use merge() in the module to add more module- and resource- specific tags.</li><li>outputs.tf exposes variables required by subsequent modules</li></ul><h4>Module sources</h4><p>Modules can come from three sources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*FP8wD4M5uPXmwxVuQB_7rg.png" /></figure><h4>Modules used in the demo</h4><p>In this demo, I’ve used all three module sources:</p><ul><li>Local network module that defines my VPC, IGW, Subnet and Route tables</li><li>Remote security_group module imported from a git repo I own, which simply creates a security group to be attached to the EC2 instance</li><li>ec2 module from the public terraform registry: <a href="https://registry.terraform.io/modules/terraform-aws-modules/ec2-instance/aws/latest?tab=outputs">https://registry.terraform.io/modules/terraform-aws-modules/ec2-instance/aws/latest?tab=outputs</a></li></ul><h4>Wiring modules up</h4><p>These modules need to be “wired” together because some of them depends on the outputs others. For example, the EC2 instance needs a subnet ID and security group IDs. The security group needs a VPC ID. This naturally implies an order of module use — in my case, I instantiate the network module, followed by the security group one, then the ec2. To pass the outputs of the security group module to the EC2 one, simply set the security group ID to be an output of the security group module, and then reference it when passing to the EC2 module using vpc_security_group_ids = module.security_group.security_group_ids.</p><p>Terraform infers the correct infrastructure creation order from these references — i.e just because you define something earlier in the .tf file doesn’t mean it gets created first. It needs to be a dependency of something else in order for terraform to prioritize its creation.</p><h4>The role of terraform init</h4><p>The init command plays a special role when modules are involved. It will download all remote modules into a .terraform/modules directory so that terraform can use them for plan and apply.</p><p>This also means that when a remote module is updated — in my example, say I push a change to my security_group module on git — we need to run terraform init --upgrade . The --upgrade flag is crucial - it checks if a newer version of the module exists and redownloads it. If not specified, terraform will merely verify that the required module exists in the expected directory (.terraform/modules ) and won’t upgrade the module if it does.</p><h4>Demo outputs</h4><p>I set my main module up to output the IP address of the EC2 instance. Once I wired everything up, fixed a bug in my remote module and upgraded my dependencies, I hit terraform apply and received a nice looking public IP address to try SSH. Here’s what happened when I SSH’ed into the instance:</p><pre>,     #_<br>   ~\\_  ####_        Amazon Linux 2023<br>  ~~  \\_#####\\<br>  ~~     \\###|<br>  ~~       \\#/ ___   &lt;https://aws.amazon.com/linux/amazon-linux-2023&gt;<br>   ~~       V~&#39; &#39;-&gt;<br>    ~~~         /<br>      ~~._.   _/<br>         _/ _/<br>       _/m/&#39;<br>[ec2-user@ip-10-0-1-129 ~]$</pre><p>The beloved bird.</p><h3>Conclusion</h3><p>There we have it — a quick intro to terraform modules, one of the most useful features of the language. Catch you in the next one — a deeper dive into terraform variables.</p><h3>Code</h3><p>Root module, main.tf</p><pre>locals {<br>    tags = merge(var.tags, {<br>        Module = &quot;Network Basic with modules&quot;<br>    })<br>}<br><br>provider &quot;aws&quot; {<br>  region = var.region<br>}<br><br>module &quot;network&quot; {<br>    source = &quot;./modules/network&quot;<br>    tags = local.tags<br>    vpc_cidr = &quot;10.0.0.0/16&quot;<br>}<br><br>module &quot;security_group&quot; {<br>    source = &quot;git::https://example.git.repo.redacted&quot;<br>    tags = local.tags<br>    vpc_id = module.network.vpc_id<br><br>}<br><br>module &quot;ec2&quot; {<br>    source  = &quot;terraform-aws-modules/ec2-instance/aws&quot;<br>    version = &quot;6.3.0&quot;<br>    ami           = var.ami<br>    name = &quot;demo_instance&quot;<br>    create_eip = true<br>    instance_type = var.instance_type<br>    key_name      = &quot;For SSH&quot;<br>    monitoring    = true<br>    subnet_id     = module.network.subnet_id<br>    vpc_security_group_ids = [module.security_group.security_group_id]<br>    tags = merge(local.tags, {<br>        Module = &quot;EC2&quot;<br>    })<br>}</pre><p>Root module, outputs.tf</p><pre>output &quot;ec2_public_ip&quot; {<br>    description = &quot;Public IP of the EC2 instance&quot;<br>    value = module.ec2.public_ip<br>}<br><br>output &quot;ssh_command&quot; {<br>    description = &quot;Command to SSH into the EC2 instance&quot;<br>    value = &quot;ssh -i ~/.ssh/aws-priv-key.pem ec2-user@${module.ec2.public_ip}&quot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2947f90975" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained: cgroups]]></title>
            <link>https://medium.com/@softwareisjustlego/explained-cgroups-a92cd31ad2c6?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a92cd31ad2c6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cgroup]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 17:43:42 GMT</pubDate>
            <atom:updated>2026-03-05T17:43:42.584Z</atom:updated>
            <content:encoded><![CDATA[<p>How Linux keeps your VM from getting monopolized</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-vvjK2h8dFmg4q_zHFlJA.png" /></figure><h3>What it is</h3><p>A cgroup (control group) is a Linux Kernel feature that limits and isolates resources (CPU, Memory, I/O) that a process can use. To prevent one process from monopolizing all resources — this is crucial for the stability of shared machines.</p><h3>How it works</h3><p>Set configurations in a special directory, /sys/fs/cgroup, create a new subdirectory for each cgroup. Each directory contains 3 files:</p><pre>/sys/fs/cgroup/groupA<br>	|- cpu.max<br>	|- memory.max<br>	|- cgroup.procs<br>/sys/fs/cgroup/groupB<br>	|- cpu.max<br>	|- memory.max<br>	|- cgroup.procs</pre><p>The files in this directory are live kernel interfaces, meaning writing to them immediately updates Kernel data structures, we as administrators don’t need to run any “reload” commands. The kernel reads cgroup.procs to figure out which processes to apply the CPU and memory limits defined in the two .max files.</p><p>To say “the kernel” applies the limits is a slight simplification — in reality, the enforcement is delegated to different subsystems of the kernel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*sievIvEvPiiPr6pSBON64w.png" /></figure><h3>Demo</h3><p>To start, we spin up the usual Ubuntu VM on AWS.</p><p>We run one of my favorite commands: yes. This is a lovely command that just outputs the character y in an infinite loop. We run this in the background and silence outputs with yes &gt; /dev/null &amp; , then inspect process stats with top, which shows how incredibly CPU hungry our innocuous process is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sq7Hg-_fbgJpiG5gBPGjBQ.png" /></figure><p>Next, let’s create a simple cgroup to throttle our poor yes command.</p><pre>sudo mkdir /sys/fs/cgroup/mygroup<br>echo &quot;2478&quot; | sudo tee /sys/fs/cgroup/mygroup/cgroup.procs # PID of the yes process<br>echo &quot;20000 100000&quot; | sudo tee /sys/fs/cgroup/mygroup/cpu.max # &lt;quota&gt; &lt;period&gt; in microseconds<br>top</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cfipwKGTecMfKmWwB8cxQ.png" /></figure><p>The yes command now only uses 20% CPU!</p><h3>Conclusion</h3><p>That’s a quick demo of the core utility of the cgroup feature - enforcing resource budgets ensure that all processes get what they need. This turns out to be fundamental to how containers work, more on that later!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a92cd31ad2c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained: Linux PID Namespaces/process trees]]></title>
            <link>https://medium.com/@softwareisjustlego/explained-linux-pid-namespaces-process-trees-76fd746c3c10?source=rss-f7ab4876748e------2</link>
            <guid isPermaLink="false">https://medium.com/p/76fd746c3c10</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[process-management]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Software Is Just Lego]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 07:06:58 GMT</pubDate>
            <atom:updated>2026-03-02T07:06:58.842Z</atom:updated>
            <content:encoded><![CDATA[<p>The building blocks of containerization!</p><h3>The one liner definition</h3><p>A Linux Namespace is a kernel feature that gives a process its own isolated view of part of the operating system.</p><h3>The key is Linux process trees</h3><p>This is a parent-child hierarchy of processes on a Linux system. Every process, except for the first, is created by another process. The creator is the parent and the new process is a child. This relationship forms a tree.</p><p>The root of the tree is PID 1 — on most systems, that is systemd. The kernel starts systemd and everything else descends from under it.</p><p>A child process is created when a process calls fork() - the new process gets a PID, and the original process becomes a parent. The shell works this way too: when you type ls, the shell forks and executes it.</p><p>Let’s take a quick look at this in action. I use my favorite old terraform configs to spin up an Ubuntu EC2 and run a command that shows me the process tree. Here’s a snippet:</p><pre>ubuntu@ip-10-0-1-252:~$ ps -ef --forest<br>UID          PID    PPID  C STIME TTY          TIME CMD<br>root           2       0  0 05:33 ?        00:00:00 [kthreadd]<br>root           3       2  0 05:33 ?        00:00:00  \\_ [pool_workqueue_release]<br>root           4       2  0 05:33 ?        00:00:00  \\_ [kworker/R-rcu_g]<br>root           5       2  0 05:33 ?        00:00:00  \\_ [kworker/R-rcu_p]<br>													.......<br>root         655       1  0 05:33 ?        00:00:00 sshd: /usr/sbin/sshd -D -o AuthorizedKeysCommand /usr/share/ec2-instance-connect/eic_run_authorized_keys %u %f -o AuthorizedKeysCommandUser ec2-instance<br>root        1132     655  0 05:33 ?        00:00:00  \\_ sshd: ubuntu [priv]<br>ubuntu      1368    1132  0 05:34 ?        00:00:00      \\_ sshd: ubuntu@pts/0<br>ubuntu      1376    1368  0 05:34 pts/0    00:00:00          \\_ -bash<br>ubuntu      2656    1376  0 05:35 pts/0    00:00:00              \\_ ps -ef --forest<br>													........</pre><p>Truncated a few lines in the middle but the tree is very obviously visible. Most interestingly, sshd is listed as process 655, and it has spawned a number of child processes which end in ps -ef --forest — the exact command that I am running to view this tree.</p><p>Now let’s see what happens when we run an NGINX container:</p><pre>ubuntu@ip-10-0-1-252:~$ podman run -d --name nginx docker.io/library/nginx:latest<br>ubuntu@ip-10-0-1-252:~$ ps -ef --forest<br>ubuntu      2515       1  0 05:35 ?        00:00:00 podman<br>ubuntu      2624       1  0 05:35 pts/0    00:00:00 /usr/bin/slirp4netns --disable-host-loopback --mtu=65520 --enable-sandbox --enable-seccomp -c -e 3 -r 4 --netns-type=path /run/user/1000/netns/cni-c6da0<br>ubuntu      2627       1  0 05:35 ?        00:00:00 /usr/bin/conmon --api-version 1 -c a468e162ba306aeea5e48530293a37b5626a58353964d63c009b8cde7a5c10a8 -u a468e162ba306aeea5e48530293a37b5626a58353964d63c0<br>ubuntu      2630    2627  0 05:35 ?        00:00:00  \\_ nginx: master process nginx -g daemon off;<br>100100      2654    2630  0 05:35 ?        00:00:00      \\_ nginx: worker process<br>100100      2655    2630  0 05:35 ?        00:00:00      \\_ nginx: worker process</pre><p>We see conmon (explained in a <a href="https://medium.com/@softwareisjustlego/docker-vs-podman-1f5e1b84d967">prior post</a>) spawning a child nginx master process, which spawns worker processes.</p><p>Process trees are maintained by the kernel, and are the single source of truth for what exactly is running on the linux machine.</p><h3>The relationship between PID namespaces and the linux process tree</h3><p>A PID namespace is basically a <strong>view</strong> of the process tree, with its own PID numbering starting at a specific <strong>root</strong>.</p><p>The host namespace sees the entire process tree, because its root is PID 1 on the host.</p><p>In contrast, a new PID namespace basically isolates a branch of the tree and turns this subtree into its entire visible world. The root of this subtree is now PID 1 for the new namespace, even if it is PID 4003 for the host. An important caveat here — you can’t retrospectively move existing processes to a new namespace. The creation of a PID namespace will isolate a process and all of its future dependents.</p><p>Concretely, lets say we’re running an nginx container on our linux host. The host namespace might look like this:</p><pre>PID 1    systemd<br>|<br>|- PID 4501 nginx<br>		|- PID 4671 nginx worker<br>		|- PID 6089 nginx helper<br>|- PID 5026 bash</pre><p>But in the nginx PID namespace (nginx container), nginx is the root:</p><pre>PID 1 nginx<br>|- PID 2 worker process<br>|- PID 3 helper</pre><p>The nginx namespace does not see systemd, bash or other host processes. But the host can see anything.</p><h4><strong>Why all the fuss about PID 1?</strong></h4><p>As the root of the tree, PID 1 is responsible for some special things like dealing with oprphans/zombies (for another article). If it exits, the kernel terminates all other processes in that namespace. In the world of containers, PID 1 is your container’s entrypoint process.</p><p>So ultimately, PID namespaces are useful because:</p><ul><li>You can now have multiple PID 1s on your machine (1 per namespace)</li><li>Each namespace has its own root process</li><li>You can build isolated process trees</li></ul><h4>/proc</h4><p>The final missing piece of the puzzle is /proc, a virtual filesystem created by the linux kernel, scoped to each namespace. It doesn’t even exist on disk. ls /proc shows all running processes in the current namespace, and cat /proc/&lt;id&gt;/status displays metadata about a particular process.</p><h3>Quick demo</h3><p>For this demo, we’ll create a new PID namespace and inspect process trees and /proc inside and outside the namespace.</p><p>We start with an EC2 running Ubuntu. Quickly inspect the process tree and count the total number of processes:</p><pre>ubuntu@ip-10-0-1-252:~$ ps -ef --forest | head -10<br>UID          PID    PPID  C STIME TTY          TIME CMD<br>root           2       0  0 05:33 ?        00:00:00 [kthreadd]<br>root           3       2  0 05:33 ?        00:00:00  \\_ [pool_workqueue_release]<br>root           4       2  0 05:33 ?        00:00:00  \\_ [kworker/R-rcu_g]<br>root           5       2  0 05:33 ?        00:00:00  \\_ [kworker/R-rcu_p]<br>root           6       2  0 05:33 ?        00:00:00  \\_ [kworker/R-slub_]<br>root           7       2  0 05:33 ?        00:00:00  \\_ [kworker/R-netns]<br>root           8       2  0 05:33 ?        00:00:00  \\_ [kworker/0:0-cgroup_destroy]<br>root           9       2  0 05:33 ?        00:00:00  \\_ [kworker/0:0H-events_highpri]<br>root          11       2  0 05:33 ?        00:00:00  \\_ [kworker/u4:0-flush-259:0]</pre><pre>ubuntu@ip-10-0-1-252:~$ ls /proc | grep -E &#39;^[0-9]+&#39; | wc -l<br>107</pre><p>Then, we create a new PID namespace and start a bash process within the new namespace. Check the process tree and /proc :</p><pre>ubuntu@ip-10-0-1-252:~$ sudo unshare --fork --pid --mount-proc bash<br>root@ip-10-0-1-252:/home/ubuntu# ps -ef --forest<br>UID          PID    PPID  C STIME TTY          TIME CMD<br>root           1       0  0 06:40 pts/1    00:00:00 bash<br>root           8       1  0 06:40 pts/1    00:00:00 ps -ef --forest<br>root@ip-10-0-1-252:/home/ubuntu# ls /proc<br>1           18         [others]</pre><p>As expected, the process tree within the new namespace only shows the bash command (which we created the namespace with) as well as ps -ef , child of bash. /proc only shows 2 processes.</p><p>About the unshare command:</p><ul><li>unshare → userspace tool that asks the kernel to create a new namespace for the current process</li><li>— fork → make the child process (bash) PID 1 in the new namespace</li><li>— pid → tells the kernel to create a new pid namespace (as opposed to other types)</li><li>— mount-proc → mount a fresh /proc so it reflects only processes visible in the new PID namespace</li><li>bash → program to run in the new namespace (becomes PID 1)</li></ul><p>And finally, lets see the PID of the new bash command in the host namespace:</p><pre>ubuntu@ip-10-0-1-252:~$ ps -ef --forest | grep bash<br>UID          PID    PPID  C STIME TTY          TIME CMD<br>root         655       1  0 05:33 ?        00:00:00 sshd: /usr/sbin/sshd -D -o AuthorizedKeysCommand /usr/share/ec2-instance<br>root        1132     655  0 05:33 ?        00:00:00  \\_ sshd: ubuntu [priv]<br>ubuntu      1368    1132  0 05:34 ?        00:00:00  |   \\_ sshd: ubuntu@pts/0<br>ubuntu      1376    1368  0 05:34 pts/0    00:00:00  |       \\_ -bash<br>root        2775    1376  0 06:40 pts/0    00:00:00  |           \\_ sudo unshare --fork --pid --mount-proc bash<br>root        2776    2775  0 06:40 pts/1    00:00:00  |               \\_ sudo unshare --fork --pid --mount-proc bash<br>root        2777    2776  0 06:40 pts/1    00:00:00  |                   \\_ unshare --fork --pid --mount-proc bash<br>root        2778    2777  0 06:40 pts/1    00:00:00  |                       \\_ bash</pre><p>From the host namespace perspective, bash is PID 2778. Job done!</p><p>As a bonus, we can check active namespaces using lsns -t pid, which yields:</p><pre>NS TYPE NPROCS   PID USER   COMMAND<br>4026531836 pid       6  1156 ubuntu /lib/systemd/systemd --user</pre><h3>Conclusion</h3><p>We’ve peeled back the curtain slightly to understand a bit more about Linux. As always, we’ll stop here to avoid rabbit holes but PID namespaces are a really important concept in eventually understanding how containers work on a deeper level. Key takeaways are:</p><ol><li>The linux process tree is king — a single source of truth for the process hierarchy on the machine</li><li>PID namespaces offer a view of the process tree with renumbered PIDs and new roots</li><li>This is cruicial for process isolation on Linux</li></ol><p>Catch you on the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76fd746c3c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>