<?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 Emmanuel Mbagwu on Medium]]></title>
        <description><![CDATA[Stories by Emmanuel Mbagwu on Medium]]></description>
        <link>https://medium.com/@lilstex4good?source=rss-765a8e4dabc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SUI5HBksuAPYehpn8ugW0g.jpeg</url>
            <title>Stories by Emmanuel Mbagwu on Medium</title>
            <link>https://medium.com/@lilstex4good?source=rss-765a8e4dabc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:09:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lilstex4good/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[Part 6: Day-2 Operations: Updating Configuration and Secrets Safely]]></title>
            <link>https://medium.com/@lilstex4good/part-6-day-2-operations-updating-configuration-and-secrets-safely-f242bfd08190?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f242bfd08190</guid>
            <category><![CDATA[cicd-pipeline]]></category>
            <category><![CDATA[system-administrator]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 08:11:01 GMT</pubDate>
            <atom:updated>2026-11-23T08:11:01.538Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FU7KcS3-N0V08UmDWNk_Zw.png" /></figure><p>Parts 1 to 5 built and tuned the platform. The rest of the series covers what happens after launch: the routine work of keeping it running. This part starts with the most common request an operator gets: “Can you change this setting in production?”</p><p>Changing a value is easy. Changing it <strong>safely</strong> depends on knowing where the value lives, which source wins when two disagree, and when the running pods will actually see it.</p><h3>Three places a setting can live</h3><p>From Part 3, the pods get their settings from three sources:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57178c90f17d5d320da2c65ff978732/href">https://medium.com/media/c57178c90f17d5d320da2c65ff978732/href</a></iframe><p><strong>Precedence:</strong> environment variables from the ConfigMap and the Secret beat the same key in .env. So the first question for any change is: <em>which of the three owns this key?</em> If you change DB_HOST in .env, nothing happens, because the ConfigMap&#39;s DB_HOST wins. That&#39;s deliberate: it stops a .env copied from a staging server from pointing production at the wrong database.</p><h3>“What does the pod actually see?”</h3><p>When in doubt, ask a running pod. This is the final answer:</p><pre>export NS=myapp<br><br># The framework&#39;s own view of drivers and environment<br>kubectl exec -n $NS deploy/myapp-web -- php artisan about --only=drivers<br><br># One value that comes from the ConfigMap or Secret<br>kubectl exec -n $NS deploy/myapp-web -- printenv DB_HOST<br><br># One value from the .env file<br>kubectl exec -n $NS deploy/myapp-web -- grep &#39;^MAIL_FROM_ADDRESS=&#39; .env</pre><h3>Case 1: Change an application setting (the .env)</h3><p>Mail server, payment keys, app URL, third-party API keys. These are the everyday changes.</p><h3>Why the whole file is one secret</h3><p>The .env is stored in Key Vault as a single base64-encoded secret (app-dotenv-b64), not as dozens of separate secrets. That has three effects:</p><ul><li>The file never passes through Terraform, so it never lands in Terraform state.</li><li>Key Vault keeps every version with a timestamp, so “what changed last Tuesday?” has an answer.</li><li>The SecretProviderClass lists one object instead of one per key, so adding a key needs no manifest change.</li></ul><h3>The safe workflow</h3><pre>export KV=YOUR_KEY_VAULT<br>export NS=myapp<br>mkdir -p ~/secure/myapp &amp;&amp; chmod 700 ~/secure/myapp<br><br># 1. Download the current file, so you edit what production really runs<br>az keyvault secret show --vault-name &quot;$KV&quot; -n app-dotenv-b64 --query value -o tsv \<br>  | base64 -d &gt; ~/secure/myapp/prod.env<br>chmod 600 ~/secure/myapp/prod.env<br><br># 2. Sanity check: the download must contain the app key<br>grep -c &#39;^APP_KEY=base64:&#39; ~/secure/myapp/prod.env      # must print 1<br><br># 3. Edit<br>nano ~/secure/myapp/prod.env<br><br># 4. Upload (validates, warns, stores a new version)<br>./scripts/push-dotenv.sh &quot;$KV&quot; ~/secure/myapp/prod.env<br><br># 5. Restart so the pods load it<br>kubectl rollout restart deploy -n &quot;$NS&quot;<br>kubectl rollout status deploy/myapp-web -n &quot;$NS&quot;<br><br># 6. Verify<br>kubectl exec -n &quot;$NS&quot; deploy/myapp-web -- grep &#39;^MAIL_HOST=&#39; .envThe upload script</pre><p>Step 2 matters more than it looks. If $KV is empty (a new terminal where you forgot the export), the download fails, and the redirect leaves an <strong>empty</strong> file behind. Editing and uploading that empty file would wipe every setting. The check catches it before the edit.</p><h3>The upload script</h3><p>A short script makes the upload safe by default:</p><pre>#!/usr/bin/env bash<br># Uploads a .env to Key Vault as the base64 secret app-dotenv-b64.<br>set -euo pipefail<br><br>VAULT=&quot;${1:?usage: push-dotenv.sh &lt;key-vault-name&gt; &lt;path/to/prod.env&gt;}&quot;<br>FILE=&quot;${2:?usage: push-dotenv.sh &lt;key-vault-name&gt; &lt;path/to/prod.env&gt;}&quot;<br><br>[ -f &quot;$FILE&quot; ] || { echo &quot;no such file: $FILE&quot; &gt;&amp;2; exit 1; }<br><br># Refuse a file without an app key: every request would fail.<br>grep -Eq &#39;^APP_KEY=base64:.+&#39; &quot;$FILE&quot; || { echo &quot;$FILE has no APP_KEY&quot; &gt;&amp;2; exit 1; }<br><br># Warn about keys that Terraform overrides, so nobody wonders why a change had no effect.<br>for key in DB_HOST DB_DATABASE DB_USERNAME DB_PASSWORD CACHE_STORE QUEUE_CONNECTION \<br>           SESSION_DRIVER AZURE_STORAGE_CONNECTION_STRING TRUSTED_PROXIES LOG_LEVEL; do<br>  if grep -Eq &quot;^${key}=&quot; &quot;$FILE&quot;; then<br>    echo &quot;note: ${key} is overridden by Terraform-managed settings&quot; &gt;&amp;2<br>  fi<br>done<br><br>TMP=&quot;$(mktemp)&quot;<br>trap &#39;rm -f &quot;$TMP&quot;&#39; EXIT<br>base64 &lt; &quot;$FILE&quot; | tr -d &#39;\n&#39; &gt; &quot;$TMP&quot;<br><br>az keyvault secret set --vault-name &quot;$VAULT&quot; --name app-dotenv-b64 \<br>  --file &quot;$TMP&quot; --content-type &quot;application/x-dotenv;base64&quot; --output none<br><br>echo &quot;stored. Now run: kubectl rollout restart deploy -n myapp&quot;</pre><p>Two details in it:</p><ul><li><strong>tr -d &#39;\n&#39;</strong>: base64 Wraps lines at 76 characters on Linux. The secret must be one line, or the decode in the container produces garbage.</li><li><strong>A temporary file, removed on exit</strong>: the secret is never passed on the command line, where it would show in shell history and process listings.</li></ul><h3>Why the restart is required</h3><p>The CSI driver refreshes the mounted file within about two minutes, so the new .env reaches each pod&#39;s disk on its own. But the container entrypoint runs php artisan config:cache at start. The framework then reads its cached config, not the file. <strong>New values take effect only when a pod starts.</strong> kubectl rollout restart replaces the pods one at a time, with no downtime for the web tier.</p><h3>The one value you never change</h3><p>APP_KEY signs links that were already emailed to customers, and decrypts values already stored in the database. Changing it breaks both, permanently, for existing data. If it ever leaks, rotating it is a planned migration, not a .env edit.</p><h3>Doing it from the portal</h3><p>Possible, but easy to get wrong:</p><ol><li>Key Vault → <strong>Secrets</strong> → app-dotenv-b64 → current version → <strong>Show secret value</strong>.</li><li>Decode it on your own machine, never in an online tool, because it contains passwords.</li><li>Edit, re-encode <strong>as a single line</strong> (base64 -w0 prod.env on Linux), then <strong>New version</strong> → paste → <strong>Create</strong>.</li><li>Restart the pods (AKS → Workloads → Deployments → select all three → <strong>Restart</strong>).</li></ol><p>The command line version is safer, because the script validates the file before uploading.</p><h3>Case 2: Change an infrastructure-owned value</h3><p>Drivers, the database host, the log level, trusted proxies. These belong to Terraform, so they change in code:</p><pre># terraform/locals.tf<br>app_runtime_settings = {<br>  LOG_LEVEL = &quot;warning&quot;     # was &quot;info&quot;<br>  # ...<br>}</pre><p>Then:</p><ol><li>terraform plan. For a ConfigMap-only change, it shows <strong>no resource changes, only output changes</strong>.</li><li>terraform apply.</li><li>Get the new values to the pods, either by running a release, or straight away:</li></ol><pre>IMAGE_TAG=$(kubectl get deploy myapp-web -n myapp \<br>  -o jsonpath=&#39;{.spec.template.spec.containers[0].image}&#39; | sed &#39;s/.*://&#39;)<br>IMAGE_TAG=$IMAGE_TAG API_HOST=api.example.com TLS_CERT_NAME=api-tls ./k8s/render.sh<br>kubectl apply -f k8s/out/configmap.yaml<br>kubectl rollout restart deploy -n myapp<br>rm -rf k8s/out</pre><p>Using the <em>running</em> image tag means this restarts the same code with new settings, without deploying anything new by accident.</p><h3>Case 3: Rotate a generated password</h3><p>The database password and the storage connection string are generated by Terraform and stored in Key Vault. <strong>Don’t edit them by hand in Key Vault.</strong> Terraform would put the old value back on its next apply, and the pods would be out of step with the database.</p><p>Rotate through Terraform instead. For example, force a new database password:</p><pre>terraform -chdir=terraform apply -replace=&#39;module.mysql.random_password.admin&#39;</pre><p>The plan replaces the random password, updates the MySQL server’s admin password in place, and writes the new value to Key Vault. The CSI driver syncs it within about 2 minutes. Then restart the pods:</p><pre>kubectl rollout restart deploy -n myapp</pre><p>Between the database change and the pod restart, existing connections keep working, but new ones fail. Do it in a quiet period, and restart right after the apply.</p><h3>Who can read what</h3><p>Access to secrets is itself a setting, managed in Terraform:</p><ul><li><strong>Operators</strong> get <em>Key Vault Secrets Officer</em> (read and write).</li><li><strong>The cluster’s CSI identity</strong> gets <em>Key Vault Secrets User</em> (read-only), on that vault only.</li><li><strong>New team members</strong> are added to a list interraform.tfvars, not through the portal. A role granted in the portal is invisible to Terraform and gets forgotten when someone leaves.</li></ul><pre>key_vault_admin_principal_ids = [<br>  &quot;OPERATOR_OBJECT_ID&quot;,   # operator<br>  &quot;CI_OBJECT_ID&quot;,         # CI pipeline<br>]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f242bfd08190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 5: Halving the Azure Bill Without Losing Data]]></title>
            <link>https://medium.com/@lilstex4good/part-5-halving-the-azure-bill-without-losing-data-15ac50812a5b?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ac50812a5b</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[cloud-cost-management]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-03T08:01:02.767Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nhl2aTMdtoTE6mZtV8iYMQ.png" /></figure><p>The platform from Parts 1 to 4 worked well, and it cost about <strong>$405 a month</strong> for a system that would serve around 30 users in its first months. This part shows how we found where the money went, which cuts we made and what each one gave up, the one cut Azure would not let us make, and how the budget is tracked now. The result was about <strong>$205 a month</strong>, with the same application and no data lost.</p><h3>Step 1: Get real numbers, not estimates</h3><p>The original pricing calculator export said about $173 a month. The real bill was more than twice that. Calculators miss things: the AKS uptime SLA, the load balancer, public IPs, disks, log ingestion, and the second node the autoscaler adds.</p><h3>List prices from the Retail Prices API</h3><p>Azure publishes every price through a public API. No sign-in needed:</p><pre>curl -sG &quot;https://prices.azure.com/api/retail/prices&quot; \<br>  --data-urlencode &quot;\$filter=armRegionName eq &#39;southcentralus&#39; and armSkuName eq &#39;Standard_D2as_v7&#39; and priceType eq &#39;Consumption&#39;&quot; \<br>  | jq -r &#39;.Items[] | select(.productName | contains(&quot;Windows&quot;) | not) | &quot;\(.retailPrice)/h  \(.productName)  \(.skuName)&quot;&#39;</pre><p>Multiply hourly prices by 730 for a monthly figure.</p><h3>Actual charges from Cost Management</h3><p>The Consumption usage API returned no cost values for this billing account type. The Cost Management query API did:</p><pre>cat &gt; query.json &lt;&lt;&#39;EOF&#39;<br>{<br>  &quot;type&quot;: &quot;ActualCost&quot;,<br>  &quot;timeframe&quot;: &quot;MonthToDate&quot;,<br>  &quot;dataset&quot;: {<br>    &quot;granularity&quot;: &quot;None&quot;,<br>    &quot;aggregation&quot;: { &quot;totalCost&quot;: { &quot;name&quot;: &quot;Cost&quot;, &quot;function&quot;: &quot;Sum&quot; } },<br>    &quot;grouping&quot;: [<br>      { &quot;type&quot;: &quot;Dimension&quot;, &quot;name&quot;: &quot;MeterCategory&quot; },<br>      { &quot;type&quot;: &quot;Dimension&quot;, &quot;name&quot;: &quot;MeterSubcategory&quot; }<br>    ]<br>  }<br>}<br>EOF</pre><pre>az rest --method post \<br>  --url &quot;https://management.azure.com/subscriptions/YOUR_SUBSCRIPTION_ID/providers/Microsoft.CostManagement/query?api-version=2023-11-01&quot; \<br>  --body @query.json</pre><p>This API rate-limits aggressively. If you get a 429, wait a minute and retry rather than looping.</p><p>To scale a month-to-date figure, work out how many days the data actually covers, because it lags by up to a day. We used a resource billed at a fixed hourly rate as the clock: MySQL compute charges divided by its hourly price gave exactly 247 hours, or 10.3 days.</p><h3>Where the $405 went</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c7ef722935739c4b86fec3274fc64c/href">https://medium.com/media/f8c7ef722935739c4b86fec3274fc64c/href</a></iframe><p>Two lines were surprising. Log Analytics was the fourth highest cost (Part 4 explains why). And the load balancer, which the calculator priced at about $18, actually cost about $0.35, because it is charged mostly by data processed.</p><h3>Step 2: Find out why there are two nodes</h3><p>The single biggest line was compute, and the second node existed for one reason. It was not load:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17d52060e0e4cd29c2ba9a53c58c2234/href">https://medium.com/media/17d52060e0e4cd29c2ba9a53c58c2234/href</a></iframe><pre>kubectl top nodes<br>kubectl describe nodes | grep -A8 &quot;Allocated resources&quot;<br>kubectl get pods -A -o custom-columns=&#39;NS:.metadata.namespace,POD:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu&#39;</pre><p>The application&#39;s own pods requested only 275m in total. The rest was AKS add-ons: 1000m for the managed ingress, 450m for the log agent, about 700m for DNS, metrics, and webhooks, and about 530m of per-node system pods.</p><p>On one 2-vCPU node (about 1900m allocatable), these reservations add up to about 2800m, so they don&#39;t fit. That is why the autoscaler kept two nodes: the scheduler counts requests, not usage.</p><p>This shapes every node decision. <strong>On small clusters, the add-ons&#39; reservations, not your application, decide how many nodes you pay for.</strong></p><h3>Step 3: The cuts, and what each one costs you</h3><p>Each cut was written down with its trade-off before anything changed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d264a54e15d4b2552ed2ffa6a33885da/href">https://medium.com/media/d264a54e15d4b2552ed2ffa6a33885da/href</a></iframe><h3>Cut 1: AKS Free tier</h3><pre>aks_sku_tier = &quot;Free&quot;</pre><p>The change is in place, with no downtime. The Standard tier buys a financially backed SLA for the API server. When the control plane has a problem, workloads keep running. Only deploys, kubectl and autoscaling waits. That is an acceptable risk for a small user base, and it is reversible in minutes when a customer contract requires an SLA.</p><h3>Cut 2: A smaller burstable database</h3><pre>mysql_sku_name = &quot;B_Standard_B1ms&quot;   # 1 vCore, 2 GB</pre><p>Before the change:</p><ol><li><strong>Check what the app needs.</strong> With 2 web pods × 12 PHP workers, plus the worker and scheduler, the app opens at most about 30 connections. B1ms allows 171.</li><li><strong>The plan says “update in-place.”</strong> A SKU change on Flexible Server restarts the server (1 to 5 minutes) but keeps the same disk. The plan line to fear is must be replaced, which means a new, empty server.</li><li><strong>Take a backup anyway</strong>, and confirm it’s complete:</li></ol><pre>kubectl run mysql-dump -n myapp --rm -i --quiet --restart=Never --image=mysql:8.0 -- \   mysqldump --ssl-mode=REQUIRED --single-transaction --routines --no-tablespaces \   -h YOUR_MYSQL_SERVER.mysql.database.azure.com -u dbadmin -p&quot;$DBPASS&quot; appdb \   &gt; backup-$(date +%F).sql tail -1 backup-$(date +%F).sql     # must say: -- Dump completed on ...</pre><blockquote>A small surprise: when kubectl could not attach to the pod, it fell back to streaming the logs. The dump still arrived complete, but with mysqldump&#39;s password warning as its first line, which would break a restore. Strip it before trusting the file.</blockquote><p>Burstable servers earn CPU credits while idle and spend them in bursts. The risk is a long, heavy job that drains them, after which the server runs at its baseline speed. That is what the cpu_credits_remaining alert from Part 4 is for.</p><h3>Cut 3: Remove the managed cache, safely</h3><p>Laravel can keep its cache, queue, and sessions in MySQL tables (cache, jobs, sessions). At 30 users, the difference in speed is not noticeable. Removing Redis safely needed two switches, not one:</p><pre>variable &quot;app_cache_backend&quot; {<br>  type    = string<br>  default = &quot;redis&quot;<br>  validation {<br>    condition     = contains([&quot;redis&quot;, &quot;database&quot;], var.app_cache_backend)<br>    error_message = &quot;app_cache_backend must be redis or database.&quot;<br>  }<br>  validation {<br>    condition     = var.app_cache_backend == &quot;database&quot; || var.redis_enabled<br>    error_message = &quot;app_cache_backend = \&quot;redis\&quot; needs redis_enabled = true.&quot;<br>  }<br>}</pre><pre>variable &quot;redis_enabled&quot; {<br>  type    = bool<br>  default = true<br>}</pre><pre>module &quot;redis&quot; {<br>  source = &quot;./modules/redis&quot;<br>  count  = var.redis_enabled ? 1 : 0<br>  # ...<br>}</pre><pre>moved {<br>  from = module.redis<br>  to   = module.redis[0]<br>}</pre><p>The order matters:</p><ol><li>Set app_cache_backend = &quot;database&quot;. Terraform only changes the ConfigMap values. Restart the app, then run whatever is still queued in Redis:</li></ol><pre>kubectl exec -n myapp deploy/myapp-worker -- php artisan queue:work redis --stop-when-empty</pre><p>2. Confirm the Redis queue is empty, and that an email (which goes through the queue) arrives.</p><p>3. Then set redis_enabled = false. The plan must show exactly the cache, its private endpoint, its DNS zone, its DNS link, and its three alerts being destroyed. Nothing else.</p><p>The cross-variable validation (supported from Terraform 1.9) makes the dangerous combination impossible: the app pointing at Redis after Redis is gone. The moved block keeps the existing instance when the module gains a count.</p><p>One detail stopped a self-inflicted outage. The pods’ SecretProviderClass still listed the cache password, and a missing Key Vault secret makes the CSI mount fail for <strong>every</strong> pod. So the secret stays, with a placeholder value:</p><pre>secrets = {<br>  &quot;db-password&quot;    = module.mysql.admin_password<br>  # Kept without Redis: the SecretProviderClass still mounts it, and a missing<br>  # secret would stop every pod from starting.<br>  &quot;redis-password&quot; = var.redis_enabled ? module.redis[0].primary_access_key : &quot;redis-not-in-use&quot;<br>}</pre><h3>Cut 4: The one Azure would not allow</h3><p>Since the reservations needed about 2.8 vCPU, one 4-vCPU node would hold everything, at a lower price than two 2-vCPU nodes. In Terraform, it is one line, and the provider temporary_name_for_rotation handles the swap.</p><p>Then the quota requests failed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa279d2048325e8116a9714b1e82401e/href">https://medium.com/media/fa279d2048325e8116a9714b1e82401e/href</a></iframe><p>The swap needs quota for the old pool, a temporary pool, and the new pool at the same time, about 16 vCPUs for a few minutes. The subscription’s regional limit was 10. Self-service increases were refused for every family we tried, which is common for new subscriptions in busy regions. A support ticket could unlock it.</p><p>We stopped there. The remaining savings were $24 to $47 a month. Two nodes also give spare capacity if one fails. A smaller 2-vCPU size with 4 GB would have fitted within quota, but the pods already used about 4.6 GB across two nodes, so it would have traded a small saving for a real risk of running out of memory.</p><p><strong>Lesson:</strong> check quota <em>before</em> you plan a resize, and remember that a node pool rotation needs headroom for the old and the new at once.</p><h3>Kubernetes cost tuning that applies everywhere</h3><ul><li><strong>Requests drive the bill, not usage.</strong> Measure kubectl top over a normal week, set requests a little above typical usage, and leave room for one surge pod during rollouts.</li><li><strong>Memory limits, but no CPU limits.</strong> A memory limit stops a leak from taking down the node. A CPU limit throttles the pod even when the node is idle. Scheduling on requests already protects neighbours.</li><li><strong>Count the add-ons.</strong> On 2-vCPU nodes, AKS’s own components can reserve more CPU than your application. Ask whether you need each optional add-on, and check their requests before choosing a node size.</li><li><strong>Keep the HPA minimum honest.</strong> Two web replicas is a reliability choice (one can restart while the other serves). It is not a performance need at this load, so don’t raise it “just in case”.</li><li><strong>Autoscale nodes with a hard maximum.</strong> max_count is a spending limit as much as a capacity limit.</li><li><strong>Log collection is a cost centre.</strong> Container Insights’ defaults collected 25 GB a month for an application that wrote under 0.5 GB of logs.</li></ul><h3>Tracking and planning the budget</h3><h3>Budgets with forecast alerts</h3><p>A Cost Management budget on the subscription sends alerts at 50%, 80%, and 100% of actual spend, plus 110% of <strong>forecast</strong> spend. The forecast alert is the useful one: it warns in the second week of the month, not after the money is spent.</p><h3>Anomaly alerts need the subscription scope</h3><p>Cost anomaly alerts email when daily spend jumps unexpectedly. Creating one failed at first with “not available for this billing account”. Anomaly alerts exist only at <strong>subscription</strong> scope, and Cost Management had opened at the billing account. Switching the scope selector to the subscription fixed it. The Terraform equivalent is azurerm_cost_anomaly_alert.</p><h3>Tags and a monthly routine</h3><p>Every resource carries project, environment and cost_center tags from the naming module (Part 1), so cost analysis can group by them. Each month:</p><ol><li>Cost analysis by resource, compared with last month.</li><li>Log Analytics ingestion by table (the Usage query in Part 4).</li><li>Whether any alert suggests a resource is too small (MySQL CPU credits, node CPU, queue depth).</li></ol><h3>Writing down when to spend more</h3><p>Cost cuts made for a small user base should not become permanent by accident. The infrastructure file states the triggers for reversing each cut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a365e42bd86a069923f8df127f4b55/href">https://medium.com/media/b5a365e42bd86a069923f8df127f4b55/href</a></iframe><p>Each reversal is one line in terraform.tfvars and one reviewed apply.</p><h3>Results</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b7046bf59c8a1e7502c118fc6c235a3/href">https://medium.com/media/3b7046bf59c8a1e7502c118fc6c235a3/href</a></iframe><h3>Summary</h3><ul><li>Get real prices from the Retail Prices API and real charges from the Cost Management query API. Calculators leave out fixed costs.</li><li>On small clusters, add-on CPU reservations decide your node count. Measure requests against usage.</li><li>For every cut, write down what it costs you and what would make you reverse it.</li><li>Remove stateful services in two steps: switch the app off them, drain, confirm, then delete.</li><li>Check quota before planning resizes. A pool rotation needs room for both pools at once.</li></ul><p>That completes the build: infrastructure as code with locked-down state, a cluster sized to reality, workloads with clear configuration rules, monitoring that costs less than it saves, and a bill that fits the stage the product is at. Parts 6 to 9 cover running it day to day, starting with configuration and secret changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ac50812a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4: Monitoring and Alerting on a Budget]]></title>
            <link>https://medium.com/@lilstex4good/part-4-monitoring-and-alerting-on-a-budget-3430075e9df8?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3430075e9df8</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-cost-management]]></category>
            <category><![CDATA[alerting]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-11-02T08:01:02.065Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSR-BvvT_jXiuXluAGtdjA.png" /></figure><p>A system isn&#39;t in production until someone finds out it broke before customers do. This part builds that for the platform from Parts 1 to 3: external health checks, alerts on platform metrics and logs, and a response plan for every alert. The constraint was cost. The target was a few dollars a month on top of what we already paid.</p><h3>Where we started</h3><p>After the first launch, the setup looked complete on paper, but it had gaps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e338baf6cc13bf327bc4ca0b56e199a/href">https://medium.com/media/8e338baf6cc13bf327bc4ca0b56e199a/href</a></iframe><p>We wrote down the questions monitoring has to answer, ordered by how much a failure hurts:</p><ol><li>Is the API reachable over valid HTTPS? (know within 5 minutes)</li><li>Can it reach its database? (5 minutes)</li><li>Are users getting server errors? (15 minutes)</li><li>Is the queue worker processing jobs? (15 to 30 minutes)</li><li>Did the daily scheduled job run? (same day)</li><li>Is anything running out of CPU, memory, disk or credits? (15 to 30 minutes)</li><li>Is the certificate close to expiry? (30 days ahead)</li><li>Is Azure itself having an incident in our region? (as it happens)</li></ol><p>Every alert below exists to answer one of these.</p><h3>Step zero: measure the log bill before adding anything</h3><p>Every monitoring change adds data, and Log Analytics charges per GB ingested after a free 5 GB a month. So the first query was about volume:</p><pre>Usage<br>| where TimeGenerated &gt; ago(30d) and IsBillable == true<br>| summarize GB = round(sum(Quantity) / 1024, 2) by DataType<br>| order by GB desc</pre><p>The result surprised us. Ingestion was about <strong>0.8 GB a day, or 25 GB a month</strong>, roughly $55 a month after the free allowance. And almost none of it was application logs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bbf82c409382561879fecea24d9acb5/href">https://medium.com/media/3bbf82c409382561879fecea24d9acb5/href</a></iframe><p>Container Insights’ own inventory and performance samples, taken every minute for every namespace, were 95% of the bill.</p><h3>Cost-optimised collection with a data collection rule</h3><p>Container Insights reads its settings from a data collection rule (DCR) when the agent runs in managed identity mode. The cluster needed one flag:</p><pre>oms_agent {<br>  log_analytics_workspace_id      = var.log_analytics_workspace_id<br>  msi_auth_for_monitoring_enabled = true<br>}</pre><p>Then the rule itself, in Terraform:</p><pre>resource &quot;azurerm_monitor_data_collection_rule&quot; &quot;container_insights&quot; {<br>  name                = &quot;dcr-ci-myapp-prod-scus&quot;<br>  resource_group_name = var.resource_group_name<br>  location            = var.location<br>  kind                = &quot;Linux&quot;</pre><pre>  destinations {<br>    log_analytics {<br>      name                  = &quot;workspace&quot;<br>      workspace_resource_id = var.log_analytics_workspace_id<br>    }<br>  }</pre><pre>  data_flow {<br>    streams      = var.streams<br>    destinations = [&quot;workspace&quot;]<br>  }</pre><pre>  data_sources {<br>    extension {<br>      name           = &quot;ContainerInsightsExtension&quot;<br>      extension_name = &quot;ContainerInsights&quot;<br>      streams        = var.streams<br>      extension_json = jsonencode({<br>        dataCollectionSettings = {<br>          interval               = &quot;5m&quot;<br>          namespaceFilteringMode = &quot;Exclude&quot;<br>          namespaces             = [&quot;kube-system&quot;, &quot;gatekeeper-system&quot;, &quot;app-routing-system&quot;]<br>          enableContainerLogV2   = true<br>        }<br>      })<br>    }<br>  }<br>}</pre><pre>resource &quot;azurerm_monitor_data_collection_rule_association&quot; &quot;container_insights&quot; {<br>  name                    = &quot;ContainerInsightsExtension&quot;<br>  target_resource_id      = var.aks_id<br>  data_collection_rule_id = azurerm_monitor_data_collection_rule.container_insights.id<br>}</pre><p>with:</p><pre>variable &quot;streams&quot; {<br>  default = [<br>    &quot;Microsoft-ContainerLogV2&quot;,<br>    &quot;Microsoft-KubeEvents&quot;,<br>    &quot;Microsoft-KubePodInventory&quot;,<br>    &quot;Microsoft-KubeNodeInventory&quot;,<br>    &quot;Microsoft-InsightsMetrics&quot;,<br>  ]<br>}</pre><p>This changes four things:</p><ul><li>Samples every 5 minutes instead of every minute.</li><li>No logs from system namespaces. The ingress controller’s access logs alone were noisy.</li><li>No Perf or ContainerInventory tables. Node and pod CPU and memory still come from free platform metrics.</li><li>App logs go toContainerLogV2, which has proper columns (PodName, PodNamespace, LogMessage) instead of the legacy schema.</li></ul><p>Expected ingestion dropped to around 1.5 GB a month, inside the free allowance.</p><h3>A daily cap as the backstop</h3><pre>resource &quot;azurerm_log_analytics_workspace&quot; &quot;this&quot; {<br>  sku               = &quot;PerGB2018&quot;<br>  retention_in_days = 30<br>  daily_quota_gb    = 0.5<br>}</pre><p>If a pod suddenly logs in a loop, or someone ships with debug logging on, collection pauses at 0.5 GB until midnight UTC instead of producing a surprise bill. Logs paused silently would be its own failure, so there is an alert for it (below). The log level is also pinned to info in the Terraform-owned ConfigMap, so an uploaded .env with LOG_LEVEL=debug cannot override it.</p><h3>The alerting layers</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e8382b5141aa85036f359d73751bfdf/href">https://medium.com/media/6e8382b5141aa85036f359d73751bfdf/href</a></iframe><p>Azure has its own availability tests, but they are billed per run. Three locations every 5 minutes adds up to tens of dollars a month. A free external monitor does the same job, and it tests from genuinely outside Azure.</p><h3>One action group, email only</h3><p>Every Azure rule sends to a single action group:</p><pre>resource &quot;azurerm_monitor_action_group&quot; &quot;this&quot; {<br>  name                = &quot;ag-myapp-prod-scus&quot;<br>  resource_group_name = var.resource_group_name<br>  short_name          = &quot;myapp-prod&quot;</pre><pre>  dynamic &quot;email_receiver&quot; {<br>    for_each = var.alert_email_receivers<br>    content {<br>      name                    = email_receiver.value.name<br>      email_address           = email_receiver.value.email<br>      use_common_alert_schema = true<br>    }<br>  }</pre><pre>  lifecycle {<br>    precondition {<br>      condition     = length(var.alert_email_receivers) &gt; 0<br>      error_message = &quot;Alerts need at least one recipient, or they reach nobody.&quot;<br>    }<br>  }<br>}</pre><p>There are no SMS or voice receivers. They are billed per message, and with no on-call rotation, an email to a shared team channel gives the same result. One of the receivers is a Microsoft Teams channel’s email address. Note that the channel must accept mail from external senders, or Teams silently drops Azure’s alert emails.</p><h3>Metric alerts</h3><p>All metric alerts come from one map, so adding a rule is three lines:</p><pre>locals {<br>  metric_alerts = {<br>    &quot;aks-node-cpu&quot; = {<br>      scope = var.aks_id, namespace = &quot;Microsoft.ContainerService/managedClusters&quot;<br>      metric = &quot;node_cpu_usage_percentage&quot;, aggregation = &quot;Average&quot;<br>      operator = &quot;GreaterThan&quot;, threshold = 85, severity = 2<br>      window = &quot;PT15M&quot;, frequency = &quot;PT5M&quot;<br>      description = &quot;AKS node CPU above 85% for 15 minutes. Runbook: section 5.&quot;<br>    }<br>    &quot;mysql-cpu-credits&quot; = {<br>      scope = var.mysql_id, namespace = &quot;Microsoft.DBforMySQL/flexibleServers&quot;<br>      metric = &quot;cpu_credits_remaining&quot;, aggregation = &quot;Average&quot;<br>      operator = &quot;LessThan&quot;, threshold = 30, severity = 2<br>      window = &quot;PT15M&quot;, frequency = &quot;PT5M&quot;<br>      description = &quot;Burstable MySQL is about to be throttled to its baseline. Runbook: section 11.&quot;<br>    }<br>    # ... node memory, node disk, unschedulable pods, node not ready,<br>    #     MySQL CPU, memory, storage, connections, aborted connections, IO,<br>    #     cache memory, cache load, cache clients, storage availability<br>  }<br>}</pre><pre>resource &quot;azurerm_monitor_metric_alert&quot; &quot;this&quot; {<br>  for_each            = local.metric_alerts<br>  name                = &quot;alert-myapp-prod-${each.key}&quot;<br>  resource_group_name = var.resource_group_name<br>  scopes              = [each.value.scope]<br>  description         = each.value.description<br>  severity            = each.value.severity<br>  window_size         = each.value.window<br>  frequency           = each.value.frequency<br>  auto_mitigate       = true</pre><pre>  criteria {<br>    metric_namespace = each.value.namespace<br>    metric_name      = each.value.metric<br>    aggregation      = each.value.aggregation<br>    operator         = each.value.operator<br>    threshold        = each.value.threshold<br>  }</pre><pre>  action {<br>    action_group_id = azurerm_monitor_action_group.this.id<br>  }<br>}</pre><p>Three practices made these alerts reliable.</p><p><strong>1. Check the metric names against the live resource.</strong> Documentation and older blog posts drift. Before writing any rule, list what the resource actually exposes, and which aggregations it accepts:</p><pre>az monitor metrics list-definitions --resource &quot;$RESOURCE_ID&quot; \<br>  --query &quot;[].{name:name.value, aggs:supportedAggregationTypes}&quot; -o table</pre><p>This caught a real mistake in the plan. The newer Azure Managed Redis has <strong>no error metric</strong>, unlike the older Azure Cache for Redis. The replacement alert fires when connectedclients drops below 1. The app&#39;s pods always hold connections, so zero clients means the app cannot reach the cache.</p><p><strong>2. Derive thresholds from the resource, not from memory.</strong> The connections alert fires at 80% ofmax_connections, and that number depends on the database size. It is computed:</p><pre>mysql_max_connections = coalesce(var.mysql_max_connections, lookup({<br>  B_Standard_B1ms = 171<br>  B_Standard_B2s  = 341<br>}, var.mysql_sku_name, null))</pre><pre># in the alert: threshold = floor(local.mysql_max_connections * 0.8)</pre><p>When the database was resized in Part 5, the alert updated itself in the same plan.</p><p><strong>3. Put the runbook in the description.</strong> The description is the first thing in the alert email. “CPU high” tells you nothing. “Burstable MySQL is about to be throttled. Find the heavy job or scale up. Runbook section 11” tells you what to do next.</p><h3>Log alerts, and why one metric alert became a query</h3><p>Four rules run KQL against the workspace every 15 minutes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95166ed3f8dd23549565dbaedf94180/href">https://medium.com/media/a95166ed3f8dd23549565dbaedf94180/href</a></iframe><h3>The false alarm we avoided</h3><p>The plan included a metric alert on kube_pod_status_ready for the app namespace. Looking at the live series first showed the problem. After every release, the finished migration Job&#39;s pod reports not ready for an hour, until ttlSecondsAfterFinished removes it. That metric would have fired after every deploy, and an alert that fires on every deploy teaches people to ignore alerts.</p><p>A query can filter what a metric can’t:</p><pre>KubePodInventory<br>| where Namespace == &quot;myapp&quot; and ControllerKind != &quot;Job&quot;<br>| summarize Restarts = max(ContainerRestartCount) - min(ContainerRestartCount),<br>            Stuck = countif(ContainerStatusReason in (&quot;CrashLoopBackOff&quot;, &quot;ImagePullBackOff&quot;,<br>                                                       &quot;ErrImagePull&quot;, &quot;CreateContainerConfigError&quot;,<br>                                                       &quot;OOMKilled&quot;)),<br>            PendingSamples = countif(PodStatus == &quot;Pending&quot;)<br>    by Name<br>| where (Restarts &gt; 0 and Name !startswith &quot;myapp-worker-&quot;)<br>     or Stuck &gt; 0<br>     or PendingSamples &gt;= 2</pre><p>The worker is excluded from the restart check because it restarts every hour by design (Part 3). Its crash states still count.</p><pre>resource &quot;azurerm_monitor_scheduled_query_rules_alert_v2&quot; &quot;pods_unhealthy&quot; {<br>  name                    = &quot;alert-myapp-prod-pods-unhealthy&quot;<br>  resource_group_name     = var.resource_group_name<br>  location                = var.location<br>  scopes                  = [var.log_analytics_workspace_id]<br>  severity                = 2<br>  evaluation_frequency    = &quot;PT15M&quot;<br>  window_duration         = &quot;PT15M&quot;<br>  auto_mitigation_enabled = true</pre><pre>  criteria {<br>    query                   = local.pods_unhealthy_query<br>    time_aggregation_method = &quot;Count&quot;<br>    operator                = &quot;GreaterThan&quot;<br>    threshold               = 0<br>  }</pre><pre>  action {<br>    action_groups = [azurerm_monitor_action_group.this.id]<br>  }<br>}</pre><p>Log alerts are billed by how often they run. Running every 15 minutes costs a fraction of running every minute, and is fast enough for every question on our list.</p><p>The error query matches both the current text log format (production.ERROR:) and the JSON format planned for later (&quot;level_name&quot;:&quot;ERROR&quot;). Switching log formats will not silently break the alert.</p><h3>Health alerts for free</h3><pre>resource &quot;azurerm_monitor_activity_log_alert&quot; &quot;service_health&quot; {<br>  name                = &quot;alert-myapp-prod-service-health&quot;<br>  resource_group_name = var.resource_group_name<br>  location            = &quot;global&quot;<br>  scopes              = [&quot;/subscriptions/${var.subscription_id}&quot;]</pre><pre>  criteria {<br>    category = &quot;ServiceHealth&quot;<br>    service_health {<br>      events    = [&quot;Incident&quot;, &quot;Maintenance&quot;, &quot;Security&quot;, &quot;ActionRequired&quot;]<br>      locations = [&quot;South Central US&quot;, &quot;Global&quot;]<br>    }<br>  }</pre><pre>  action {<br>    action_group_id = azurerm_monitor_action_group.this.id<br>  }<br>}</pre><p>Service Health is personalised to the services the subscription uses, so it needs no service filter. A second rule watches <strong>Resource Health</strong> for the resource group and fires when any resource is reported as Degraded or Unavailable. Both are activity log alerts, which cost nothing.</p><p>One setup detail: the subscription must have the Microsoft.AlertsManagement resource provider registered. Ours did not, and that would have failed the first apply.</p><h3>Outside-in checks and heartbeats</h3><p>Azure-side alerts cannot see DNS mistakes, an expired certificate, or the whole cluster being unreachable. An external uptime monitor checks, every 5 minutes:</p><ul><li>GET https://api.example.com/up returns 200.</li><li>GET https://api.example.com/api contains the expected welcome text.</li><li>The certificate’s expiry date, with warnings at 30, 14, and 7 days.</li></ul><p>A <strong>dead man’s switch</strong> service covers the failures that make no noise at all. It alerts when an expected ping does <em>not</em> arrive. The checks are set up first; the app’s pings ship as a small code change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7416e98db6907ccefaa9f6699eb04606/href">https://medium.com/media/7416e98db6907ccefaa9f6699eb04606/href</a></iframe><p>The worker check proves the whole chain: scheduler, queue backend, and worker. If any link breaks, the ping stops. The framework supports this directly:</p><pre>Schedule::command(&#39;reports:nightly&#39;)-&gt;dailyAt(&#39;00:10&#39;)<br>    -&gt;pingBeforeIf($url = config(&#39;services.heartbeat.daily&#39;), $url)<br>    -&gt;thenPingIf((bool) $url, $url);</pre><p>Ping URLs live in the production.env, never in code. When they are unset (development, tests), nothing is sent.</p><h3>Testing the alert code</h3><p>Alerts are code, so they have tests. With mocked providers, these run in seconds:</p><pre>run &quot;every_alert_reaches_the_action_group_by_email_only&quot; {<br>  command = apply   # mocked: nothing real is created</pre><pre>  assert {<br>    condition = alltrue([<br>      length(azurerm_monitor_action_group.this[0].sms_receiver) == 0,<br>      length(azurerm_monitor_action_group.this[0].voice_receiver) == 0,<br>    ])<br>    error_message = &quot;email only: SMS and voice are billed per message&quot;<br>  }<br>  assert {<br>    condition = alltrue([<br>      for a in azurerm_monitor_metric_alert.this :<br>      alltrue([for x in a.action : x.action_group_id == azurerm_monitor_action_group.this[0].id])<br>    ])<br>    error_message = &quot;every metric alert must send to the action group&quot;<br>  }<br>}</pre><pre>run &quot;log_alerts_run_at_most_every_15_minutes&quot; {<br>  command = plan<br>  assert {<br>    condition = alltrue([<br>      for a in azurerm_monitor_scheduled_query_rules_alert_v2.this :<br>      contains([&quot;PT15M&quot;, &quot;PT30M&quot;, &quot;PT1H&quot;], a.evaluation_frequency)<br>    ])<br>    error_message = &quot;a log alert running more often than every 15 minutes costs 2 to 6 times more&quot;<br>  }<br>}</pre><p>The tests encode <em>policy</em>: no paid notification channels, every rule routed, no expensive frequencies. A future change that breaks the policy fails in CI, not on the bill.</p><h3>Response steps</h3><p>An alert is only useful if the person who receives it knows what to do. Every alert maps to a runbook section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/787894ce66384475e0df90f8099540a5/href">https://medium.com/media/787894ce66384475e0df90f8099540a5/href</a></iframe><p>Before calling the setup done, run a drill for each layer. Each one must produce an email to every recipient within the expected time:</p><ul><li>point an uptime monitor at a missing path</li><li>scale the worker to zero for 20 minutes, in a quiet hour</li><li>press the action group’s built-in <strong>Test</strong> button</li></ul><p>An alert that has never fired in a drill is an assumption, not a safety net.</p><h3>What we did not use</h3><ul><li><strong>Azure Managed Grafana:</strong> a monthly cost for dashboards that Azure Workbooks give us for free over the same workspace.</li><li><strong>Managed Prometheus:</strong> more ingestion and more agents. Platform metrics cover every alert on the list.</li><li><strong>Application Insights with OpenTelemetry for PHP:</strong> there is no first-party PHP SDK. It needs a PHP extension plus a collector in the cluster, and all of its data counts toward log ingestion. It becomes worth it when there are several services and distributed tracing matters.</li><li><strong>A self-hosted Prometheus, Grafana, and Loki stack:</strong> the nodes were already short of requested CPU. A third node costs more than everything above combined.</li></ul><h3>Summary</h3><ul><li>Measure log volume first. Container Insights’ own samples can cost more than your application logs.</li><li>Use a data collection rule for 5-minute samples and no system namespaces, plus a daily cap with an alert on the cap.</li><li>Check metric names and aggregations against the live resource before writing rules.</li><li>Prefer a log query when a metric can’t exclude a known, harmless case.</li><li>Use free external tools for uptime, heartbeats, and errors. Pay Azure only for what it uniquely sees.</li><li>Treat alerts as code, with tests that enforce cost and routing policy.</li></ul><p><em>The monitoring layer added about $3 a month, and its log changes removed about $50 a month. Part 5 continues with cost.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3430075e9df8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Organising Kubernetes Workloads, and What We Left Out]]></title>
            <link>https://medium.com/@lilstex4good/part-3-organising-kubernetes-workloads-and-what-we-left-out-1666e63d2c3f?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1666e63d2c3f</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-31T08:01:02.183Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from an empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6UIcCD7D67NGGYhpuB_sQ.png" /></figure><p>Parts 1 and 2 built the infrastructure and the cluster. This part covers what runs on it, from the container image down to the release pipeline. The second half is a deep dive into the Kubernetes features we considered and decided not to use yet, with the reasoning behind each decision.</p><h3>One image, three roles</h3><p>The application is a PHP (Laravel) API. In production, it runs as three different processes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3defb9d1990553c1ac47a9b891d2c43/href">https://medium.com/media/b3defb9d1990553c1ac47a9b891d2c43/href</a></iframe><p>All three use <strong>the same image</strong>. An environment variable picks the role at start-up. One image means one build, one tag, and no chance of the worker running different code from the web pods.</p><h3>The entrypoint</h3><pre>#!/bin/sh<br>set -eu<br>cd /var/www/html</pre><pre># 1. The CSI driver mounts the whole .env (base64) from Key Vault at this path.<br>DOTENV_FILE=&quot;${APP_DOTENV_FILE:-/mnt/secrets-store/app-dotenv-b64}&quot;<br>if [ -f &quot;$DOTENV_FILE&quot; ]; then<br>    base64 -d &quot;$DOTENV_FILE&quot; &gt; .env<br>    chmod 0600 .env<br>fi</pre><pre># 2. Without APP_KEY every request is a 500. Fail loudly instead.<br>if [ -z &quot;${APP_KEY:-}&quot; ] &amp;&amp; ! grep -Eq &#39;^APP_KEY=.+&#39; .env; then<br>    echo &quot;entrypoint: APP_KEY is not set&quot; &gt;&amp;2<br>    exit 1<br>fi</pre><pre># 3. Cache config at start, never at build: the image carries no environment.<br>php artisan config:cache<br>php artisan route:cache<br>php artisan view:cache</pre><pre>if [ &quot;$#&quot; -gt 0 ]; then<br>    exec &quot;$@&quot;            # e.g. the migrate Job passes &quot;php artisan migrate --force&quot;<br>fi</pre><pre>case &quot;${CONTAINER_ROLE:-web}&quot; in<br>    web)       exec supervisord -c /etc/supervisor/app/web.conf ;;<br>    worker)    exec php artisan queue:work --sleep=3 --tries=3 --max-time=3600 ;;<br>    scheduler) exec php artisan schedule:work ;;<br>    *) echo &quot;unknown CONTAINER_ROLE &#39;${CONTAINER_ROLE}&#39;&quot; &gt;&amp;2; exit 1 ;;<br>esac</pre><p>Design notes:</p><ul><li><strong>Config is cached at start, not at build.</strong> The same image runs anywhere. Settings come only from the environment.</li><li><strong>A missing </strong><strong>APP_KEY makes the container exit.</strong> A pod in CrashLoopBackOff with a clear log line is far easier to debug than a pod that is Ready but returns 500 for every request.</li><li><strong>The worker exits every hour (</strong><strong>--max-time=3600)</strong> and Kubernetes restarts it. This bounds memory growth in long-running PHP processes. It also means one restart per hour on the worker is normal, and alerts must know that (Part 4).</li><li><strong>The image runs as </strong><strong>www-data.</strong> Code is root-owned and read-only to the app. Only storage/ and bootstrap/cache are writable.</li></ul><h3>Sizing php-fpm to the pod</h3><pre>pm = dynamic<br>; Sized to the web pod&#39;s 2Gi memory limit: a worker rendering a PDF can use<br>; well over 100 MB. Scale out with more pods (HPA), not more workers per pod.<br>pm.max_children = 12<br>pm.start_servers = 4<br>clear_env = no   ; keep the pod&#39;s environment visible to PHP</pre><p>clear_env = no is easy to miss. Without it, php-fpm hides the environment variables that Kubernetes injects, and the app falls back to whatever is in .env.</p><h3>Where configuration comes from</h3><p>Settings reach the pods from three places, in a fixed order of precedence:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c58a2111a9d9dce50def4844d5ea1be/href">https://medium.com/media/7c58a2111a9d9dce50def4844d5ea1be/href</a></iframe><p>Real environment variables win over .env. So the ConfigMap and the Secret override any matching key that an operator leaves in the uploaded .env. That is deliberate. If someone uploads a .env copied from a staging server, its DB_HOST=127.0.0.1 cannot break production.</p><h3>The ConfigMap is a Terraform output</h3><pre>locals {<br>  app_runtime_settings = {<br>    DB_CONNECTION   = &quot;mysql&quot;<br>    DB_URL          = &quot;&quot;            # a DB_URL left in .env would beat DB_HOST<br>    DB_HOST         = module.mysql.fqdn<br>    DB_DATABASE     = module.mysql.database_name<br>    LOG_CHANNEL     = &quot;stderr&quot;<br>    LOG_LEVEL       = &quot;info&quot;        # a copied .env with &quot;debug&quot; can&#39;t flood the logs<br>    CACHE_STORE     = var.app_cache_backend<br>    QUEUE_CONNECTION = var.app_cache_backend<br>    TRUSTED_PROXIES = &quot;*&quot;           # the ingress is the only way in<br>  }<br>}</pre><pre>output &quot;app_runtime_settings&quot; {<br>  value = local.app_runtime_settings<br>}</pre><p>At release time, a small script renders it into a manifest:</p><pre>terraform -chdir=terraform output -json app_runtime_settings \<br>  | jq -r &#39;to_entries[] | &quot;\(.key)=\(.value)&quot;&#39; &gt; out/app.env<br>kubectl create configmap myapp-config -n myapp \<br>  --from-env-file=out/app.env --dry-run=client -o yaml &gt; out/configmap.yaml</pre><p>Infrastructure and application config cannot disagree. If Terraform moves the database, the next release carries the new host.</p><h3>Secrets through the CSI driver</h3><pre>apiVersion: secrets-store.csi.x-k8s.io/v1<br>kind: SecretProviderClass<br>metadata:<br>  name: myapp-secrets<br>  namespace: myapp<br>spec:<br>  provider: azure<br>  secretObjects:                 # also synced to a normal Secret for envFrom<br>    - secretName: myapp-secrets<br>      type: Opaque<br>      data:<br>        - { objectName: db-password, key: DB_PASSWORD }<br>        - { objectName: storage-connection-string, key: AZURE_STORAGE_CONNECTION_STRING }<br>  parameters:<br>    useVMManagedIdentity: &quot;true&quot;<br>    userAssignedIdentityID: &quot;${KV_IDENTITY_CLIENT_ID}&quot;<br>    keyvaultName: &quot;${KEY_VAULT_NAME}&quot;<br>    tenantId: &quot;${TENANT_ID}&quot;<br>    objects: |<br>      array:<br>        - |<br>          objectName: app-dotenv-b64<br>          objectType: secret<br>        - |<br>          objectName: db-password<br>          objectType: secret<br>        - |<br>          objectName: storage-connection-string<br>          objectType: secret</pre><p>One behaviour to plan around: <strong>if any object listed here is missing from Key Vault, the volume mount fails, and every pod stays in </strong><strong>ContainerCreating.</strong> When the cache was later removed (Part 5), its password secret was kept in Key Vault with a placeholder value for exactly this reason. Removing it from both places at once would have meant a coordinated release.</p><h3>The workloads</h3><h3>Web</h3><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: myapp-web<br>  namespace: myapp<br>spec:<br>  replicas: 2<br>  strategy:<br>    rollingUpdate: { maxUnavailable: 0, maxSurge: 1 }<br>  template:<br>    spec:<br>      nodeSelector: { workload: apps }<br>      securityContext: { runAsNonRoot: true, runAsUser: 33, runAsGroup: 33, fsGroup: 33 }<br>      containers:<br>        - name: api<br>          image: my-acr.azurecr.io/myapp-api:${IMAGE_TAG}<br>          env:<br>            - { name: CONTAINER_ROLE, value: web }<br>          envFrom:<br>            - configMapRef: { name: myapp-config }<br>            - secretRef: { name: myapp-secrets }<br>          ports:<br>            - containerPort: 8080<br>          readinessProbe:<br>            httpGet: { path: /up, port: 8080 }<br>            initialDelaySeconds: 10<br>            periodSeconds: 10<br>          livenessProbe:<br>            httpGet: { path: /up, port: 8080 }<br>            initialDelaySeconds: 30<br>            periodSeconds: 20<br>          resources:<br>            requests: { cpu: 100m, memory: 512Mi }<br>            limits:   { memory: 2Gi }<br>          volumeMounts:<br>            - { name: secrets-store, mountPath: /mnt/secrets-store, readOnly: true }<br>      volumes:<br>        - name: secrets-store<br>          csi:<br>            driver: secrets-store.csi.k8s.io<br>            readOnly: true<br>            volumeAttributes: { secretProviderClass: myapp-secrets }</pre><p>The probes use the framework’s built-in /up route, which proves the app boots. They deliberately do <strong>not</strong> check the database. If MySQL restarts, a liveness probe that depends on it would restart every web pod at the same moment, turning a 2-minute database blip into a full outage. Database health is checked from outside instead (Part 4).</p><h3>Worker</h3><p>The same image, CONTAINER_ROLE=worker, smaller requests, and:</p><pre>terminationGracePeriodSeconds: 90   # let a running job finish; queue:work handles SIGTERM</pre><h3>Scheduler</h3><pre>spec:<br>  replicas: 1                   # exactly one<br>  strategy: { type: Recreate }  # never two during a rollout</pre><p>A rolling update would briefly run two schedulers, and daily jobs would run twice. Recreate stops the old pod before starting the new one. A few seconds without a scheduler is harmless. Two schedulers are not.</p><h3>Migrations as a Job, once per release</h3><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: myapp-migrate<br>  namespace: myapp<br>spec:<br>  backoffLimit: 1<br>  ttlSecondsAfterFinished: 3600<br>  template:<br>    spec:<br>      restartPolicy: Never<br>      containers:<br>        - name: migrate<br>          image: my-acr.azurecr.io/myapp-api:${IMAGE_TAG}<br>          args: [&quot;php&quot;, &quot;artisan&quot;, &quot;migrate&quot;, &quot;--force&quot;]</pre><p>Running migrations in the web entrypoint would make every replica race to migrate. A Job runs them once, before the new pods roll out. If it fails, the pipeline prints its logs and stops, and the old version keeps serving.</p><h3>Service and ingress</h3><p>The Service is ClusterIP (port 80 to 8080). Only the ingress is public. The cluster uses the <strong>AKS application routing add-on</strong> (a managed NGINX ingress controller), with the TLS certificate pulled straight from Key Vault:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: myapp<br>  namespace: myapp<br>  annotations:<br>    kubernetes.azure.com/tls-cert-keyvault-uri: &quot;https://YOUR_KEY_VAULT.vault.azure.net/certificates/api-tls&quot;<br>spec:<br>  ingressClassName: webapprouting.kubernetes.azure.com<br>  tls:<br>    - hosts: [api.example.com]<br>      secretName: keyvault-myapp<br>  rules:<br>    - host: api.example.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service: { name: myapp-web, port: { number: 80 } }</pre><p>Because TLS ends at the ingress, the app sees plain HTTP from inside the cluster. Laravel only builds https:// URLs if it trusts the X-Forwarded-Proto header, which is why TRUSTED_PROXIES is set, and set only in production. On a VPS with no proxy in front, trusting forwarded headers would let clients spoof their IP.</p><h3>The release pipeline</h3><p>A push to the prod branch runs:</p><ol><li><strong>Tests</strong> (PHPUnit, about 450 tests).</li><li><strong>Build and push</strong> my-acr.azurecr.io/myapp-api:&lt;git-sha7&gt;. The tag is the commit, so kubectl get deploy always tells you which commit is live.</li><li><strong>Render manifests</strong> from Terraform outputs (envsubst for names, the ConfigMap as shown above).</li><li><strong>Apply</strong> the namespace, SecretProviderClass, and ConfigMap.</li><li><strong>Wait for the Secret to sync.</strong> When the SecretProviderClass gains a key, the driver adds it to the synced Secret on its next refresh (every 2 minutes). Pods created before that would start without it, so the pipeline compares the expected keys with the Secret’s keys and waits.</li><li><strong>Run the migrate Job.</strong> On failure: print logs, stop.</li><li><strong>Roll out</strong> web, worker, and scheduler, and wait for each.</li><li><strong>Drain the previous queue backend</strong> if the queue driver just changed (for example, Redis to database).</li><li><strong>Smoke tests:</strong> /up and /api through the Service, a cache write and read inside a pod, then the public https:// URL.</li></ol><p>Rollback is kubectl rollout undo on the three Deployments. Migrations are not rolled back automatically. A rollback that drops columns is a decision, not a reflex.</p><h3>Deep dive: what we considered and left out</h3><p>Each of these is a good tool. Each was left out because, at this size, its cost (in money, moving parts, or team attention) was higher than the problem it solves. The reasons are written down so the decisions can be revisited when the situation changes.</p><h3>Helm or Kustomize</h3><p><strong>Considered for:</strong> templating manifests and per-environment overlays.</p><p><strong>Left out because:</strong> there is one production environment on Kubernetes (the others run on a VPS). The only values that change are about six names and the image tag. envsubst With an explicit variable list, does that in five lines, and the rendered output is plain YAML you can read and diff. A Helm chart adds a templating language, a release store, and upgrade semantics to learn and debug.</p><p><strong>Revisit when:</strong> a second cluster or environment appears, or the manifests start needing conditionals.</p><h3>GitOps (Argo CD or Flux)</h3><p><strong>Considered for:</strong> pull-based deploys, drift detection inside the cluster, and a UI for the current state.</p><p><strong>Left out because:</strong> it means another always-on controller on a small node, plus another system to secure and upgrade. The push pipeline already gives an audit trail (git history plus workflow runs) and deterministic releases. The extra drift detection matters less when nobody has a reason to kubectl apply by hand.</p><p><strong>Revisit when:</strong> several services or clusters need to stay in sync, or more people have cluster access.</p><h3>Service mesh (Istio, Linkerd)</h3><p><strong>Considered for:</strong> mTLS between pods, retries, and traffic splitting for canary releases.</p><p><strong>Left out because:</strong> there is one service. Pod-to-pod traffic is web-to-nothing, and the data tier is reached over TLS already. A mesh adds a sidecar to every pod, so more CPU and memory requests on nodes that were already short on <em>requested</em> CPU (Part 2).</p><p><strong>Revisit when:</strong> the system splits into several services that call each other.</p><h3>KEDA (event-driven autoscaling)</h3><p><strong>Considered for:</strong> scaling queue workers on queue length instead of CPU.</p><p><strong>Left out because:</strong> one worker easily handles the email and notification volume, which is a few jobs a minute at peak. The queue depth is watched by an alert instead (Part 4).</p><p><strong>Revisit when:</strong> queue work becomes heavy, for example bulk imports or report generation that has to finish within minutes.</p><h3>cert-manager</h3><p><strong>Considered for:</strong> automatic Let’s Encrypt renewal.</p><p><strong>Left out because:</strong> the domain’s DNS is hosted at a registrar with no API access for the team, so the DNS-01 challenge cannot be automated, and HTTP-01 would need the ingress serving before the certificate exists. The certificate was issued once with a manual DNS challenge and imported into Key Vault. The ingress reads it from there.</p><p><strong>The cost of this choice:</strong> a manual renewal every 60 to 90 days. It is on a calendar, and an external uptime monitor watches the expiry date (Part 4).</p><p><strong>Revisit when:</strong> DNS moves to Azure DNS (or any provider with an API). Then cert-manager, or Key Vault’s own certificate issuance, removes the manual step.</p><h3>Databases and caches inside the cluster</h3><p><strong>Considered for:</strong> cost, since a MySQL StatefulSet on an existing node costs nothing extra.</p><p><strong>Left out because:</strong> backups, point-in-time restore, patching, failover, and storage growth all become our job. Azure Database for MySQL does all of that, and its smallest production-grade size costs less than an hour of engineering time per month. State lives in managed services. The cluster holds only stateless pods and can be rebuilt from code.</p><h3>Init containers for migrations</h3><p><strong>Considered for:</strong> running migrations before each pod starts.</p><p><strong>Left out because:</strong> every replica would run them, and the first wins a race. A Job runs once, its logs are easy to read, and its failure stops the release before any pod changes.</p><h3>Vertical Pod Autoscaler</h3><p><strong>Considered for:</strong> tuning requests automatically.</p><p><strong>Left out because:</strong> in “auto” mode it restarts pods to change requests. In “recommend” mode it is useful, but kubectl top plus Container Insights gave the same answer for three workloads. Requests were set once from measured usage.</p><h3>External Secrets Operator</h3><p><strong>Considered for:</strong> syncing Key Vault into Kubernetes Secrets without a CSI volume.</p><p><strong>Left out because:</strong> AKS ships and maintains the Secrets Store CSI driver as an add-on. The operator would be one more component to install and upgrade, for the same result.</p><h3>Network policies and Entra ID cluster access</h3><p>These were also left out, but they belong to security, and Part 2 covers them with the configuration needed. In short: set the network policy engine when you create the cluster, even if you don’t need policies yet.</p><h3>Managed Prometheus and Grafana</h3><p>Covered in Part 4. Platform metrics and Log Analytics answer every question we have today, at a fraction of the cost.</p><h3>Summary</h3><ul><li>One image, three roles chosen by an environment variable. One build, one tag, no version skew.</li><li>Configuration has three sources with a fixed precedence. Terraform-owned values always win.</li><li>Probes check that the app boots, not its dependencies. Dependencies are watched from outside.</li><li>Migrations run once per release in a Job, before any rollout.</li><li>Every tool left out has a written reason and a trigger for revisiting it.</li></ul><p><em>Part 4 covers how we know all of this is working.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1666e63d2c3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: A Production-Ready AKS Cluster Without Overbuilding It]]></title>
            <link>https://medium.com/@lilstex4good/part-2-a-production-ready-aks-cluster-without-overbuilding-it-092d488c8c47?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/092d488c8c47</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-devops]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-30T08:01:02.567Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*If6jbIHEQycAe8jElIpmIA.png" /></figure><p>Part 1 built the network, state, and data services. This part adds the Azure Kubernetes Service cluster that runs the application: a PHP API, a queue worker, and a scheduler.</p><p>“Production ready” means different things at different scales. Here the starting load is a few dozen users, the team is small, and every monthly dollar is visible. The aim is a cluster that is secure by default, upgrades itself, scales when needed, and costs as little as possible while doing so. The article also lists what we chose <em>not</em> to enable yet, and why.</p><h3>The cluster in Terraform</h3><pre>resource &quot;azurerm_kubernetes_cluster&quot; &quot;this&quot; {<br>  name                      = &quot;aks-myapp-prod-scus&quot;<br>  location                  = var.location<br>  resource_group_name       = var.resource_group_name<br>  dns_prefix                = &quot;myappprodscus&quot;<br>  node_resource_group       = &quot;rg-myapp-prod-scus-aks-nodes&quot;<br>  sku_tier                  = var.sku_tier          # &quot;Free&quot; or &quot;Standard&quot;<br>  automatic_upgrade_channel = &quot;patch&quot;<br>  oidc_issuer_enabled       = true<br>  workload_identity_enabled = true</pre><pre>  default_node_pool {<br>    name                        = &quot;system&quot;<br>    vm_size                     = var.node_vm_size  # Standard_D2as_v7<br>    vnet_subnet_id              = var.subnet_id<br>    auto_scaling_enabled        = true<br>    min_count                   = 1<br>    max_count                   = 2<br>    os_disk_size_gb             = 32<br>    temporary_name_for_rotation = &quot;systemtmp&quot;</pre><pre>    upgrade_settings {<br>      max_surge = &quot;33%&quot;<br>    }<br>  }</pre><pre>  identity {<br>    type = &quot;SystemAssigned&quot;<br>  }</pre><pre>  network_profile {<br>    network_plugin      = &quot;azure&quot;<br>    network_plugin_mode = &quot;overlay&quot;<br>    load_balancer_sku   = &quot;standard&quot;<br>    service_cidr        = &quot;10.100.0.0/16&quot;<br>    dns_service_ip      = &quot;10.100.0.10&quot;<br>  }</pre><pre>  maintenance_window_auto_upgrade {<br>    frequency   = &quot;Weekly&quot;<br>    interval    = 1<br>    duration    = 4<br>    day_of_week = &quot;Sunday&quot;<br>    start_time  = &quot;02:00&quot;<br>    utc_offset  = &quot;+00:00&quot;<br>  }</pre><pre>  key_vault_secrets_provider {<br>    secret_rotation_enabled = true<br>  }</pre><pre>  oms_agent {<br>    log_analytics_workspace_id      = var.log_analytics_workspace_id<br>    msi_auth_for_monitoring_enabled = true<br>  }</pre><pre>  web_app_routing {<br>    dns_zone_ids = []<br>  }</pre><pre>  lifecycle {<br>    ignore_changes = [default_node_pool[0].node_count]<br>  }<br>}</pre><p>The rest of this article explains each block.</p><h3>Choosing the node size</h3><h3>Start from what the region will actually give you</h3><p>The pricing calculator suggested a D2_v3 node. The first terraform apply failed with an error that read like a zone problem. The real cause was that this size was not offered to the subscription in that region at all. Several newer families were blocked as well.</p><p>Check before choosing:</p><pre>az vm list-skus --location southcentralus --size Standard_D2as_v7 \<br>  --query &quot;[].{size:name, restricted:join(&#39;,&#39;, restrictions[].reasonCode)}&quot; -o table</pre><p>An empty restricted column means the size is available. NotAvailableForSubscription means it is not, whatever the docs say.</p><p>Then check quota, which is a separate limit:</p><pre>az vm list-usage --location southcentralus -o table | grep -E &quot;Dasv7|Total Regional&quot;</pre><p>New subscriptions often have small limits, for example 10 vCPUs per family and 10 in total for the region. Part 5 shows how that limit blocked a later resize.</p><h3>Why a 2 vCPU, 8 GB node</h3><p>Standard_D2as_v7 (2 vCPU, 8 GB, AMD) was the closest available match to the original plan, at about $80 a month per node. For a PHP API that renders PDFs in the request path, memory matters more than CPU. Each PHP worker can use over 100 MB while rendering a document.</p><h3>One pool, with a switch for two</h3><p>AKS recommends separate system and user pools, so cluster add-ons never compete with application pods. At this size, a second pool doubles the node bill for no measurable benefit. The module keeps a single pool by default and offers a variable for later:</p><pre>default_node_pool {<br>  only_critical_addons_enabled = var.apps_pool_enabled<br>  node_labels                  = var.apps_pool_enabled ? {} : { workload = &quot;apps&quot; }<br>}</pre><pre>resource &quot;azurerm_kubernetes_cluster_node_pool&quot; &quot;apps&quot; {<br>  count       = var.apps_pool_enabled ? 1 : 0<br>  name        = &quot;apps&quot;<br>  mode        = &quot;User&quot;<br>  node_labels = { workload = &quot;apps&quot; }<br>}</pre><p>The application pods select workload: apps. With one pool, the system pool carries that label. Turning the apps pool on moves them without touching the manifests.</p><h3>Resizing later</h3><p>Changing vm_size on the default pool used to mean recreating the cluster. With temporary_name_for_rotation, the provider creates a temporary pool, moves the pods, rebuilds the default pool on the new size, and moves them back. Plan for quota here: during the swap the old, temporary, and new nodes exist together.</p><h3>Choosing the network plugin</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f6d52a78c84f05d4da047fa49681f4/href">https://medium.com/media/d3f6d52a78c84f05d4da047fa49681f4/href</a></iframe><p>With Overlay, the AKS subnet only needs addresses for nodes. Pods use a separate CIDR that never appears in the VNet, so a /22 subnet lasts a long time.</p><p>The service CIDR (10.100.0.0/16) must not overlap the VNet or anything peered later. The DNS service IP must fall inside it.</p><p>The Standard load balancer is required for multiple node pools and availability zones, and it provides the cluster’s outbound IP.</p><h3>Identity: no passwords between services</h3><p>Each managed identity gets exactly the role it needs, scoped to one resource:</p><pre># Nodes pull images from the registry. The registry has admin credentials disabled.<br>resource &quot;azurerm_role_assignment&quot; &quot;acr_pull&quot; {<br>  scope                = var.acr_id<br>  role_definition_name = &quot;AcrPull&quot;<br>  principal_id         = azurerm_kubernetes_cluster.this.kubelet_identity[0].object_id<br>}</pre><pre># The Secrets Store CSI driver reads application secrets, nothing more.<br>resource &quot;azurerm_role_assignment&quot; &quot;key_vault_secrets_user&quot; {<br>  scope                = var.key_vault_id<br>  role_definition_name = &quot;Key Vault Secrets User&quot;<br>  principal_id         = azurerm_kubernetes_cluster.this.key_vault_secrets_provider[0].secret_identity[0].object_id<br>}</pre><pre># The cluster identity manages load balancer rules in the custom subnet.<br>resource &quot;azurerm_role_assignment&quot; &quot;subnet_network_contributor&quot; {<br>  scope                = var.subnet_id<br>  role_definition_name = &quot;Network Contributor&quot;<br>  principal_id         = azurerm_kubernetes_cluster.this.identity[0].principal_id<br>}</pre><p>oidc_issuer_enabled and workload_identity_enabled are on so that pods can later use their own Entra ID identities, for example to reach Blob Storage without a connection string. Today the app still uses a connection string from Key Vault. Moving to workload identity is a small follow-up because the cluster side is already in place.</p><h3>Securing the cluster</h3><h3>What is in place</h3><ul><li><strong>Kubernetes RBAC</strong> is enabled (the AKS default).</li><li><strong>Pods run as a non-root user</strong> with a fixed UID, and the image’s code directory is root-owned and read-only to the app:</li></ul><pre>securityContext: { runAsNonRoot: true, runAsUser: 33, runAsGroup: 33, fsGroup: 33 }</pre><ul><li><strong>No secrets in manifests or environment files in git.</strong> Secrets come from Key Vault through the CSI driver (Part 3).</li><li><strong>No registry passwords.</strong> Image pulls use the kubelet identity.</li><li><strong>Only the ingress is public.</strong> The API Service is ClusterIP. The database and cache have no public endpoints.</li></ul><h3>What comes next, and how</h3><p>Two hardening steps were deliberately postponed. Both are listed here with the configuration they need, so they are a planned change and not an unknown.</p><p><strong>1. Entra ID for cluster access, and no local admin account.</strong> Today, az aks get-credentials hands out a cluster-admin kubeconfig to anyone with the right Azure role. Integrating Entra ID makes every kubectl call an Entra identity, which can be audited and limited with Azure RBAC:</p><pre>resource &quot;azurerm_kubernetes_cluster&quot; &quot;this&quot; {<br>  # ...<br>  local_account_disabled = true</pre><pre>  azure_active_directory_role_based_access_control {<br>    azure_rbac_enabled     = true<br>    admin_group_object_ids = [var.cluster_admins_group_id]<br>  }<br>}</pre><p>The reason for waiting: CI deploys with a service principal through kubectl. That identity needs an explicit role (for example <em>Azure Kubernetes Service RBAC Writer</em> on the namespace) and the kubelogin plugin in the pipeline. Doing it carefully takes an afternoon of testing, which was spent on monitoring first.</p><p><strong>2. Network policies.</strong> Without them, any pod can talk to any other pod. With one application namespace and only platform add-ons beside it, the risk is low but not zero. On Azure CNI Overlay, the cleanest engine is Cilium:</p><pre>network_profile {<br>  network_plugin      = &quot;azure&quot;<br>  network_plugin_mode = &quot;overlay&quot;<br>  network_data_plane  = &quot;cilium&quot;<br>  network_policy      = &quot;cilium&quot;<br>}</pre><p>Then a default-deny policy for the namespace, plus explicit allows:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-ingress<br>  namespace: myapp<br>spec:<br>  podSelector: {}<br>  policyTypes: [Ingress]<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-ingress-controller-to-web<br>  namespace: myapp<br>spec:<br>  podSelector:<br>    matchLabels: { role: web }<br>  policyTypes: [Ingress]<br>  ingress:<br>    - from:<br>        - namespaceSelector:<br>            matchLabels: { kubernetes.io/metadata.name: app-routing-system }<br>      ports:<br>        - { protocol: TCP, port: 8080 }</pre><p>The reason for waiting: changing the network data plane on a running cluster is a disruptive operation. It is cheaper to decide it at creation time, and that is the honest lesson here. If you are creating a cluster today, set the network policy engine on day one, even if the first policy only allows everything.</p><p><strong>3. Restrict the API server.</strong> api_server_access_profile { authorized_ip_ranges = [...] } Limits which IPs can reach the Kubernetes API. For a team working from changing home IPs plus GitHub-hosted runners, the allow-list is hard to keep accurate. A private cluster with a self-hosted runner is the stronger option when the team grows.</p><h3>Upgrades without surprises</h3><ul><li><strong>automatic_upgrade_channel = &quot;patch&quot;</strong> Applies Kubernetes patch releases automatically. Minor version upgrades stay a deliberate change.</li><li><strong>A maintenance window</strong> (Sunday 02:00 UTC, 4 hours) keeps automatic upgrades away from business hours.</li><li><strong>max_surge = &quot;33%&quot;</strong> Adds a temporary node during upgrades, so pods move to fresh capacity before the old node drains. With one or two nodes, that rounds up to one extra node.</li></ul><h3>Availability and scaling</h3><h3>Three layers of scaling</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c6c46ee4cf4f64df31a5b7c4309128b/href">https://medium.com/media/4c6c46ee4cf4f64df31a5b7c4309128b/href</a></iframe><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: myapp-web<br>spec:<br>  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: myapp-web }<br>  minReplicas: 2<br>  maxReplicas: 4<br>  metrics:<br>    - type: Resource<br>      resource:<br>        name: cpu<br>        target: { type: Utilization, averageUtilization: 70 }</pre><p>The web Deployment rolls out with maxUnavailable: 0, maxSurge: 1. A new pod must pass its readiness probe before an old one stops.</p><h3>The resource request lesson</h3><p>The first manifests requested 250m CPU for each web pod, 100m for the worker and 50m for the scheduler. Those are reasonable-looking numbers. Each 2 vCPU node offers about 1900m to pods, and the AKS add-ons already reserve a large share of that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15005dfc31cd475e3649ee96f8e30f87/href">https://medium.com/media/15005dfc31cd475e3649ee96f8e30f87/href</a></iframe><p>Both nodes sat at 93 to 98% <em>requested</em>, while real usage was around 4%. During a rollout, the surge pod could not be scheduled; the autoscaler was already at its maximum, and the deploy stalled max node group size reached.</p><p>The fix was to size requests from measured usage, not from guesses:</p><pre>resources:<br>  requests: { cpu: 100m, memory: 512Mi }<br>  limits:   { memory: 2Gi }   # no CPU limit: a busy pod may burst</pre><p>There is a memory limit (a leaking PHP worker should be killed and restarted) but no CPU limit. A CPU limit throttles a pod even when the node is idle, and request-based scheduling already protects neighbours.</p><h3>Availability zones: not yet</h3><p>The cluster runs without zones (zones = []). With one or two nodes, spreading them across zones does not add meaningful resilience. If a zone goes down while it holds your only node, the outage is the same either way. Zones become worth it with three or more nodes, and they must be chosen when the pool is created.</p><h3>Free tier or Standard tier?</h3><p>The Standard tier adds a financially backed uptime SLA for the control plane, at about $73 a month. The Free tier has no SLA. If the control plane has a problem, running pods keep serving traffic. Onlykubectl, deploys, and autoscaling pause. For the first months with a small user base, the cluster moved to the Free tier (Part 5). It goes back to Standard when a customer contract needs an uptime promise.</p><h3>Summary</h3><ul><li>Pick node sizes from what the subscription can actually create az vm list-skusand check quota before you depend on it.</li><li>Use Azure CNI Overlay, so pod IPs don’t consume the VNet.</li><li>Give each managed identity one role on one resource. No admin credentials anywhere.</li><li>Size CPU requests from measured usage, and remember that add-ons reserve a large share of a small node.</li><li>Decide the network policy engine at creation time. It is cheap then and disruptive later.</li></ul><p><em>Part 3 looks at what runs on this cluster and how it is organised.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=092d488c8c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Building Azure Infrastructure with Terraform]]></title>
            <link>https://medium.com/@lilstex4good/part-1-building-azure-infrastructure-with-terraform-63aa943c3b30?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/63aa943c3b30</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 12:42:03 GMT</pubDate>
            <atom:updated>2026-10-29T12:42:03.070Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: Running a SaaS API on Azure, from an empty subscription to production</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2-gOcotC7r8LS7BhaP2Yg.png" /></figure><p>This series follows one real project: moving the production backend of a multi-tenant SaaS platform from a single VPS to Azure. The backend is a PHP API with a MySQL database, a queue worker, and a scheduler. The team is small, the first customers number in the dozens, and the budget matters.</p><p>This first part covers the foundation: how the Terraform code is organised, where state lives, how the network keeps the data tier private, and the habits that stop the live environment drifting away from the code.</p><h3>What we are building</h3><p>By the end of this part, Terraform creates:</p><ul><li>A resource group for production, plus a separate one for Terraform state.</li><li>A virtual network with three subnets: one for Kubernetes, one delegated to MySQL, one for private endpoints.</li><li>Azure Database for MySQL Flexible Server with no public endpoint.</li><li>Azure Container Registry, Azure Key Vault, and a storage account for application documents.</li><li>A Log Analytics workspace.</li><li>An AKS cluster (covered in Part 2).</li></ul><p>Everything is code. Nobody creates or edits production resources in the portal.</p><h3>Repository layout</h3><pre>terraform/<br>  bootstrap/            state storage (applied once, by hand)<br>  modules/<br>    naming/             names and tags, nothing else<br>    network/            VNet and subnets<br>    acr/                container registry<br>    storage/            application blob storage<br>    mysql/              MySQL Flexible Server + private DNS<br>    redis/              optional cache (removed later, see Part 5)<br>    key_vault/          vault, RBAC, generated secrets<br>    aks/                Kubernetes cluster<br>    monitoring/         alerts and log collection (Part 4)<br>  tests/                root-level tests<br>  main.tf               wires the modules together<br>  locals.tf             derived values (the app&#39;s runtime settings)<br>  variables.tf          every input, with defaults<br>  terraform.tfvars      production values (no secrets)<br>  versions.tf           providers and backend</pre><p>Each module does one thing and exposes only what callers need. The root main.tf reads like a parts list:</p><pre>module &quot;mysql&quot; {<br>  source              = &quot;./modules/mysql&quot;<br>  name                = local.names.mysql_server<br>  resource_group_name = azurerm_resource_group.this.name<br>  location            = azurerm_resource_group.this.location<br>  subnet_id           = module.network.subnet_ids.mysql<br>  virtual_network_id  = module.network.vnet_id<br>  sku_name            = var.mysql_sku_name<br>  storage_size_gb     = var.mysql_storage_size_gb<br>  tags                = local.tags<br>}</pre><h3>A naming module</h3><p>Azure names have different rules per resource type. Storage accounts allow 24 lowercase characters and no hyphens. Key Vault allows 24 characters with hyphens. Registries allow 50 alphanumerics. Rather than scattering string templates everywhere, one module builds every name from four inputs:</p><pre>locals {<br>  base    = join(&quot;-&quot;, [var.project, var.workload, var.environment, var.location_short])<br>  compact = replace(local.base, &quot;-&quot;, &quot;&quot;)</pre><pre>  generated = {<br>    resource_group     = &quot;rg-${local.base}&quot;<br>    virtual_network    = &quot;vnet-${local.base}&quot;<br>    aks                = &quot;aks-${local.base}&quot;<br>    mysql_server       = &quot;mysql-${local.base}&quot;<br>    log_analytics      = &quot;log-${local.base}&quot;<br>    # Trim the base, never the suffix: the suffix is what makes a clashing name unique.<br>    storage_account    = &quot;${substr(&quot;st${local.compact}&quot;, 0, 24 - length(var.unique_suffix))}${var.unique_suffix}&quot;<br>    key_vault          = &quot;${substr(&quot;kv${local.compact}&quot;, 0, 24 - length(var.unique_suffix))}${var.unique_suffix}&quot;<br>    container_registry = &quot;${substr(&quot;cr${local.compact}&quot;, 0, 50 - length(var.unique_suffix))}${var.unique_suffix}&quot;<br>  }</pre><pre>  names = merge(local.generated, var.name_overrides)<br>}</pre><p>The same module produces the tags (project, environment, managed_by = &quot;terraform&quot;, plus anything extra). Every resource gets the same tags, which matters later for cost reporting.</p><h3>State: solving the chicken and egg problem</h3><p>Terraform state for production must live somewhere durable, shared, and locked. On Azure that means a storage account. But Terraform is also what should create that storage account. The usual answer is a small, separate configuration that runs once.</p><h3>The bootstrap configuration</h3><p>terraform/bootstrap creates only the state storage:</p><pre>resource &quot;azurerm_storage_account&quot; &quot;state&quot; {<br>  name                            = &quot;YOUR_STATE_STORAGE_ACCOUNT&quot;<br>  resource_group_name             = azurerm_resource_group.state.name<br>  location                        = azurerm_resource_group.state.location<br>  account_tier                    = &quot;Standard&quot;<br>  account_replication_type        = &quot;GRS&quot;<br>  min_tls_version                 = &quot;TLS1_2&quot;<br>  allow_nested_items_to_be_public = false<br>  shared_access_key_enabled       = false # Entra ID only, no account keys</pre><pre>  blob_properties {<br>    versioning_enabled = true<br>    delete_retention_policy           { days = 30 }<br>    container_delete_retention_policy { days = 30 }<br>  }<br>}</pre><pre>resource &quot;azurerm_management_lock&quot; &quot;state&quot; {<br>  name       = &quot;do-not-delete-terraform-state&quot;<br>  scope      = azurerm_storage_account.state.id<br>  lock_level = &quot;CanNotDelete&quot;<br>}</pre><p>The choices here protect the most valuable file in the project:</p><ul><li><strong>GRS replication</strong> keeps a copy in the paired region.</li><li><strong>Versioning plus 30 days of soft delete</strong> means a corrupted or deleted state file can be restored.</li><li><strong>Shared keys disabled</strong> forces Entra ID authentication. There is no account key to leak.</li><li><strong>A delete lock</strong> stops anyone, including Terraform, from deleting the account without first removing the lock on purpose.</li></ul><h3>Moving the bootstrap’s own state into the account</h3><p>The bootstrap starts with local state, because the storage does not exist yet. After the first apply, it moves its own state into the account it just created:</p><pre># terraform/bootstrap/backend.tf, added after the first apply<br>terraform {<br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-myapp-tf-prod-scus&quot;<br>    storage_account_name = &quot;YOUR_STATE_STORAGE_ACCOUNT&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;myapp/bootstrap.tfstate&quot;<br>    use_azuread_auth     = true<br>  }<br>}</pre><pre>terraform -chdir=terraform/bootstrap init -migrate-state</pre><p>Now both configurations keep state in the same account under different keys, and no state file lives on a laptop.</p><h3>The production backend</h3><p>The main configuration writes the backend out in full. Backend blocks cannot read variables, so the names are literal, with a comment saying where they come from:</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.9.0&quot;</pre><pre>  required_providers {<br>    azurerm = { source = &quot;hashicorp/azurerm&quot;, version = &quot;~&gt; 4.0&quot; }<br>    random  = { source = &quot;hashicorp/random&quot;, version = &quot;~&gt; 3.6&quot; }<br>  }</pre><pre>  backend &quot;azurerm&quot; {<br>    resource_group_name  = &quot;rg-myapp-tf-prod-scus&quot;<br>    storage_account_name = &quot;YOUR_STATE_STORAGE_ACCOUNT&quot;<br>    container_name       = &quot;tfstate&quot;<br>    key                  = &quot;myapp/prod.tfstate&quot;<br>    use_azuread_auth     = true<br>  }<br>}</pre><p>Writing the backend in full means terraform init needs no -backend-config flags. A new engineer signs in with az login, exports one variable, and runs init:</p><pre>az login --tenant YOUR_TENANT_ID<br>export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)<br>terraform -chdir=terraform init</pre><h3>One provider gotcha worth knowing</h3><p>With storage_use_azuread = true, the azurerm provider also tries to read storage data plane properties (queue and static website settings) using Entra ID. If the operator has no data role on the account, the first apply fails with a 403. Containers are managed through the ARM API anyway, so the fix is to tell the provider not to touch the data plane:</p><pre>provider &quot;azurerm&quot; {<br>  storage_use_azuread = true<br>  features {<br>    storage {<br>      data_plane_available = false<br>    }<br>  }<br>}</pre><p>The lock file (.terraform.lock.hcl) is committed, so every machine and the pipeline use the same provider build.</p><h3>Network design: keep the data tier off the internet</h3><p>The goal is simple. Only the ingress controller faces the internet. The database, cache, and anything holding data are reachable only from inside the virtual network.</p><pre>variable &quot;vnet_address_space&quot; {<br>  default = [&quot;10.20.0.0/16&quot;]<br>}</pre><pre>variable &quot;subnet_prefixes&quot; {<br>  default = {<br>    aks       = &quot;10.20.0.0/22&quot;   # nodes<br>    mysql     = &quot;10.20.9.0/27&quot;   # delegated to MySQL Flexible Server<br>    endpoints = &quot;10.20.10.0/27&quot;  # private endpoints<br>  }<br>}</pre><p>A few points behind these numbers:</p><ul><li><strong>The AKS subnet is a /22 even though there are only a handful of nodes.</strong> With Azure CNI Overlay (Part 2), pods get addresses from a separate overlay range, not from this subnet. The /22 leaves room for node growth and upgrade surge nodes.</li><li><strong>MySQL needs its own delegated subnet.</strong> VNet-integrated Flexible Server requires a subnet delegated to Microsoft.DBforMySQL/flexibleServers, and nothing else can live in it.</li><li><strong>Private endpoints need a subnet that is not delegated.</strong> A delegated subnet cannot hold private endpoints, so they get their own.</li></ul><h3>MySQL with VNet integration</h3><p>The database has no public endpoint at all. It is injected into its subnet and resolves through a private DNS zone linked to the VNet:</p><pre>resource &quot;azurerm_private_dns_zone&quot; &quot;this&quot; {<br>  name                = &quot;${var.name}.private.mysql.database.azure.com&quot;<br>  resource_group_name = var.resource_group_name<br>}</pre><pre>resource &quot;azurerm_private_dns_zone_virtual_network_link&quot; &quot;this&quot; {<br>  name                  = &quot;${var.name}-vnet-link&quot;<br>  resource_group_name   = var.resource_group_name<br>  private_dns_zone_name = azurerm_private_dns_zone.this.name<br>  virtual_network_id    = var.virtual_network_id<br>}</pre><pre>resource &quot;azurerm_mysql_flexible_server&quot; &quot;this&quot; {<br>  name                   = var.name<br>  resource_group_name    = var.resource_group_name<br>  location               = var.location<br>  sku_name               = var.sku_name<br>  administrator_login    = var.admin_username<br>  administrator_password = random_password.admin.result<br>  delegated_subnet_id    = var.subnet_id<br>  private_dns_zone_id    = azurerm_private_dns_zone.this.id<br>  backup_retention_days  = var.backup_retention_days</pre><pre>  storage {<br>    size_gb           = var.storage_size_gb<br>    auto_grow_enabled = true<br>  }</pre><pre>  depends_on = [azurerm_private_dns_zone_virtual_network_link.this]</pre><pre>  lifecycle {<br>    # Azure picks and may swap zones on failover; don&#39;t fight it on every plan.<br>    ignore_changes = [zone]<br>  }<br>}</pre><p>TLS is required on the server. The application container trusts the system CA bundle, which already includes the roots Azure uses, so no certificate file needs shipping.</p><h3>Private endpoints for platform services</h3><p>For a managed cache, the pattern is a private endpoint plus a privatelink DNS zone. The DNS zone group registers the service&#39;s normal hostname against the private IP, so application config does not change:</p><pre>resource &quot;azurerm_private_endpoint&quot; &quot;this&quot; {<br>  name                = &quot;pe-${var.name}&quot;<br>  resource_group_name = var.resource_group_name<br>  location            = var.location<br>  subnet_id           = var.subnet_id</pre><pre>  private_service_connection {<br>    name                           = &quot;${var.name}-connection&quot;<br>    private_connection_resource_id = azurerm_managed_redis.this.id<br>    subresource_names              = [&quot;redisEnterprise&quot;]<br>    is_manual_connection           = false<br>  }</pre><pre>  private_dns_zone_group {<br>    name                 = &quot;default&quot;<br>    private_dns_zone_ids = [azurerm_private_dns_zone.this.id]<br>  }<br>}</pre><p>The cache itself sets public_network_access = &quot;Disabled&quot;.</p><h3>What is not private yet</h3><p>Key Vault and the document storage account still have public endpoints, protected by Entra ID RBAC and TLS. Moving them behind private endpoints uses the same pattern and is on the follow-up list. It is listed here on purpose. A design document that admits its gaps is more useful than one that pretends to be finished.</p><h3>Secrets: generated by Terraform, stored in Key Vault</h3><p>Nobody types a database password. Terraform generates it, stores it in Key Vault, and the cluster reads it from there (Part 3 shows how):</p><pre>resource &quot;random_password&quot; &quot;admin&quot; {<br>  length           = 32<br>  special          = true<br>  override_special = &quot;-_=+.:&quot;<br>}</pre><pre>module &quot;key_vault&quot; {<br>  source  = &quot;./modules/key_vault&quot;<br>  secrets = {<br>    &quot;db-password&quot;               = module.mysql.admin_password<br>    &quot;storage-connection-string&quot; = module.app_storage.primary_connection_string<br>  }<br>}</pre><p>The vault uses RBAC authorisation (not access policies) and purge protection.</p><p>Two rules follow from generating secrets in Terraform:</p><ol><li><strong>State contains secrets.</strong> That is one more reason for Entra-only access to the state account.</li><li><strong>Plan files contain secrets in clear text.</strong> The pipeline never uploads a plan file as an artifact, *.tfplan is git-ignored, and local plan files are deleted right after apply.</li></ol><h3>A role assignment trap</h3><p>The first version of the Key Vault module granted <em>Secrets Officer</em> to “whoever runs Terraform” using data.azurerm_client_config.current.object_id. That works for one person. With an operator and a CI service principal both running Terraform, each run gave the role to itself and removed it from the other. The pipeline then failed with a 403 the next time it tried to read a secret.</p><p>The fix is a fixed list keyed by object ID, with the caller merged in:</p><pre>locals {<br>  admin_principal_ids = toset(concat(<br>    [data.azurerm_client_config.current.object_id],<br>    var.admin_principal_ids,<br>  ))<br>}</pre><pre>resource &quot;azurerm_role_assignment&quot; &quot;secrets_officer&quot; {<br>  for_each             = local.admin_principal_ids<br>  scope                = azurerm_key_vault.this.id<br>  role_definition_name = &quot;Key Vault Secrets Officer&quot;<br>  principal_id         = each.value<br>}</pre><p>Changing a single resource into a for_each map would normally destroy and recreate it. A moved block tells Terraform the existing assignment is now one entry in the map:</p><pre>moved {<br>  from = module.key_vault.azurerm_role_assignment.secrets_officer<br>  to   = module.key_vault.azurerm_role_assignment.secrets_officer[&quot;OPERATOR_OBJECT_ID&quot;]<br>}</pre><h3>Infrastructure as code practices that paid off</h3><h3>Test the wiring with mocked providers</h3><p>terraform test with mock_provider runs in seconds, needs no Azure access, and catches wiring mistakes before a plan ever touches production. Child modules can be replaced by fixed outputs, so a root test checks only what the root does:</p><pre>mock_provider &quot;azurerm&quot; {}</pre><pre>override_module {<br>  target  = module.mysql<br>  outputs = {<br>    id             = &quot;/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.DBforMySQL/flexibleServers/mysql&quot;<br>    fqdn           = &quot;mysql-test.mysql.database.azure.com&quot;<br>    admin_username = &quot;dbadmin&quot;<br>    admin_password = &quot;not-a-real-password&quot;<br>  }<br>}</pre><pre>run &quot;pods_get_the_database_host_from_terraform&quot; {<br>  command = plan</pre><pre>  assert {<br>    condition     = output.app_runtime_settings.DB_HOST == &quot;mysql-test.mysql.database.azure.com&quot;<br>    error_message = &quot;DB_HOST must come from the MySQL module&quot;<br>  }<br>}</pre><p>Two lessons from running these tests for a few months:</p><ul><li><strong>Mocked IDs must look like real IDs.</strong> Some resources validate their inputs even under a mock provider. An alert rule rejects a scope of&quot;mysql-id&quot;, so overrides use full ARM IDs.</li><li><strong>terraform test reads </strong><strong>terraform.tfvars.</strong> A test that checks <em>defaults</em> starts failing the day production values change in tfvars. Split tests into two kinds. Runs with no variables check what production actually runs. Runs that test another scenario set every switch they depend on.</li></ul><h3>A pipeline that plans, waits, and applies the reviewed plan</h3><p>The infrastructure pipeline runs on pushes to a dedicated terraform branch:</p><ol><li>fmt -check, validateand every module&#39;s tests.</li><li>plan -detailed-exitcode. Exit code 2 means there are changes, and only then is the apply job created.</li><li>The apply job runs in a GitHub environment with required reviewers. It waits for a human.</li><li>After approval, it plans again with-out, and applies exactly that file.</li></ol><pre>- name: terraform plan<br>  run: |<br>    set +e<br>    terraform -chdir=terraform plan -lock-timeout=5m -detailed-exitcode -no-color &gt; plan.txt 2&gt;&amp;1<br>    rc=$?<br>    set -e<br>    case $rc in<br>      0) echo &quot;has_changes=false&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot; ;;<br>      2) echo &quot;has_changes=true&quot;  &gt;&gt; &quot;$GITHUB_OUTPUT&quot; ;;<br>      *) exit $rc ;;<br>    esac</pre><p>A concurrency group (cancel-in-progress: false) makes sure two runs never apply at once, and a running apply is never cancelled halfway. Destroy exists only as a manual run that needs a typed confirmation plus the same approval.</p><h3>Preventing drift</h3><p>Drift is any difference between the code and what is running. These habits kept it close to zero:</p><ul><li><strong>No portal edits.</strong> If something must change, it changes in code.</li><li><strong>Ignore only what Azure legitimately owns.</strong> The node count belongs to the cluster autoscaler, and the MySQL zone can change on failover. Those two get ignore_changes. Nothing else does.</li><li><strong>Refactor with </strong><strong>moved blocks.</strong> When a module became optional (count), a moved block mapped module.redis to module.redis[0], and the plan showed a rename instead of a destroy.</li><li><strong>“No changes” is a test.</strong> After any manual apply from a workstation, the change is pushed, and the pipeline’s plan must come back as No changes. If it doesn&#39;t, someone stops and finds out why.</li></ul><h3>One near miss, and the rule it produced</h3><p>During the cost work in Part 5, five staged changes sat interraform.tfvars, each commented out, to be applied one at a time. One commit uncommented all five, and it was merged to the terraform branch. The pipeline planned all of them together, including deleting the cache while the application still used it. The environment approval gate caught it: the plan was rejected, and nothing ran.</p><p>The rule since then: <strong>read the plan summary before every approval, and treat any plan that does more than the change you intended as a stop sign.</strong> The approval gate is only useful if someone reads what they approve.</p><h3>Summary</h3><ul><li>Keep state in its own locked, versioned, Entra-only storage account, created by a small bootstrap configuration that migrates its own state.</li><li>Keep the data tier private: delegated subnet for MySQL, private endpoints for platform services, private DNS zones linked to the VNet.</li><li>Generate secrets in Terraform, store them in Key Vault, and treat state and plan files as secrets.</li><li>Test module wiring with mocked providers, gate applies behind a human review, and use “No changes” as proof that code and cloud agree.</li></ul><p><em>Part 2 builds the AKS cluster on top of this network.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63aa943c3b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built and Shipped an AI Product Alone. Here Is What That Looked Like.]]></title>
            <link>https://medium.com/@lilstex4good/i-built-and-shipped-an-ai-product-alone-here-is-what-that-looked-like-ebd06a7bcfa0?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd06a7bcfa0</guid>
            <category><![CDATA[entrepreneur]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tech-startups]]></category>
            <category><![CDATA[solvedcv]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-28T08:01:02.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6m5WsbvexYqRLWjyJC5SA.png" /></figure><p>I want to be honest about something most polished product launches do not show you. SolvedCV was not built by a team. There is no funding behind it. It is one engineer, me, designing, building, and shipping every part of it alone.</p><p>I am writing this partly to share what that process actually looked like, and partly because I think more people should see the unfiltered version of building something, not just the finished product.</p><h3>What building alone actually means day to day</h3><p>It means every decision is yours, for better or worse. No one to split the backend from the frontend with. No designer to hand mockups to. No one to tell you an idea is bad before you spend a week building it. You design the database, write the AI prompts, build the payment integration, style the interface, and fix the bugs, all of it, one task at a time.</p><p>It also means progress is slower than a funded team moving in parallel, but every part of the product is something you actually understand deeply, because you built it yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydFXo20Eftt9JJdYa0b45Q.png" /></figure><h3>The approach that actually worked</h3><p>Ship one working piece, then the next one. I did not try to build a complete, polished product before letting anyone use it. I built the core flow first: paste a job description, get a tailored resume, and made sure that worked well before adding anything else. Cover letters came after. Freelance proposals came after that. The application tracker came later still.</p><p>Trying to build everything at once, alone, with no team to catch mistakes early, is a good way to spend months building things nobody asked for. Shipping small, working pieces kept me honest about what actually mattered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJ5fzI_vlvIdnRqU_ilhLQ.png" /></figure><h3>What I would tell someone starting the same way</h3><p>Do not wait for the product to feel finished before putting it in front of real people. It will never feel finished. Pick the one thing that solves a real problem, ship that, and let actual usage tell you what to build next, instead of guessing in isolation.</p><p>And be honest about the constraints. No funding and no team are real limitations, but they also force a kind of focus that is easy to lose when resources are not scarce. Every feature had to earn its place, because I was the one who had to build it.</p><h3>Where this goes next</h3><p>I am continuing to build SolvedCV in the open, sharing real numbers and real lessons as they come, not a polished highlight reel. If you are building something alone too, or just curious how a solo-built AI product actually comes together, I will keep sharing what I am learning.</p><p>And if you are job hunting or freelancing, I would genuinely appreciate you trying SolvedCV and telling me what does not work. That feedback is most of how this gets better from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QH-DeXHxB7w5Emh88EIJw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd06a7bcfa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why SolvedCV Charges Per Use, Not a Monthly Fee]]></title>
            <link>https://medium.com/@lilstex4good/why-solvedcv-charges-per-use-not-a-monthly-fee-c52d70fb01a4?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c52d70fb01a4</guid>
            <category><![CDATA[ai-resume-builder]]></category>
            <category><![CDATA[solvedcv]]></category>
            <category><![CDATA[ats-resume]]></category>
            <category><![CDATA[resume-tips]]></category>
            <category><![CDATA[freelancing]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-27T08:01:02.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biVCHuT2anQcDBKROOWKPA.png" /></figure><p>Most tools in this space work on a subscription. You pay every month, whether you used the tool that month or not. SolvedCV does not work that way, and I want to explain why, because it was a deliberate decision, not an accident.</p><h3>The problem with subscriptions for this specific product</h3><p>Job hunting is not a constant activity. You might apply heavily for a few weeks, then go quiet for a while, then get busy again. Once you land a job, you stop needing the tool entirely, often for months or years. A subscription model charges you the same amount regardless of whether you are in an active search or not, which means you either overpay during quiet periods, or you forget to cancel after you get hired and keep getting billed for a tool you no longer need.</p><p>Freelancers have a similar pattern. Some weeks you are sending proposals constantly. Other weeks you are mostly doing client work and barely applying to anything new.</p><p>A flat monthly fee does not match how people actually use this kind of tool.</p><h3>How SolvedCV pricing works instead</h3><p>You buy credits, and you use them when you generate a document. Apply heavily one month, use more credits. Go quiet for a while, spend nothing. Once you land the job or wrap up your freelance pipeline, you simply stop buying credits. Nothing keeps charging you in the background.</p><p>Credits do not expire, so there is no pressure to use them before some arbitrary deadline either.</p><p>Pricing is also shown in your own currency automatically, Naira or Dollars depending on where you are, instead of forcing everyone onto a single US-dollar price that does not reflect local cost of living.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1p2NBADYJCDnuBpRYCRgg.png" /></figure><h3>Why this matters beyond just saving money</h3><p>A job search already costs something, even beyond money. Time, energy, the mental weight of waiting to hear back. The tools you use for it should not add another ongoing cost on top of that, especially not one that keeps charging after you no longer need it. Paying only for what you actually use felt like the more honest way to price this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvBIGKg6oM8A1xaUrDdlBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8F0ii5_i013ZD9_1NqaQQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c52d70fb01a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Resume Cannot Be the Right Fit for Fifty Different Jobs]]></title>
            <link>https://medium.com/@lilstex4good/one-resume-cannot-be-the-right-fit-for-fifty-different-jobs-ddd8d0412710?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddd8d0412710</guid>
            <category><![CDATA[ats-resume]]></category>
            <category><![CDATA[ai-resume-builder]]></category>
            <category><![CDATA[solvedcv]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[resume-tips]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 08:01:01 GMT</pubDate>
            <atom:updated>2026-10-26T08:01:01.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruXOw6JpEq6D85jCAZ2v7g.png" /></figure><p>Most people job hunting have one resume file. One. They open it, change the company name in the cover letter if they even write one, and send it off. Then they do the exact same thing for the next job, and the one after that.</p><p>This feels efficient. It is actually the opposite.</p><h3>Why one resume stops working</h3><p>Every job posting is different, even within the same role title. A “Marketing Manager” role at a startup wants someone scrappy who can do a bit of everything. The same title at a large company wants someone who can manage a team and a budget. If your resume says the same thing for both applications, it is not really speaking to either one.</p><p>Hiring managers and recruiters can tell. A resume that reads generically signals that you sent it everywhere, which quietly signals that you are not especially interested in this specific role. Even if that is not true, it is the impression a generic resume leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1gu_2R6VB3fyPBIpaBxJw.png" /></figure><h3>What tailoring actually looks like</h3><p>Tailoring does not mean lying or inventing experience you do not have. It means choosing which parts of your real experience to highlight, and how to describe them, based on what this specific job is asking for. The same person, the same work history, described slightly differently depending on what the job actually needs to hear.</p><p>Done by hand, this takes real time. You have to read the job post carefully, figure out what matters most, and rewrite sections of your resume to reflect it. Most people do not have the time to do that for every single application, so they do not do it at all.</p><h3>Building it once, using it everywhere</h3><p>This is the actual reason SolvedCV exists. You build your profile one time, with your real work experience, skills, and projects. After that, every application is: paste the job post, let the AI tailor it, download. Under a minute, every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K69ueIcxh3dx1FSMKjIYow.png" /></figure><p>You are not writing a new resume from scratch for every job. You are generating the right version of the resume you already have, specific to that one opportunity. That is the difference between one resume sent fifty times and fifty resumes, each one actually built for the job it is going to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNhY1emQYT5pe7gdDw1ZQQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddd8d0412710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Resume Is Read by Software Before a Human Ever Sees It]]></title>
            <link>https://medium.com/@lilstex4good/your-resume-is-read-by-software-before-a-human-ever-sees-it-d880810bb911?source=rss-765a8e4dabc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d880810bb911</guid>
            <category><![CDATA[resume-tips]]></category>
            <category><![CDATA[solvedcv]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[ats-resume]]></category>
            <category><![CDATA[ai-resume-builder]]></category>
            <dc:creator><![CDATA[Emmanuel Mbagwu]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-24T08:01:02.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUenxOzi7at348jRRSI38g.png" /></figure><p>Here is something a lot of job seekers do not fully realize. When you apply to a job at most mid-size or large companies, your resume usually does not go straight to a human. It goes through software first, called an applicant tracking system, or ATS. That software scans your resume, compares it against the job description, and decides whether it gets passed along to a recruiter at all.</p><p>This matters because a resume that would impress a human reader can still get filtered out before anyone sees it, simply because of how it is written or formatted.</p><h3>What actually trips up a resume</h3><p>A few common issues cause good resumes to get missed. The resume does not use the same language as the job post. If the job post says “project management” and your resume only says “coordinated team deliverables,” the system may not connect the two, even though they mean the same thing. The formatting is too complex for the software to read cleanly, things like tables, columns, or text inside graphics. And the resume is generic, sent unchanged to every job, instead of reflecting the specific language and priorities of that posting.</p><p>None of this means you are unqualified. It means the resume was not built to be read by both a machine and a human.</p><h3>What a tailored resume actually fixes</h3><p>A resume tailored to a specific job description naturally picks up the language that job actually uses, because it is built by reading that exact posting. It keeps formatting clean and simple, which is also easier for a human to skim. And it highlights the parts of your experience that are most relevant to that role, instead of listing everything you have ever done in the same order every time.</p><p>This is the entire reason SolvedCV exists. You paste the job description, and it generates a resume that is tailored to that posting specifically, built to get through the initial screening and still read well to the person on the other side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVU45lVQIv39UnVHr3KUVw.png" /></figure><h3>The simple takeaway</h3><p>Tailoring your resume per job is not a nice extra step anymore. For a lot of applications, it is the difference between getting a reply and getting filtered out silently, without ever knowing why. The good news is that tailoring does not have to take you thirty minutes per application. It can take under a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGZXbUPE6_cWgeDyCkbHVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIzp7xP2UGaJGfJCCfqHsQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d880810bb911" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>