<?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 Rob McBryde on Medium]]></title>
        <description><![CDATA[Stories by Rob McBryde on Medium]]></description>
        <link>https://medium.com/@robert_mcbryde?source=rss-b49cd92f1dee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HmLDdA3fOJNQuoryvgJx_A.jpeg</url>
            <title>Stories by Rob McBryde on Medium</title>
            <link>https://medium.com/@robert_mcbryde?source=rss-b49cd92f1dee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:40:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robert_mcbryde/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[Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 6: The infra Workspace and cdk…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-quality-in-a-ci-cd-pipeline-stage-by-stage-part-6-the-infra-workspace-and-cdk-bd8700ba3155?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd8700ba3155</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[qa]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 23:29:18 GMT</pubDate>
            <atom:updated>2026-11-24T23:29:18.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 6: The infra Workspace and cdk bootstrap</h3><p>By the end of this post you’ll have an infra workspace in the <a href="https://github.com/rob212/mood-check">Mood Check repo</a>, with the <a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">AWS CDK</a> installed at pinned versions and type-checked by the build gate we already have. You&#39;ll also have run a one-off cdk bootstrap against the beta account. This follows on from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8?postPublishedType=repub">Part 5: AWS Accounts, Budget Alarms and CLI Access</a>.</p><blockquote><strong>Why infrastructure as code, and why the CDK.</strong> Infrastructure as code means describing your cloud resources in files, not clicking them together in a console. Those files live in git, so changes are reviewed, repeatable and easy to undo. The same code can create beta and prod, and later a pipeline can run it with no one at a keyboard. <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8?postPublishedType=repub">Part 5’s</a> accounts were set up by hand. From here on, anything that runs in them should be described in code.</blockquote><p>The <a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">AWS Cloud Development Kit (CDK)</a> lets me write that code in TypeScript, the language the rest of this project already uses. It turns the code into CloudFormation templates, which AWS then deploys. Because it’s ordinary TypeScript, the gates we already have, such as type-checking, linting and tests, can apply to it too. The trade-off is that the CDK sits on top of CloudFormation, so some errors come from CloudFormation and not from your own code. This part sets up the tooling. The first real infrastructure comes in Part 7.</p><p>You’ll need the moodcheck-beta profile from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8?postPublishedType=repub">Part 5</a>, and a signed-in session:</p><pre>aws sso login --sso-session rob-sso<br>aws sts get-caller-identity --profile moodcheck-beta</pre><p>Check the Account in the output is your beta account before you go any further. Every command from Step 7 onwards changes that account.</p><h3>Step 1: Create the infra workspace</h3><p>From the repo root:</p><pre>mkdir infra</pre><p>Create infra/package.json:</p><pre>{<br>  &quot;name&quot;: &quot;infra&quot;,<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;<br>}</pre><p>Then add it to the workspaces array in the root package.json:</p><pre>&quot;workspaces&quot;: [<br>  &quot;web&quot;,<br>  &quot;infra&quot;<br>],</pre><p>private stops the package being published to npm by accident. &quot;type&quot;: &quot;module&quot; makes the folder&#39;s JavaScript and TypeScript files ES modules, the same as web.</p><blockquote><strong>Why list the workspace by name:</strong> the project rule is explicit workspaces, never a wildcard. A stray folder with a package.json can&#39;t then join the build or the lockfile without someone editing this array. The trade-off is one more line to edit for each new workspace.</blockquote><h3>Step 2: Install the CDK, pinned</h3><p>Install everything infra needs in one command, run as a single line:</p><pre>npm install --save-dev --save-exact --workspace infra aws-cdk-lib@2.278.0 constructs@10.8.1 aws-cdk@2.1149.0 typescript@~6.0.0 &quot;@types/node@^24&quot;</pre><ul><li>--workspace infra installs into infra/package.json. The packages are hoisted into the root node_modules and recorded in the single root package-lock.json.</li><li>aws-cdk-lib is the construct library, constructs is the base package it builds on, and aws-cdk is the command-line tool that synthesises and deploys. These were the current versions when I wrote this. Yours will be newer.</li><li>--save-exact writes 2.278.0 rather than ^2.278.0.</li></ul><p>That flag applies to every package in the command, so open infra/package.json and set the “@types/node” and “typescript” back to the ranges web uses:</p><pre>&quot;devDependencies&quot;: {<br>  &quot;@types/node&quot;: &quot;^24.19.2&quot;,<br>  &quot;aws-cdk&quot;: &quot;2.1149.0&quot;,<br>  &quot;aws-cdk-lib&quot;: &quot;2.278.0&quot;,<br>  &quot;constructs&quot;: &quot;10.8.1&quot;,<br>  &quot;typescript&quot;: &quot;~6.0.0&quot;<br>}</pre><p>Run npm install again from the root, then check what you have:</p><pre>npm ls aws-cdk-lib aws-cdk constructs</pre><p>You should see all three listed under infra@0.0.0.</p><blockquote><strong>Why pin the CDK exactly:</strong> aws-cdk-lib ships almost weekly. With a ^ range, a fresh install can change the CloudFormation your code generates without you touching any code. The lockfile already protects npm ci, but an exact pin makes the intent visible in review, and an upgrade becomes a deliberate commit. It&#39;s the same rule as Prettier and Husky.</blockquote><blockquote><strong>Why the library and the CLI have different version numbers:</strong> they’re released separately. The CLI must be at least as new as the library, and a newer CLI is fine.</blockquote><blockquote><strong>Why keep TypeScript at </strong><strong>~6.0.0:</strong> web already uses it. If infra pinned a different patch, the next bump to either workspace could leave two copies of TypeScript in the tree, each with its own behaviour. One range, one copy.</blockquote><h3>Step 3: Take cdk.json from a throwaway cdk init</h3><p>cdk.json tells the CLI how to run your app, and it carries a long list of feature flags. Rather than write it by hand, generate one in a scratch folder outside the repo and copy the file in:</p><pre>mkdir /tmp/cdk-scratch &amp;&amp; cd /tmp/cdk-scratch &amp;&amp; ~/code/mood-check/node_modules/.bin/cdk init app --language typescript --generate-only &amp;&amp; cp cdk.json ~/code/mood-check/infra/cdk.json &amp;&amp; cd ~/code/mood-check</pre><p>Then open infra/cdk.json and change only the first app line, to:</p><pre>&quot;app&quot;: &quot;node bin/app.ts&quot;,</pre><ul><li>--generate-only writes the files without running git init or npm install. We only want one file from it.</li><li>~/code/mood-check/node_modules/.bin/cdk is the CLI we just pinned, so the scratch run uses the same version as the repo.</li><li>The &amp;&amp; between every command means a failure stops the chain, so a failed mkdir can&#39;t leave cdk init running inside your repo.</li><li>The generated app line runs npx tsc &amp;&amp; npx tsx .... Ours replaces it with node bin/app.ts. Step 4 explains why that works.</li></ul><blockquote><strong>Why take the file from </strong><strong>cdk init:</strong> it contains about ninety feature flags that opt a new app into current construct defaults. A hand-written cdk.json without them gets the legacy behaviour for some constructs, including some CloudFront and S3 settings we&#39;ll depend on in Part 7. Existing apps keep old behaviour so upgrades don&#39;t change their templates. A new app has no reason to.</blockquote><h3>Step 4: Configure TypeScript so Node can run it directly</h3><p>Create infra/tsconfig.json:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2023&quot;,<br>    &quot;module&quot;: &quot;NodeNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;NodeNext&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;erasableSyntaxOnly&quot;: true,<br>    &quot;verbatimModuleSyntax&quot;: true,<br>    &quot;rewriteRelativeImportExtensions&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;types&quot;: [&quot;node&quot;]<br>  },<br>  &quot;include&quot;: [&quot;bin&quot;, &quot;lib&quot;]<br>}</pre><ul><li>noEmit makes tsc type-check only. Node runs the .ts source itself, so there is no compiled output to ignore or commit.</li><li>erasableSyntaxOnly makes tsc reject TypeScript syntax that has to be transformed rather than just deleted: enums, namespaces and constructor parameter properties.</li><li>verbatimModuleSyntax requires import type for type-only imports, so it&#39;s clear which imports Node can erase.</li><li>rewriteRelativeImportExtensions lets you write .ts in relative imports, which Node needs.</li><li>strict is the same strictness as web.</li></ul><blockquote><strong>Why let Node run the TypeScript:</strong> Node 24 strips type annotations from .ts files itself. That means no ts-node or tsx to install, pin and keep patched, and one less moving part under the deploy command. The app line in cdk.json is just node bin/app.ts.</blockquote><p><strong>The trade-off:</strong> Node only deletes types. It can’t transform syntax, so enums and the other constructs above won’t run. erasableSyntaxOnly turns that into a build error you see early, instead of a crash at deploy time. Relative imports also need the .ts extension. .nvmrc pins Node 24, which is what makes this safe.</p><h3>Step 5: Write the smallest possible app</h3><p>Create infra/bin/app.ts:</p><pre>import { App, Tags } from &#39;aws-cdk-lib&#39;<br><br>const app = new App()<br>Tags.of(app).add(&#39;project&#39;, &#39;moodcheck&#39;)</pre><p>Add a build script to infra/package.json, after &quot;type&quot;: &quot;module&quot;:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsc&quot;<br>},</pre><p>An app is the root of everything CDK deploys. It holds stacks, and stacks hold resources. We have no stacks yet, so there’s nothing to synthesise. You can see that from infra/:</p><pre>cd infra &amp;&amp; npx cdk synth; echo &quot;exit: $?&quot;; cd ..</pre><p>It prints This app contains no stacks and exits with 1. That&#39;s the correct result, and it proves the CLI found cdk.json and ran bin/app.ts.</p><blockquote><strong>Why tag the app, not each resource:</strong> Tags.of(app).add(...) puts project=moodcheck on every resource in every stack we add later. It enforces the project&#39;s tagging rule in one line, so no future stack can forget it.</blockquote><blockquote><strong>Why the script is called </strong><strong>build:</strong> it only type-checks, but the root npm run build runs build in every workspace. Using that name puts infra under the gate we already have, with no change to the root scripts.</blockquote><h3>Step 6: Ignore cdk.out and run the gates</h3><p>Add this line to the root .gitignore:</p><pre>cdk.out</pre><p>Format the new files with the repo’s own Prettier config, then stage everything and run all five gates:</p><pre>npx prettier --write infra<br>git add -A<br>npm test &amp;&amp; npm run lint &amp;&amp; npm run format:check &amp;&amp; npm run build &amp;&amp; npm run sast</pre><p>The build step now runs tsc in infra after the web build, and prints nothing for it. Semgrep&#39;s target count goes up, because the new files are tracked.</p><blockquote><strong>Why </strong><strong>cdk.out:</strong> the existing out entry only matches a directory named exactly out. cdk.out is synthesised output (templates, asset copies and a manifest), generated rather than source. Left unignored, Prettier and Semgrep would start reading it, as with dist in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a">Part 4</a>.</blockquote><blockquote><strong>Why </strong><strong>git add -A first:</strong> Semgrep scans only git-tracked files. Without staging, the new workspace would pass the SAST gate by never being scanned.</blockquote><h3>See the type-check fail</h3><p>A gate only counts once it has been seen to fail. Temporarily add an enum to infra/bin/app.ts after the import line:</p><pre>enum Colour {<br>  Red,<br>}</pre><pre>npm run build -w infra</pre><pre>bin/app.ts:2:6 - error TS1294: This syntax is not allowed when &#39;erasableSyntaxOnly&#39; is enabled.</pre><p>The build exits non-zero. Remove the enum and run it again to confirm it’s green.</p><blockquote><strong>Why this matters:</strong> Node can’t run an enum. Without erasableSyntaxOnly, tsc would accept it, and you&#39;d only find out when cdk deploy crashed. With it, the same mistake fails at the build gate.</blockquote><p>Now the code is building again, commit and push:</p><pre>git add -A<br>git commit -m &quot;Add infra workspace with AWS CDK, pinned, type-checked in the build gate&quot;<br>git push</pre><p>The pre-commit hook from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3</a> runs gitleaks on the commit.</p><h3>Step 7: Bootstrap the beta account, once</h3><p>This is the first command in the series that changes anything in AWS, so check the target first. From the repo root:</p><pre>ACCOUNT=$(aws sts get-caller-identity --profile moodcheck-beta --query Account --output text)<br>echo $ACCOUNT</pre><p>Confirm the number is your moodcheck-beta account, not prod and not the management account. Then:</p><pre>npx cdk bootstrap aws://$ACCOUNT/eu-west-2 --profile moodcheck-beta --tags project=moodcheck</pre><ul><li>--query Account --output text pulls just the account ID out of get-caller-identity, so you don&#39;t type it, and it comes from the same profile that runs the bootstrap.</li><li>aws://$ACCOUNT/eu-west-2 names the account and Region. Bootstrapping is per account and per Region, and naming both leaves no doubt about the target.</li><li>--profile moodcheck-beta uses the SSO credentials from Part 5.</li><li>--tags project=moodcheck tags the bootstrap stack, so the project&#39;s tagging rule covers it too.</li></ul><p>It takes about a minute and ends with a line saying the environment was bootstrapped. It also prints that it used AdministratorAccess as the default execution policy. We&#39;ll come back to that.</p><p>Check what it created:</p><pre>aws cloudformation list-stack-resources --stack-name CDKToolkit --profile moodcheck-beta --query &#39;StackResourceSummaries[].[ResourceType,LogicalResourceId]&#39; --output table<br>aws cloudformation describe-stacks --stack-name CDKToolkit --profile moodcheck-beta --query &#39;Stacks[0].Tags&#39;</pre><p>The first lists a CloudFormation stack’s resources:</p><ul><li>An S3 bucket, StagingBucket, with its bucket policy. This holds file assets: the website files we&#39;ll deploy in Part 7.</li><li>An ECR repository, ContainerAssetsRepository, for container images. We won&#39;t use it, because Mood Check builds no images.</li><li>Five IAM roles: DeploymentActionRole, FilePublishingRole, ImagePublishingRole, LookupRole and CloudFormationExecutionRole, with default policies on the two publishing roles.</li><li>An SSM parameter, CdkBootstrapVersion, which records the bootstrap version.</li></ul><p>The second prints the project=moodcheck tag on the stack.</p><blockquote><strong>Why bootstrap at all:</strong> cdk deploy can&#39;t upload your files or assume deploy roles in an account that doesn&#39;t have these resources. It&#39;s a one-off per account and Region. You&#39;d repeat it for prod, and later for gamma.</blockquote><blockquote><strong>Why run it from the repo root:</strong> if the working directory has a cdk.json, the CLI loads and synthesises your app before it does anything else. Ours has no stacks yet, so the command would stop at &quot;This app contains no stacks&quot; before reaching AWS. Bootstrapping needs only an account, a Region and credentials, so the root, which has no cdk.json, is the right place to run it.</blockquote><p><strong>Cost:</strong> the bucket and repository sit empty until Part 7, so this costs effectively nothing. The moodcheck-beta-monthly budget from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8">Part 5</a> is the backstop.</p><h3>The quality decision</h3><p>This part adds one gate and makes two deliberate decisions about the bootstrap.</p><p><strong>The infra type-check (</strong><strong>npm run build, now including </strong><strong>infra)</strong></p><ul><li>Protects against: type errors in infrastructure code, and TypeScript syntax Node can’t run, reaching a deploy.</li><li>Gates: the root build, which will fail the Build stage in the pipeline.</li><li>Trade-offs: it’s a type-check, not a lint. infra has no lint script yet, and the ESLint config lives in web, so the root lint skips infra silently and reports success. That&#39;s acceptable for five lines of code. It stops being acceptable when there&#39;s a real stack, so I&#39;ll fix it in Part 7. Only erasable TypeScript syntax is allowed.</li></ul><p><strong>The default CloudFormation execution role</strong></p><ul><li>Protects against: nothing. It’s a risk I’m accepting for now.</li><li>What it is: the role CloudFormation uses to create resources during a deploy has AdministratorAccess by default. That&#39;s broader than the project&#39;s least-privilege rule for the pipeline&#39;s deploy roles.</li><li>Trade-offs: beta is an isolated account with a budget alarm, so I’ve accepted the default. When the pipeline arrives, the GitHub OIDC role will assume the bootstrap’s DeploymentActionRole, not an admin role, and I&#39;ll revisit --cloudformation-execution-policies then.</li></ul><p><strong>The default qualifier</strong></p><ul><li>What it is: the bootstrap resources are named cdk-hnb659fds-..., without the moodcheck prefix.</li><li>Trade-offs: changing the qualifier means configuring it in every app and every environment. Beta and prod are dedicated accounts, so the project tag is enough, and I’ve made this a deliberate exception to the prefix rule.</li></ul><p>One more thing to be honest about: the bootstrap is state in AWS that isn’t described anywhere in the repo, only by the command in this post. That’s normal for CDK, but it’s a manual step to repeat for each account.</p><h3>Where we are, and what’s next</h3><p>Mood Check now has the machinery to deploy infrastructure, though not yet any infrastructure:</p><ul><li><strong>An </strong><strong>infra workspace.</strong> The CDK is pinned exactly, TypeScript is in step with web, and Node runs the code directly with no extra runner.</li><li><strong>A wider build gate.</strong> npm run build now type-checks infra as well as building web, and the type-check has been seen to fail for the right reason.</li><li><strong>A bootstrapped beta account.</strong> The CDKToolkit stack exists in moodcheck-beta in eu-west-2, tagged project=moodcheck. Prod hasn&#39;t been bootstrapped, and I&#39;ll do that when the pipeline needs it.</li></ul><p>In the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, the infra type-check sits in the Build stage, as part of Build Code, and it&#39;s the same gate we&#39;ve had since <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a">Part 4</a>. The bootstrap isn&#39;t a pipeline stage. It&#39;s the groundwork the Test (Beta) and Prod deployments stand on.</p><p>The limits are worth stating:</p><ul><li>infra isn&#39;t linted yet, and the root lint skips it without saying so.</li><li>The bootstrap’s execution role is AdministratorAccess, and it&#39;s not the least-privilege setup the pipeline will need.</li><li>Nothing has been deployed. cdk synth still reports no stacks.</li></ul><p>Next time, in Part 7: we write MoodcheckWebStack, a private S3 bucket with all public access blocked, behind a CloudFront distribution using Origin Access Control. We deploy web/dist into it by hand with --profile moodcheck-beta, open the CloudFront URL, and prove the bucket can&#39;t be reached directly. We&#39;ll also give infra a lint step.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd8700ba3155" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 5: AWS Accounts, Budget Alarms and CLI…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4cab354f5a8</guid>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[qa-automation]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 21:51:31 GMT</pubDate>
            <atom:updated>2026-11-24T22:58:12.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 5: AWS Accounts, Budget Alarms and CLI Access</h3><p>By the end of this post you’ll have two dedicated AWS accounts for Mood Check, one for beta and one for prod, each watched by a budget alarm. You’ll also have command-line access to both through IAM Identity Center, with no long-lived access keys anywhere on your machine. This follows on from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a">Part 4: Build Code and SAST with Semgrep</a>.</p><p><a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a">Part 4 </a>completed the Local Development column of the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>. Everything after it happens in AWS. The Test (Beta) and Prod stages need somewhere to deploy to, and this part builds that somewhere. Part 6 will deploy the web app into it.</p><p>Nothing in this part changes the repo. It’s all AWS setup.</p><p>A caveat before we start. There are many valid ways to set up AWS accounts, and it’s a big subject in its own right. This series is about the pipeline, not account design, so I’ve kept this part to one current baseline that follows AWS’s own guidance. If your company already has a landing zone and gives you accounts, use those and skip to Step 7. This process can obviously be substituted for other cloud providers such as Azure or GCP.</p><p>Strap in, this is a long one.</p><h3>Step 1: Start with an organisation and IAM Identity Center</h3><p>I already had an AWS Organization and IAM Identity Center. So this step is a summary with links rather than a walkthrough. If you’re starting from nothing, you need three things before Step 2:</p><ul><li><strong>A management account.</strong> This is the AWS account that owns the organisation and pays the bills. AWS changed its sign-up in September 2026: a new account starts as a “project”, and <a href="https://aws.amazon.com/blogs/aws/aws-reimagines-the-getting-started-experience/">activating advanced features</a> gives you a full AWS Organization.</li><li><strong>AWS Organizations</strong>, with all features enabled. It lets one management account create and govern member accounts.</li><li><strong>IAM Identity Center</strong>, enabled as an organisation instance in your home Region (mine is eu-west-2, London). Create a user for yourself and turn on MFA.</li></ul><p>The management account itself should hold nothing else. Everything Mood Check runs goes into member accounts, which is Step 2.</p><blockquote><strong>Why Identity Center rather than IAM users:</strong> an IAM user with access keys gives you a secret that lives on disk until someone rotates it. Identity Center gives you one sign-in, protected by MFA, that hands out temporary credentials for any account you’re allowed into. It’s also the simplest way to have one login across several accounts. The trade-off is one more service to set up before you can do anything, which is why it comes first.</blockquote><h3>Step 2: Decide on two dedicated accounts</h3><p>Mood Check gets two new member accounts, moodcheck-beta and moodcheck-prod. A third, for gamma, will arrive later in this series.</p><p>I already have a “General” account I could have used to host my Mood Check application, but I didn’t, for two reasons from AWS’s own guidance:</p><ul><li><strong>Keep workloads out of the management account.</strong> Its reach is the whole organisation, so AWS recommends it runs nothing. My General account is the management account.</li><li><strong>Separate production from non-production.</strong> <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices.html">AWS recommends</a> separate accounts for applications. An account is the strongest isolation boundary AWS has. A tag or a name prefix is much weaker.</li></ul><p>Dedicated accounts make the rest of the series simpler. Each budget covers one account’s whole spend, with no tag filtering. Broad permissions in beta can’t touch anything else. When the series ends, tidying up means closing two accounts.</p><p>The accounts themselves cost nothing. Joining an organisation does end any new-customer Free Tier credits, but the always-free allowances, such as Lambda’s and DynamoDB’s, still apply.</p><blockquote><strong>Naming conventions: Why beta and prod, not dev and prod?</strong> the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS reference architecture </a>names its stages Test (Beta), Test (Gamma) and Prod. These are Amazon’s internal names. Roughly, beta is what many teams call dev or test, and gamma is staging or pre-prod. This may differ for your teams, but for this series I will taking this opionated approach.</blockquote><h3>Step 3: Check the OU policies</h3><p>Organisational units (OUs) group accounts so policies can apply to the whole group. My organisation already had two, DEV and PROD, so beta goes in DEV and prod goes in PROD. If you have none, create them in AWS Organizations: <strong>AWS accounts → Root → Actions → Create new</strong>.</p><p>Before putting accounts in them, check what policies they carry. In AWS Organizations, open each OU and look at its <strong>Policies</strong> tab. Mine showed one service control policy, FullAWSAccess, listed twice: once attached directly to the OU, and once inherited from Root.</p><p><strong>Why check:</strong> service control policies (SCPs) don’t grant permissions. They set the maximum an account is allowed to do, and an action must be allowed at every level from Root down to the account. That’s why AWS attaches FullAWSAccess to every new OU: detach it, and everything inside is denied, admins included. Allow-all at every level means no restriction, which is what I want here. A restrictive SCP would make later deploys fail with access-denied errors that no IAM change can fix. In a real organisation, this is where guardrails go, such as denying every Region you don&#39;t use.</p><h3>Step 4: Create the beta and prod accounts</h3><p>In the management account, open <strong>AWS Organizations → AWS accounts → Add an AWS account → Create an AWS account</strong> and fill in:</p><ul><li><strong>AWS account name:</strong> moodcheck-beta</li><li><strong>Email address of the account’s owner:</strong> an address no other AWS account uses. I used Gmail plus-addressing, in the form you+root-user-moodcheck-beta@gmail.com, which lands in my normal inbox.</li><li><strong>IAM role name:</strong> leave it as OrganizationAccountAccessRole.</li><li><strong>Tags:</strong> project = moodcheck.</li></ul><p>Repeat for moodcheck-prod. Each takes a minute or two to show as <strong>Active</strong>. Then move each into its OU: tick it, then <strong>Actions → Move</strong>.</p><p>I used the console. For reference, the CLI equivalent, run in the management account, is <em>(remember and replace “you” part of your email with your actual email address)</em>:</p><pre>aws organizations create-account \<br>  --account-name moodcheck-beta \<br>  --email you+root-user-moodcheck-beta@gmail.com \<br>  --tags Key=project,Value=moodcheck</pre><p>Open the new account in AWS Organizations and check its <strong>Policies</strong> tab. It now shows FullAWSAccess three times: on the account, on its OU and on Root. That&#39;s the &quot;allowed at every level&quot; rule from Step 3, made visible.</p><p><strong>Why the email matters:</strong> it identifies the account’s root user. Every AWS account has exactly one, and it can do anything; no policy can restrict it. Organizations creates it with no password, so nobody can sign in as root without resetting the password through that inbox. In effect, the inbox is the root key, so protect it with MFA. You won’t use root day to day. You’ll sign in through Identity Center (Step 9). For a production organisation, AWS can also remove member accounts’ root credentials centrally, with root access management. That’s beyond this series.</p><p><strong>Why keep </strong><strong>OrganizationAccountAccessRole:</strong> it&#39;s an admin role inside the new account that trusts the management account. It&#39;s a back door for the management account, but the management account already controls its members, so it adds no new risk. It&#39;s also the way back in if Identity Center access is ever misconfigured.</p><p><strong>Why the tag:</strong> it’s free, and it keeps project=moodcheck consistent from the account down to every resource the series creates.</p><h3>Step 5: Give each account a budget alarm</h3><p>Before anything goes into these accounts, each gets a budget alarm. I created both in the management account, each filtered to one member account. I used CloudShell, the terminal in the console’s footer, which is already signed in as you. I used the CLI rather than the console form because brand-new accounts take a while to appear in the form’s Linked account list, and the API accepts the account ID straight away.</p><p>In CloudShell, in the management account, capture that account’s ID:</p><pre>MGMT_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)<br>echo $MGMT_ACCOUNT</pre><ul><li>aws sts get-caller-identity asks AWS who you&#39;re signed in as.</li><li>--query Account --output text picks out just the account ID as plain text.</li></ul><p>Next, describe the budget in a JSON file. Replace &lt;beta-account-id&gt; with the 12-digit ID of your AWS account for moodcheck-beta:</p><pre>cat &gt; budget-beta.json &lt;&lt; &#39;EOF&#39;<br>{<br>  &quot;BudgetName&quot;: &quot;moodcheck-beta-monthly&quot;,<br>  &quot;BudgetType&quot;: &quot;COST&quot;,<br>  &quot;TimeUnit&quot;: &quot;MONTHLY&quot;,<br>  &quot;BudgetLimit&quot;: {&quot;Amount&quot;: &quot;5&quot;, &quot;Unit&quot;: &quot;USD&quot;},<br>  &quot;CostFilters&quot;: {&quot;LinkedAccount&quot;: [&quot;&lt;beta-account-id&gt;&quot;]}<br>}<br>EOF</pre><ul><li>cat &gt; file &lt;&lt; &#39;EOF&#39; is a here-document. Everything up to the line EOF becomes the file. The quotes around EOF stop the shell expanding anything inside.</li><li>COST, MONTHLY and the BudgetLimit make it a $5-a-month spending budget that resets each month.</li><li>CostFilters with LinkedAccount limits it to one member account&#39;s spend.</li></ul><p>Then the alerts, in a second file, with your own email address:</p><pre>cat &gt; notifications.json &lt;&lt; &#39;EOF&#39;<br>[<br>  {&quot;Notification&quot;: {&quot;NotificationType&quot;: &quot;ACTUAL&quot;, &quot;ComparisonOperator&quot;: &quot;GREATER_THAN&quot;, &quot;Threshold&quot;: 20, &quot;ThresholdType&quot;: &quot;PERCENTAGE&quot;},<br>   &quot;Subscribers&quot;: [{&quot;SubscriptionType&quot;: &quot;EMAIL&quot;, &quot;Address&quot;: &quot;you@example.com&quot;}]},<br>  {&quot;Notification&quot;: {&quot;NotificationType&quot;: &quot;ACTUAL&quot;, &quot;ComparisonOperator&quot;: &quot;GREATER_THAN&quot;, &quot;Threshold&quot;: 100, &quot;ThresholdType&quot;: &quot;PERCENTAGE&quot;},<br>   &quot;Subscribers&quot;: [{&quot;SubscriptionType&quot;: &quot;EMAIL&quot;, &quot;Address&quot;: &quot;you@example.com&quot;}]},<br>  {&quot;Notification&quot;: {&quot;NotificationType&quot;: &quot;FORECASTED&quot;, &quot;ComparisonOperator&quot;: &quot;GREATER_THAN&quot;, &quot;Threshold&quot;: 100, &quot;ThresholdType&quot;: &quot;PERCENTAGE&quot;},<br>   &quot;Subscribers&quot;: [{&quot;SubscriptionType&quot;: &quot;EMAIL&quot;, &quot;Address&quot;: &quot;you@example.com&quot;}]}<br>]<br>EOF</pre><p>Each entry is one alert. PERCENTAGE thresholds are measured against the $5 limit:</p><ul><li><strong>Actual spend over 20% ($1).</strong> The early warning.</li><li><strong>Actual spend over 100% ($5).</strong> The limit has been passed.</li><li><strong>Forecasted spend over 100%.</strong> AWS predicts the month will end over $5.</li></ul><p>Create the budget:</p><pre>aws budgets create-budget \<br>  --account-id &quot;$MGMT_ACCOUNT&quot; \<br>  --budget file://budget-beta.json \<br>  --notifications-with-subscribers file://notifications.json</pre><ul><li>--account-id is the management account&#39;s ID, because that&#39;s where the budget lives. The member account appears only in the filter.</li><li>file:// tells the CLI to read a parameter&#39;s value from a file.</li></ul><p>A successful create prints nothing. For prod, copy the file, change BudgetName to moodcheck-prod-monthly and the account ID to prod&#39;s, and run the same command with --budget file://budget-prod.json:</p><pre>cp budget-beta.json budget-prod.json<br>nano budget-prod.json</pre><p><strong>Why $5 and a $1 alert:</strong> Mood Check should cost pennies a month, so $5 is a round ceiling that’s still low enough to mean something has gone wrong. The $1 alert matters most early on. AWS needs <a href="https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-best-practices.html">about five weeks of usage data</a> before it can forecast, so a forecast alert on a new account stays silent for over a month.</p><p><strong>Why the budgets live in the management account:</strong> both are in one place, and admins inside the member accounts can’t delete them. That includes the pipeline’s roles later in the series. The Linked account filter also only works from the management account. The trade-off is that a budget wouldn’t follow an account that left the organisation.</p><p><strong>Why no budget actions:</strong> actions can apply IAM policies or stop resources when a threshold is crossed. That’s useful in larger estates, but overkill here, and an automatic action that misfires can break things. Budgets without actions are free.</p><h3>Step 6: Read the budgets back</h3><pre>aws budgets describe-budgets --account-id &quot;$MGMT_ACCOUNT&quot; \<br>  --query &#39;Budgets[].{name:BudgetName,limit:BudgetLimit.Amount,filters:CostFilters}&#39;<br>aws budgets describe-notifications-for-budget \<br>  --account-id &quot;$MGMT_ACCOUNT&quot; --budget-name moodcheck-prod-monthly</pre><p>The first lists every budget in the account, with its limit and filter. The second lists the alerts attached to one budget. Mine showed both budgets at 5.0, each with its own LinkedAccount, and three alerts in state OK.</p><p><strong>Why read it back:</strong> every gate in Parts 1 to 4 was seen to fail before I trusted it. I can’t do that with a budget alarm, because triggering it means spending money. This is evidence my budgets are configured as I intended.</p><p>Be clear about what this alarm is. A budget warns; it doesn’t stop spending. Billing data refreshes at least once a day, so an email can arrive hours after the money has gone.</p><h3>Step 7: Install the AWS CLI v2</h3><p>First check nothing is installed already:</p><pre>which -a aws</pre><p>which -a lists every aws on your PATH, not just the first. Mine printed aws not found.</p><p>Then install it with AWS’s install script:</p><pre>curl -fsSL https://awscli.amazonaws.com/v2/install.sh -o install-awscli.sh<br>bash install-awscli.sh<br>rm install-awscli.sh</pre><ul><li>curl -fsSL ... -o downloads the script. -f fails on an HTTP error rather than saving an error page, -sS hides the progress bar but still shows errors, and -L follows redirects.</li><li>bash install-awscli.sh installs it for your user only, into ~/.local/share/aws-cli, with a link in ~/.local/bin. No sudo needed.</li></ul><p>Check it:</p><pre>which aws<br>aws --version</pre><p>Mine printed ~/.local/bin/aws and aws-cli/2.42.1 Python/3.14.10 Darwin/25.6.0 script-exe/arm64. script-exe confirms it came from the install script, and arm64 that it runs natively on Apple Silicon. The CLI bundles its own Python, so it needs nothing from your system.</p><blockquote><strong>Why the install script, not Homebrew:</strong> it’s AWS’s own installer, and the CLI’s aws update command only works for installs made by an official installer. ~/.local/bin was already on my PATH from mise in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-0-prequisties-setting-up-your-machine-0a730c09b255">Part 0</a>, so it worked straight away. The trade-off is one more tool that brew upgrade won&#39;t update: aws update joins mise self-update on my list. Homebrew&#39;s awscli formula would work fine too.</blockquote><h3>Step 8: Create a read-only permission set for prod</h3><p>A permission set is a bundle of permissions in Identity Center. Assigning one to a user for an account creates a matching IAM role in that account.</p><p>Sign in to the management account, switch the console to the Region where Identity Center lives (eu-west-2 for me), and open <strong>IAM Identity Center → Permission sets → Create permission set</strong>:</p><ul><li><strong>Type:</strong> Predefined permission set</li><li><strong>Policy:</strong> ReadOnlyAccess</li><li><strong>Name:</strong> ReadOnlyAccess</li><li><strong>Session duration:</strong> the default, 1 hour</li></ul><p>You’ll also need an AdministratorAccess permission set, created the same way with the AdministratorAccess policy, if you don&#39;t already have one.</p><p><strong>Why read-only for prod:</strong> prod deploys will only ever come from the pipeline, behind a manual approval. If my own login can’t change prod, nobody can skip that approval by deploying from a laptop, me included. Read-only still lets me see what’s running. ReadOnlyAccess can read data as well as configuration. AWS&#39;s stricter ViewOnlyAccess can&#39;t, and would suit a product holding personal data. Mood Check&#39;s data isn&#39;t sensitive.</p><p><strong>Why a 1-hour session is fine:</strong> that’s how long each set of role credentials lasts. The CLI fetches new ones automatically while your Identity Center sign-in is still valid, so you won’t notice.</p><h3>Step 9: Give yourself access to the new accounts</h3><p>In <strong>IAM Identity Center → AWS accounts</strong>:</p><ol><li>Tick moodcheck-beta and choose <strong>Assign users or groups</strong>.</li><li>Tick your user, then <strong>Next</strong>.</li><li>Tick AdministratorAccess, then <strong>Next</strong>, check the summary, and <strong>Submit</strong>.</li><li>Repeat for moodcheck-prod, ticking only ReadOnlyAccess.</li></ol><p>The account list then shows each account with its permission set. Each assignment creates an IAM role in the account named AWSReservedSSO_&lt;PermissionSet&gt;_&lt;random&gt;. That role is what you actually use.</p><blockquote><strong>Why admin on beta:</strong> in the upcoming Part 6, we will be using Infrastructure as Code cdk bootstrap to create IAM roles, an S3 bucket and an ECR repository. A hand-written narrower policy would mean guessing CDK&#39;s exact needs and debugging access-denied errors. Beta is an isolated account with a $5 alarm, so admin there is a reasonable risk. The least-privilege effort goes into the pipeline&#39;s roles, which run unattended.</blockquote><blockquote><strong>Why only one permission set on prod:</strong> you can assign several to one account, and the portal asks which to use at sign-in. Giving myself admin as well would undo the point.</blockquote><p>In a team, you’d assign permission sets to groups rather than to individual users, so joiners and leavers are one group change. With one person, a group adds nothing.</p><h3>Step 10: Configure SSO profiles</h3><p>Back on your Mac terminal:</p><pre>aws configure sso</pre><p>It asks a series of questions. My answers:</p><ul><li><strong>SSO session name:</strong> rob-sso</li><li><strong>SSO start URL:</strong> the access portal URL, shaped like <a href="https://d-xxxxxxxxxx.awsapps.com/start">https://d-xxxxxxxxxx.awsapps.com/start</a></li><li><strong>SSO region:</strong> eu-west-2</li><li><strong>SSO registration scopes:</strong> the default, sso:account:access</li></ul><p>The browser then opens. Sign in to the access portal with MFA and allow the CLI. Back in the terminal, it lists your accounts. Choose moodcheck-beta. It&#39;s the only role there, so it picks AdministratorAccess itself. Then:</p><ul><li><strong>Default client Region:</strong> eu-west-2</li><li><strong>CLI default output format:</strong> json</li><li><strong>Profile name:</strong> moodcheck-beta</li></ul><blockquote>CLI 2.42 then asked whether to configure AWS skills and an MCP server for any AI coding agents on the machine. I answered n. It&#39;s unrelated to CLI access, and giving an AI agent a route into my accounts deserves its own decision.</blockquote><p>Run aws configure sso again with the same session name. It reuses the session details, so you only choose the account, moodcheck-prod with ReadOnlyAccess, plus the Region, the output format and the profile name, moodcheck-prod.</p><p>Now look at what it wrote <em>(my ids and urls redacted, you will have your own)</em>:</p><pre>cat ~/.aws/config<br>ls ~/.aws</pre><pre>[profile moodcheck-beta]<br>sso_session = rob-sso<br>sso_account_id = &lt;beta-account-id&gt;<br>sso_role_name = AdministratorAccess<br>region = eu-west-2<br>output = json<br>[sso-session rob-sso]<br>sso_start_url = https://d-xxxxxxxxxx.awsapps.com/start<br>sso_region = eu-west-2<br>sso_registration_scopes = sso:account:access<br>[profile moodcheck-prod]<br>sso_session = rob-sso<br>sso_account_id = &lt;prod-account-id&gt;<br>sso_role_name = ReadOnlyAccess<br>region = eu-west-2<br>output = json</pre><p>The [sso-session] block is how to sign in. The [profile] blocks say which account and role to use once signed in. Both profiles share one session, so one sign-in serves both. There are no keys or tokens in the file. ls ~/.aws shows cli, config and sso, and no credentials file. sso/cache holds the sign-in token and cli/cache holds the temporary role credentials. Both expire, and both live outside the repo.</p><p><strong>Why the browser step:</strong> the CLI never sees your password or MFA code. You approve it in the browser, which hands a short-lived token back to the CLI on your own machine. The CLI then exchanges that token for temporary role credentials per profile. The older aws configure, with access keys, writes a permanent secret to ~/.aws/credentials. That&#39;s exactly what the project&#39;s &quot;no long-lived keys&quot; rule exists to avoid. If you&#39;re on a machine without a browser, aws sso login --use-device-code gives you a code to enter in a browser elsewhere.</p><h3>Step 11: Prove who you are</h3><pre>aws sts get-caller-identity --profile moodcheck-beta<br>aws sts get-caller-identity --profile moodcheck-prod</pre><pre>{<br>    &quot;UserId&quot;: &quot;AROA...:rob-mcbryde&quot;,<br>    &quot;Account&quot;: &quot;&lt;beta-account-id&gt;&quot;,<br>    &quot;Arn&quot;: &quot;arn:aws:sts::&lt;beta-account-id&gt;:assumed-role/AWSReservedSSO_AdministratorAccess_&lt;random&gt;/rob-mcbryde&quot;<br>}</pre><p>get-caller-identity needs no permissions, so it&#39;s the cleanest test of a profile. Check Account matches the profile&#39;s account, and that the role is the one you assigned: AdministratorAccess for beta, ReadOnlyAccess for prod. assumed-role and the AROA prefix both mean temporary role credentials. An IAM user would show AIDA.</p><h3>Step 12: Prove prod is read-only</h3><p>Try a read, then a write, I expect to be able to list s3 buckets (although there are 0), but shouldn’t be able to make an s3 bucket:</p><pre>aws s3 ls --profile moodcheck-prod; echo &quot;exit code: $?&quot;<br>aws s3 mb s3://moodcheck-prod-write-test-$RANDOM --profile moodcheck-prod; echo &quot;exit code: $?&quot;</pre><ul><li>s3 ls lists buckets. The account is empty, so it prints nothing, and exits 0.</li><li>s3 mb (&quot;make bucket&quot;) should be refused. $RANDOM adds a number, because bucket names are unique across all of AWS.</li></ul><p>The write failed as it should:</p><pre>make_bucket failed: s3://moodcheck-prod-write-test-31959 An error occurred (AccessDenied) when calling the CreateBucket operation: User: arn:aws:sts::&lt;prod-account-id&gt;:assumed-role/AWSReservedSSO_ReadOnlyAccess_&lt;random&gt;/rob-mcbryde is not authorized to perform: s3:CreateBucket on resource: &quot;arn:aws:s3:::moodcheck-prod-write-test-31959&quot; because no identity-based policy allows the s3:CreateBucket action<br>exit code: 1</pre><blockquote>It’s worth learning to read this message, because you’ll see it often once CDK arrives. It says who (ReadOnlyAccess role), tried what (s3:CreateBucket), on what (the bucket ARN), and why it was refused. &quot;No identity-based policy allows&quot; means an implicit deny: nothing granted the action. A message saying &quot;explicit deny in a service control policy&quot; would point at an SCP instead. That distinction tells you where to look when a deploy fails.</blockquote><p><strong>Why test the denial:</strong> “prod is read-only” is only a claim until a write has been seen to fail. It’s the same habit as planting a type error in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a">Part 4</a>.</p><h3>Step 13: Prove the credentials expire</h3><pre>aws sso logout<br>aws sts get-caller-identity --profile moodcheck-beta; echo &quot;exit code: $?&quot;<br>aws sso login --sso-session rob-sso<br>aws sts get-caller-identity --profile moodcheck-beta</pre><p>aws sso logout deletes the cached token, which is what happens on its own when a session times out. The next call failed with Error loading SSO Token: Token for rob-sso does not exist and exit code 255. aws sso login opened the browser for one sign-in, and the same call worked again.</p><p><strong>Why this matters:</strong> if this laptop were lost or its files copied, there would be no lasting key to steal. That’s the property the pipeline will need too, and it’s why GitHub Actions will use OIDC later in the series rather than stored access keys.</p><h3>Where we are, and what’s next</h3><p>Mood Check now has somewhere to run:</p><ul><li><strong>Two dedicated accounts.</strong> moodcheck-beta in the DEV OU and moodcheck-prod in the PROD OU, both tagged project=moodcheck. The management account runs nothing.</li><li><strong>A budget alarm for each.</strong> $5 a month, with email alerts at $1 actual, $5 actual and $5 forecast, kept in the management account where the member accounts can’t remove them.</li><li><strong>Access through IAM Identity Center.</strong> Admin on beta, read-only on prod, each seen working, with the prod write seen failing.</li><li><strong>The AWS CLI v2 with two profiles.</strong> One browser sign-in, temporary credentials only, and nothing in ~/.aws that works without my password and MFA.</li></ul><p>Nothing was committed. Account IDs, root emails and the portal URL live only in AWS and in ~/.aws/config, outside the public repo.</p><p>The limits are worth stating plainly:</p><ul><li>The budget alarm warns; it doesn’t stop spending. Alerts can lag the spend by a day, and forecast alerts stay silent for about five weeks on new accounts.</li><li>Admin on beta is broad. It’s a deliberate trade for hand deploys in an isolated, budgeted account, not a pattern for the pipeline.</li></ul><p>This part adds no stage to our repo from the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline reference architecture</a>. It builds what the Test (Beta) and Prod stages stand on. The reference architecture says the beta environment should sit in a different AWS account from the tools that run the pipeline, and that access to production should go through cross-account IAM roles. Our pipeline will be GitHub Actions, outside AWS entirely, and it will reach these accounts through OIDC roles, with no stored keys.</p><p>Next time, in Part 6: we will create a new infra workspace with the AWS CDK, a one-off cdk bootstrap of the beta account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4cab354f5a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 4: Build Code and SAST]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-4-build-code-and-sast-b8dd5fd5257a?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8dd5fd5257a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cicd-pipeline]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[qa-engineer]]></category>
            <category><![CDATA[qa]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 11:15:58 GMT</pubDate>
            <atom:updated>2026-11-24T21:02:16.655Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>All code can be referenced in my <a href="https://github.com/rob212/mood-check">Mood Check Github repo</a></blockquote><p>By the end of this post the repo will have two more quality gates: npm run build, which type-checks and bundles every workspace, and npm run sast, which scans the source for security bugs with Semgrep. Both fail with a non-zero exit code when something is wrong, so a pipeline can call them unchanged. This follows on from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3: A Pre-commit Secrets Check with Gitleaks</a>.</p><p>In the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, the Local Development column lists five required items: Unit Tests, Code Quality, Secrets Detection, Build Code and SAST. Parts 1 to 3 covered the first three. This part covers the last two, which completes our local development setup.</p><ul><li><strong>Build Code</strong> means one command that proves the code compiles and packages. If it doesn’t build on my laptop, nothing later in the pipeline matters.</li><li><strong>SAST</strong> (static application security testing) reads the source code without running it and looks for patterns that are known to be dangerous.</li></ul><p>Let’s start with our command to build our code.</p><h3>Step 1: Run the existing build</h3><p>The Vite scaffold from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part 1</a> already gave the web workspace a build script:</p><pre>&quot;build&quot;: &quot;tsc -b &amp;&amp; vite build&quot;</pre><p>Run it from the repo root:</p><pre>npm run build -w web</pre><ul><li>tsc -b runs the TypeScript compiler in build mode across the project&#39;s config files. It type-checks the code.</li><li>vite build bundles the app into web/dist, ready to upload to a web host.</li><li>&amp;&amp; runs the second command only if the first one succeeds.</li></ul><p>Mine ended like this:</p><pre>✓ 16 modules transformed.<br>dist/index.html                   0.45 kB │ gzip:  0.29 kB<br>dist/assets/index-DGNrK5qb.css    1.78 kB │ gzip:  0.81 kB<br>dist/assets/index-DysBgn6i.js   219.65 kB │ gzip: 68.64 kB<br>✓ built in 291ms</pre><p><strong>Why the build needs </strong><strong>tsc as well as Vite:</strong> Vite strips TypeScript types without checking them. That keeps it fast in development, but on its own it would happily bundle code with type errors. tsc -b &amp;&amp; in front is what turns &quot;it bundled&quot; into &quot;it bundled and it&#39;s type-correct&quot;. Without it, the build would not be much of a gate.</p><h3>Step 2: Check the build output is ignored</h3><p>A build creates files. They must not end up in a commit, and the format check must not try to judge them.</p><pre>git status --short<br>git check-ignore -v web/dist<br>npm run format:check</pre><ul><li>git status --short should print nothing. If web/dist appeared as untracked, the build output isn&#39;t ignored.</li><li>git check-ignore -v web/dist prints which ignore rule matches the folder. No output means it isn&#39;t ignored.</li><li>npm run format:check re-runs Prettier&#39;s check now that dist exists.</li></ul><p>Mine printed web/.gitignore:11:dist web/dist, and the format check still passed.</p><p><strong>Why check:</strong> the match came from the web workspace&#39;s own .gitignore, created by the Vite scaffold, not from a root one. Prettier 3 skips anything git ignores, so it never sees the minified bundle. When later workspaces arrive, each will produce its own output (CDK writes cdk.out), and each needs the same check.</p><h3>Step 3: Add a root build script</h3><p>In the root package.json, add build beside the existing scripts:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npm test --workspaces --if-present&quot;,<br>  &quot;lint&quot;: &quot;npm run lint --workspaces --if-present&quot;,<br>  &quot;build&quot;: &quot;npm run build --workspaces --if-present&quot;,<br>  &quot;format&quot;: &quot;prettier . --write&quot;,<br>  &quot;format:check&quot;: &quot;prettier . --check&quot;,<br>  &quot;prepare&quot;: &quot;husky&quot;<br>}</pre><p>Then run it and check the exit code:</p><pre>npm run build; echo &quot;exit code: $?&quot;</pre><p>The output is the same as Step 1, ending with exit code: 0. The asset file names, such as index-DysBgn6i.js, are identical too. Vite names files after a hash of their contents, so the same source gives the same output.</p><p><strong>Why at the root:</strong> it’s the same pattern as test and lint in Parts 1 and 2. The pipeline calls one command, npm run build, and every workspace that has a build script is included. Adding the api and infra workspaces later won&#39;t mean editing the pipeline.</p><h3>Step 4: Prove the build fails on a type error</h3><p>A build that has never failed hasn’t been proven to catch anything. So we’ll create a file with a deliberate type error:</p><pre>echo &quot;export const count: number = &#39;one&#39;&quot; &gt; web/src/broken.ts<br>npm run build; echo &quot;exit code: $?&quot;</pre><p>The export stops the compiler also complaining that the variable is unused, so there&#39;s exactly one error to read. The output:</p><pre>src/broken.ts:1:14 - error TS2322: Type &#39;string&#39; is not assignable to type &#39;number&#39;.</pre><pre>1 export const count: number = &#39;one&#39;<br>               ~~~~~</pre><pre>Found 1 error.</pre><pre>npm error Lifecycle script `build` failed with error:<br>npm error code 2<br>...<br>exit code: 2</pre><p>Three things to notice:</p><ul><li>tsc names the file, line, column and error code.</li><li>There’s no vite v8... line. &amp;&amp; stopped the chain at tsc, so Vite never ran.</li><li>The exit code is 2, which is tsc&#39;s own code passed up through npm. Any non-zero code fails a pipeline step.</li></ul><p>Delete the file and check the build recovers:</p><pre>rm web/src/broken.ts<br>npm run build; echo &quot;exit code: $?&quot;<br>git status --short</pre><p>The build passes again, and git status --short shows only M package.json. Commit it on its own:</p><pre>git add package.json<br>git commit -m &quot;Add root build script running each workspace build&quot;<br>git push</pre><p>The gitleaks hook from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3</a> runs on the commit and reports no leaks.</p><p><strong>Why one change per commit:</strong> Build Code and SAST are separate gates. If either needs reverting or explaining later, it’s easier when each sits in its own commit.</p><h3>Choosing a SAST tool</h3><p>I chose <a href="https://docs.semgrep.dev/getting-started/cli">Semgrep’s free command-line tool</a>. There are plenty of alternatives, and the right one depends on the size of the codebase and the team. These are the ones I weighed:</p><p><strong>Semgrep (Community Edition)</strong></p><ul><li>How it works: rules written as code-like patterns, from a public registry or your own YAML files.</li><li>Local and CI: the same single CLI command in both.</li><li>Cost: free, no account needed.</li><li>What I’d give up: it analyses one file at a time. Cross-file analysis is in the paid tier.</li></ul><p><strong>eslint-plugin-security</strong></p><ul><li>How it works: a small set of ESLint rules for risky JavaScript and Node.js patterns.</li><li>Local and CI: yes, it would run inside npm run lint.</li><li>Cost: free.</li><li>What I’d give up: a narrow rule set, JavaScript only, with nothing for config files or other languages.</li></ul><p><strong>CodeQL</strong></p><ul><li>How it works: builds a database of the code, then runs queries that follow data from an input to a dangerous use.</li><li>Local and CI: possible locally, but mostly run through GitHub.</li><li>Cost: free for public repos.</li><li>What I’d give up: it’s slower and heavier to run, and closely tied to GitHub.</li></ul><p><strong>Commercial platforms (for example SonarQube or Snyk Code)</strong></p><ul><li>How it works: their own analysis engines, plus dashboards, triage and policy controls.</li><li>Local and CI: usually through their hosted service.</li><li>Cost: paid tiers and accounts.</li><li>What I’d give up: another platform to run and pay for.</li></ul><p><strong>Why Semgrep:</strong> it runs as one command that behaves the same on my laptop and on a GitHub Actions runner. It needs no account, sends no code anywhere, and covers more than JavaScript. That matters when the repo gains CDK code and pipeline YAML. Its rules look like the code they match, so I can read why something was flagged and write my own rule later. eslint-plugin-security was the simplest option, but its rule set is too narrow to be worth a separate gate. CodeQL&#39;s dataflow analysis is deeper than anything Semgrep&#39;s free tier does, but it&#39;s more machinery than a hello-world app needs. I professional settings, the most common approach I have seen used is SonarQube or Synk. Regardless of the platform, the underlying theory of SAST within our CI/CD pipeline is comparable.</p><p><strong>Why this is light touch:</strong> treat what follows as a sensible starting point, not a complete SAST setup. A larger or regulated application would usually add some of the following:</p><ul><li>A deeper engine with cross-file dataflow analysis, such as CodeQL or a paid Semgrep tier, alongside the pattern rules.</li><li>Pinned or vendored rules, so a rule update can’t change the result of a scan when the code hasn’t changed.</li><li>Custom rules for the organisation’s own frameworks and banned functions.</li><li>A triage process: who reviews findings, how false positives are suppressed, and how quickly real ones must be fixed.</li><li>Results published somewhere people look, such as GitHub code scanning, rather than only in a build log.</li></ul><h3>Step 5: Install Semgrep with pipx</h3><p>Semgrep is written in Python. Its documentation recommends installing it with pipx, which installs Python command-line tools into their own isolated environments.</p><pre>brew install pipx<br>pipx ensurepath</pre><p>pipx ensurepath adds ~/.local/bin to your PATH in your shell config. As with mise in Part 0, the running terminal won&#39;t pick that up, so <strong>open a new terminal</strong>. Then:</p><pre>pipx install semgrep<br>semgrep --version<br>pipx list</pre><p>Mine was 1.186.0. pipx list shows the version and the commands it exposes, semgrep and pysemgrep.</p><p><strong>Why pipx, not Homebrew or pip:</strong> Homebrew has a Semgrep formula, but Semgrep’s docs say it’s maintained on a best-effort basis and often lags the latest release. With pipx I can install an exact version (pipx install semgrep==1.186.0) on my laptop and on the CI runner, so both scan with the same engine. Plain pip install into the system Python is refused on modern macOS with an &quot;externally-managed-environment&quot; error, and pipx exists for exactly this case.</p><p><strong>The trade-off:</strong> npm has a lockfile and pipx doesn’t. The Semgrep version is written down in two places that I have to keep in step by hand: the README (Step 10) and, later, the pipeline workflow.</p><h3>Step 6: Plant some unsafe code and pick a rule pack</h3><p>Semgrep’s checks come from rule packs. You can load them from the Semgrep Registry by name, for example p/typescript. Before choosing one, I want something it should catch. A clean scan of a hello world app looks exactly like a scan that checks nothing.</p><p>Create a function that runs eval on its input, and stage it:</p><pre>cat &gt; web/src/Unsafe.tsx &lt;&lt; &#39;EOF&#39;<br>export function run(input: string) {<br>  return eval(input)<br>}<br>EOF<br>git add web/src/Unsafe.tsx</pre><p>eval runs a string as code. If that string can come from outside the program, anyone who controls it can run their own code in the page. It&#39;s one of the most widely flagged patterns in JavaScript.</p><p>I staged the file because Semgrep’s summary says it scans only files tracked by git. Staging makes sure the new file is included.</p><p>Now run five plausible packs against it, one at a time:</p><pre>for pack in p/default p/security-audit p/javascript p/typescript p/react; do semgrep scan --config $pack --metrics=off --error --quiet . ; echo &quot;$pack exit: $?&quot;; done</pre><ul><li>semgrep scan is the local-only command. It needs no account. (semgrep ci is the one that connects to Semgrep&#39;s paid platform.)</li><li>--config loads a rule pack. p/ means a pack from the registry.</li><li>--metrics=off stops Semgrep sending anonymous usage data, which it does by default when it fetches registry rules. The code itself is never sent.</li><li>--error makes Semgrep exit 1 when it finds anything. Without it, Semgrep exits 0 whenever the scan completes, findings or not, and can&#39;t act as a gate.</li><li>--quiet hides the progress table, so the five runs stay readable.</li><li>. scans the whole repo, minus anything git ignores.</li></ul><p>The result surprised me:</p><pre>web/src/Unsafe.tsx<br>    ❯❱ javascript.browser.security.eval-detected.eval-detected<br>          ❰❰ Blocking ❱❱<br>          Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content.<br>            2┆ return eval(input)</pre><pre>p/default exit: 1<br>p/security-audit exit: 0<br>p/javascript exit: 0<br>p/typescript exit: 0<br>p/react exit: 0</pre><p>Only p/default caught it. That&#39;s Semgrep&#39;s own general-purpose starter set, and it reports the rule ID, the file, the line and a plain explanation.</p><p>I also tried a second unsafe pattern: a React component that passes a prop straight into dangerouslySetInnerHTML, a classic cross-site scripting risk. None of the five packs flagged it, with Semgrep 1.186.0 and the registry rules as they were when I ran the scan.</p><p><strong>Why test the rules before trusting them:</strong> a SAST gate is only as good as its rules, and from the outside a pack’s name tells you little about what it covers. With p/typescript and p/react, the scan would have passed a repo full of eval calls and printed exactly what it prints for a clean one. A false negative never shows up in a log. The only way to find one is to plant something the gate should catch and see whether it does.</p><h3>Step 7: Add the sast script and watch it fail</h3><p>In the root package.json, add:</p><pre>&quot;sast&quot;: &quot;semgrep scan --config p/default --metrics=off --error .&quot;</pre><p>With Unsafe.tsx still staged, run it through npm:</p><pre>npm run sast; echo &quot;exit code: $?&quot;</pre><p>The summary ends like this:</p><pre>✅ Scan completed successfully.<br> • Findings: 1 (1 blocking)<br> • Rules run: 227<br> • Targets scanned: 24<br>exit code: 1</pre><p>The tick says the scan finished, not that the code is clean. In a pipeline log, read the Findings line and the exit code, never the banner.</p><p>p/default ran 227 rules on 24 files, including JSON and HTML as well as TypeScript. That&#39;s much broader than the language-specific packs, which is likely why it caught what they missed. The cost is more chance of noisy findings as the repo grows.</p><p><strong>Why test through npm:</strong> this is the same reason <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3</a> tested the hook with a real git commit. Step 6 proved Semgrep can find the problem. This step proves npm passes the failing exit code up, which is what the pipeline will rely on.</p><p><strong>Why </strong><strong>sast isn&#39;t in the pre-commit hook:</strong> Semgrep downloads its rules from the registry on every run, so it needs the network and is slower than gitleaks. A hook that&#39;s slow, or fails when you&#39;re offline, gets skipped. A leaked secret can&#39;t be taken back once pushed, which justified the gitleaks hook. A SAST finding can be fixed in the next commit, so the pipeline is the right place to enforce it.</p><h3>Step 8: Clean up and prove it passes</h3><pre>git restore --staged web/src/Unsafe.tsx<br>rm web/src/Unsafe.tsx<br>npm run sast; echo &quot;exit code: $?&quot;<br>git status --short</pre><p>The summary now shows Findings: 0, Rules run: 227 and Targets scanned: 23, one fewer than before, and exit code: 0. Only M package.json is listed as changed.</p><p>The file count matters as much as the zero findings. It shows Semgrep actually read the repo, in the same way gitleaks’ “commits scanned” line did in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3</a>.</p><p>The scan also prints a line saying I “missed out on” more rules by not logging in. I’m not logging in. Those rules belong to Semgrep’s platform tiers, and the free CLI is the point of this setup.</p><h3>Step 9: Run every gate and commit</h3><pre>npm test &amp;&amp; npm run lint &amp;&amp; npm run format:check &amp;&amp; npm run build &amp;&amp; npm run sast<br>echo &quot;exit code: $?&quot;</pre><p>That’s the whole Local Development column as one chain. &amp;&amp; stops at the first failure, so exit code: 0 means all five passed. Then commit:</p><pre>git add package.json<br>git commit -m &quot;Add root sast script running Semgrep as a blocking gate&quot;<br>git push</pre><p><strong>Why run them all before committing:</strong> the change touched package.json, which Prettier checks too. Running the full chain means the commit is known to pass every gate the pipeline will run, rather than finding out in CI later.</p><h3>Step 10: Write down the prerequisites</h3><p>The repo now depends on two tools npm doesn’t install: gitleaks and Semgrep. <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1">Part 3 </a>showed that a missing gitleaks gives only an unhelpful “command not found”. So I added a README that says what to install. You can see it in the accompanying <a href="https://github.com/rob212/mood-check">Mood Check Github repo</a>.</p><p>Run npm run format:check before committing it, because Prettier formats Markdown too. Then commit it on its own:</p><pre>git add README.md<br>git commit -m &quot;Add README with prerequisites, setup and checks&quot;<br>git push</pre><p><strong>Why a README now:</strong> this is where the Semgrep version pin lives, as Step 5 noted, and it’s the answer to anyone whose commit fails because gitleaks is missing. The Checks list is the same five commands the pipeline will run, so a contributor can run the full gate set before pushing.</p><h3>Where we are, and what’s next</h3><p>The <a href="https://github.com/rob212/mood-check">repo</a> now has five local quality gates, each seen failing for the right reason and passing on clean code:</p><ul><li><strong>Unit Tests:</strong> npm test. Fails when a test fails.</li><li><strong>Code Quality:</strong> npm run lint and npm run format:check. Fails on any lint error or warning, or an unformatted file.</li><li><strong>Secrets Detection:</strong> the gitleaks pre-commit hook via husky. Fails when a staged change looks like a secret.</li><li><strong>Build Code:</strong> npm run build. Fails on a type error, or when the bundle can&#39;t be built.</li><li><strong>SAST:</strong> npm run sast. Fails on any Semgrep p/default finding.</li></ul><p>That completes the Local Development column of the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, and with it the local foundations for this series.</p><p>The SAST gate has real limits, and it’s worth being plain about them:</p><ul><li>It caught eval but missed a dangerouslySetInnerHTML cross-site scripting risk. A clean scan means none of these rules matched, not that the code is safe.</li><li>The rules are fetched from the registry on every run. A scan needs the network, and a rule update can change the result when the code hasn’t changed. This is the same problem the exact Prettier pin solved in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-2-linting-and-formatting-as-quality-gates-cebacf336130">Part 2</a>, and I’ve accepted it here for simplicity.</li><li>The free tier analyses one file at a time. It won’t follow untrusted data from a function in one file to a dangerous call in another.</li><li>The Semgrep version is pinned by hand in the README, with no lockfile behind it.</li></ul><p>For a hello world app, I think that’s the right amount of SAST. For a real product, I’d start with the list in “Choosing a SAST tool” above.</p><p>None of these gates are enforced yet. Each one runs only when someone chooses to run it, apart from the pre-commit hook, and that can be skipped with --no-verify. The pipeline will run all five on every push, where they can&#39;t be skipped.</p><p>Before the pipeline, the series moves to AWS. Next time in <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-5-aws-accounts-budget-alarms-and-cli-access-b4cab354f5a8">Part 5</a>: budget alarms in both accounts before anything else, then command-line access through IAM Identity Center, and a first deployment of the web app to S3 and CloudFront in the beta account, by hand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8dd5fd5257a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 3: A Pre-commit Secrets Check with…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-3-a-pre-commit-secrets-check-with-gitleaks-5d8ead9e0ee1?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d8ead9e0ee1</guid>
            <category><![CDATA[qa-engineer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[qa]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 22:21:45 GMT</pubDate>
            <atom:updated>2026-11-24T21:01:52.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 3: A Pre-commit Secrets Check with Gitleaks</h3><p>By the end of this post our repo will block any commit that contains something that looks like a secret, such as an AWS access key. The check runs automatically on every commit, and anyone who clones the repo and runs npm ci gets it too. This follows on from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-2-linting-and-formatting-as-quality-gates-cebacf336130">Part 2: Linting and Formatting as Quality Gates</a>, which added lint and format checks you run by hand.</p><p>The repo is public. Once a secret is pushed to a public GitHub repo, you have to assume someone has it. Bots scan new public commits for credentials within minutes, and deleting the file in a later commit doesn’t help, because the secret stays in the history. A failing test can be fixed in the next commit. A leaked key has to be revoked and rotated. That’s why this check runs before the commit exists, not later in a pipeline.</p><p>In the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, the <strong>Local Development</strong> column is about checks that run on the developer’s machine before code reaches the source repository, including pre-commit hooks. This is the first one, and it completes the local foundations for the series.</p><p>Two tools do the work:</p><ul><li><strong>gitleaks</strong> scans files or commits for patterns that look like secrets, using a built-in set of rules for AWS keys, GitHub tokens, private keys and many others.</li><li><strong>Husky</strong> installs git hooks from files stored in the repo, so the hook is shared rather than living only on my laptop.</li></ul><h3>Step 1: Install gitleaks and check the version</h3><p>On a Mac, from any directory:</p><pre>brew install gitleaks<br>gitleaks version</pre><p>Mine printed 8.30.1.</p><p><strong>Why check the version:</strong> gitleaks renamed its commands partway through the 8.x releases. Older guides use gitleaks detect and gitleaks protect. Current versions use gitleaks git to scan commits and gitleaks dir to scan files, and the old names are deprecated. If you copy a command from an older post and it behaves oddly, the version is the first thing to check.</p><p><strong>Why a system install, not an npm package:</strong> gitleaks is a single Go binary, not a Node tool. Installing it with Homebrew keeps it out of the repo’s dependencies. The trade-off is that it’s one more prerequisite every contributor has to install, which I come back to at the end.</p><h3>Step 2: Scan the existing history</h3><p>From the repo root:</p><pre>gitleaks git --verbose --redact<br>echo &quot;exit code: $?&quot;</pre><ul><li><strong>gitleaks git</strong> scans every commit in the repo&#39;s history, not just the files as they are now.</li><li><strong>--verbose</strong> prints each finding in full, not just a count.</li><li><strong>--redact</strong> masks the secret&#39;s value in the output, so a real key doesn&#39;t end up in your terminal scrollback or a CI log.</li></ul><p>Mine ended like this:</p><pre>INF 3 commits scanned.<br>INF scanned ~156351 bytes (156.35 KB) in 29.1ms<br>INF no leaks found<br>exit code: 0</pre><p><strong>Why scan history first:</strong> a hook only protects future commits. If a secret was already committed, even in a commit that later deleted it, the hook won’t notice, and the secret is still public. Scanning the history once tells me I’m starting from a clean baseline. The “commits scanned” and bytes lines matter too: they show it actually read the history, rather than finding nothing because it looked at nothing.</p><h3>Step 3: Prove the scanner fails on a fake secret</h3><p>A clean result is also what a broken scanner would print. Before wiring gitleaks into anything, I want to see it fail. Create a file containing a made-up key and stage it:</p><pre>echo &#39;const awsKey = &quot;AKIAZ3MQ7XJ2K5PLR4TN&quot;&#39; &gt; fake-secret.ts<br>git add fake-secret.ts<br>gitleaks git --pre-commit --staged --verbose --redact<br>echo &quot;exit code: $?&quot;</pre><ul><li>The key is 20 characters starting with AKIA, the format of an AWS access key ID. It isn&#39;t a real key.</li><li><strong>git add</strong> puts the file in the staging area. A commit records exactly what&#39;s staged, so that&#39;s what a pre-commit check needs to look at.</li><li><strong>--pre-commit --staged</strong> scans only the staged changes, not the history. These are the flags the hook will use.</li></ul><p>The output names the rule, the file and the line, with the value masked:</p><pre>Finding:     const awsKey = &quot;REDACTED<br>Secret:      REDACTED<br>RuleID:      aws-access-token<br>File:        fake-secret.ts<br>Line:        1</pre><pre>INF 0 commits scanned.<br>WRN leaks found: 1<br>exit code: 1</pre><p>“0 commits scanned” is expected here, because this mode scans the staging area rather than commits.</p><p>Now unstage and delete the file, and check the tree is clean:</p><pre>git restore --staged fake-secret.ts<br>rm fake-secret.ts<br>git status</pre><p><strong>Why not use AWS’s example key:</strong> the AWS documentation uses AKIAIOSFODNN7EXAMPLE in its examples. Because it&#39;s so widely published, secret scanners tend to allow-list it, so it can give you a false pass. A made-up key in the right format tests the rule itself.</p><p><strong>Why never commit the test secret:</strong> even a fake key shouldn’t go into the history of a public repo. Other scanners would flag it, and it teaches the wrong habit. Every test in this post is done in the staging area and undone straight away.</p><h3>Step 4: Install Husky</h3><p>Git has a built-in feature called hooks: scripts that git runs automatically at certain points, such as just before a commit is created. If a pre-commit hook exits with anything other than 0, git refuses to make the commit. That&#39;s the mechanism that will run gitleaks for us.</p><p><a href="https://typicode.github.io/husky/">Husky</a> is a small npm package that manages those hooks for JavaScript projects. You write each hook as a plain shell script in a .husky/ folder in the repo, and Husky tells git to run them. It has no runtime dependencies and does nothing at build or run time; it only wires up git.</p><p>Git runs hooks from .git/hooks, but that folder isn&#39;t committed, so a hook placed there exists only on one machine. A hook runner solves that by keeping hook scripts in the repo. From the root:</p><pre>npm install --save-dev --save-exact husky<br>npx husky init</pre><ul><li><strong>--save-dev --save-exact</strong> records Husky as a dev dependency at an exact version, as with Prettier in Part 2. Mine was 9.1.7.</li><li><strong>npx husky init</strong> adds a prepare script to the root package.json and creates .husky/pre-commit with a placeholder command.</li></ul><p>Check what it changed:</p><pre>cat .husky/pre-commit<br>git diff package.json</pre><p>The placeholder is npm test, and the new script is:</p><pre>&quot;prepare&quot;: &quot;husky&quot;</pre><p>npm runs prepare automatically after npm install and npm ci. Husky uses it to point git&#39;s core.hooksPath setting at .husky/_, which holds small generated stubs that call your scripts in .husky/. You can confirm it with git config core.hooksPath.</p><p><strong>Why Husky:</strong> everything in this repo already runs through npm, and the prepare script means anyone who runs npm ci gets the hook with no extra step. I considered two alternatives. <a href="https://github.com/evilmartians/lefthook">Lefthook</a> is a single Go binary with no npm dependency, which is better for repos that aren&#39;t Node-based. The <a href="https://github.com/pre-commit/pre-commit">pre-commit framework</a> is popular, but needs Python, a new dependency this repo doesn&#39;t otherwise use. The trade-off with Husky is one more dev dependency to keep updated.</p><h3>Step 5: Replace the placeholder hook with gitleaks</h3><pre>echo &#39;gitleaks git --pre-commit --staged --redact --verbose&#39; &gt; .husky/pre-commit<br>cat .husky/pre-commit</pre><p>The single &gt; overwrites the placeholder. The cat confirms it, because a redirect gives no output of its own.</p><p>Husky runs the script with the shell’s exit-on-error behaviour, so any non-zero exit stops the commit. That includes gitleaks finding a secret (exit 1), and gitleaks not being installed at all (exit 127, command not found). Either way, the commit doesn’t happen.</p><p><strong>Why only gitleaks, not the tests:</strong> running tests, lint and format on every commit makes commits slow, and those checks will run in the pipeline anyway. A secret is different. Once it’s pushed to a public repo it can’t be taken back, so it’s the one check worth paying for on every commit. A fast hook is also one people are less tempted to skip.</p><h3>Step 6: Prove the hook blocks a commit</h3><p>Let’s recreate the fake secret and try to commit it:</p><pre>echo &#39;const awsKey = &quot;AKIAZ3MQ7XJ2K5PLR4TN&quot;&#39; &gt; fake-secret.ts<br>git add fake-secret.ts<br>git commit -m &quot;Test: this commit should be blocked&quot;<br>echo &quot;exit code: $?&quot;<br>git log --oneline -3</pre><p>The same gitleaks finding appears, followed by Husky’s own line:</p><pre>WRN leaks found: 1<br>husky - pre-commit script failed (code 1)<br>exit code: 1</pre><p>git log still shows the previous commit at the top. No commit was created.</p><p>Clean up exactly as before:</p><pre>git restore --staged fake-secret.ts<br>rm fake-secret.ts<br>git status</pre><p><strong>Why test through </strong><strong>git commit:</strong> Step 3 proved gitleaks can detect the key. This step proves the wiring: that git calls Husky, Husky calls the script, and a non-zero exit actually stops the commit. Each link could fail on its own, so the only convincing test is the real action the gate is meant to stop.</p><h3>Step 7: Run the gates and commit</h3><pre>npm test &amp;&amp; npm run lint &amp;&amp; npm run format:check</pre><p>These are the three gates from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Parts 1</a> and <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-2-linting-and-formatting-as-quality-gates-cebacf336130">2</a>. They confirm the Husky changes didn’t break anything, such as the format check objecting to the updated package.json.</p><p>Stage the files by name and commit:</p><pre>git add package.json package-lock.json .husky/pre-commit<br>git status<br>git commit -m &quot;Add Husky pre-commit hook running gitleaks on staged changes&quot;<br>git push</pre><p>The commit itself runs the hook. This time gitleaks reports no leaks found and the commit goes through, with three files changed. The generated .husky/_ folder isn&#39;t included, because Husky gives it its own .gitignore.</p><p><strong>Why stage by name:</strong> git add . would pick up anything lying around, including a test file you forgot to delete. When the commit is about keeping things out of the repo, being explicit about what goes in is the point.</p><p><strong>Why this commit matters:</strong> it’s the gate’s other half. Step 6 showed the hook blocks a bad commit. This shows it lets a clean one through. A gate that blocks everything gets bypassed as quickly as one that blocks nothing.</p><h3>Where we are, and what’s next</h3><p>The repo now has four local quality gates:</p><ul><li>npm test runs the unit tests.</li><li>npm run lint runs static analysis, failing on warnings as well as errors.</li><li>npm run format:check checks formatting without changing anything.</li><li>A <strong>pre-commit hook</strong> runs gitleaks on every commit and blocks any that contain something that looks like a secret.</li></ul><p>The first three run when I choose to run them. The fourth runs automatically, and npm ci installs it for anyone who clones the repo. In the reference architecture, that covers three of the five required items in the <strong>Local Development</strong> column. Unit Tests, Code Quality and Secrets Detection. <em>(I want to acknowledge the unit tests is extremely basic at this stage, but will grow and evolve as our application codebase does).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lQlxZfrFHQ_pjvxsoFWOA.png" /></figure><p>It isn’t a guarantee, and it’s worth being honest about the limits:</p><ul><li>git commit --no-verify skips the hook entirely.</li><li>Anyone without gitleaks installed gets a “command not found” error. The commit is still blocked, which is the safe way to fail, but the message doesn’t say what to do. Our repo’s README will need a prerequisites line: brew install gitleaks.</li><li>Pattern matching catches well-known formats like AWS keys. It won’t catch a password typed into a config file with nothing distinctive about it.</li></ul><p>The local hook is about fast feedback. The enforcement belongs in the pipeline, where the same scan will run on every push and can’t be skipped. That arrives in a later part.</p><p>Two items in that column are still missing: <strong>Build Code</strong>, a single command that proves the app compiles and bundles, and <strong>SAST</strong> (static application security testing), which scans the source for security bugs such as injection risks. Next time I’ll add both, using the same commands the pipeline will run later. That completes the local foundations, and after it the series moves to AWS: budget alarms first, then infrastructure as code and a first deployment to the beta account, by hand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d8ead9e0ee1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 0: Prerequisites, setting up your…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-0-prequisties-setting-up-your-machine-0a730c09b255?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a730c09b255</guid>
            <category><![CDATA[qa-testing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[qa-automation]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 12:09:08 GMT</pubDate>
            <atom:updated>2026-11-24T21:01:12.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Quality In: A CI/CD Pipeline, Stage by Stage — Part 0: Prerequisites, setting up your machine</h3><p>As part of my “Building a CI/CD” series, I use Node, npm and git. This is a short guide in getting these setup on a macbook.</p><p>By the end of this post you’ll have Node 24, npm 11 and a current git installed, with Node managed by a version manager, and a clone of the Mood Check repo that installs and tests cleanly. This is my opinionated setup for this series, but the logic can be applied in other languages and frameworks, but the focus on this series is a working best practive CI/CD pipeline from the perspective of Quality Engineering not the underlaying languages or app.</p><p>This is the groundwork for <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part 1: A Tested Hello World</a>, where Step 1 lists these tools as prerequisites without saying how to get them.</p><h3>Step 1: Check your shell</h3><p>Open the Terminal app and run:</p><pre>echo $SHELL</pre><p>You should see /bin/zsh. echo prints text, and $SHELL is an environment variable holding the path of your login shell.</p><p><strong>Why check:</strong> everything below assumes zsh, the macOS default. The shell decides which startup file is read when a terminal opens, and several steps add a line to that file. In zsh, ~/.zprofile is read when a login shell starts and ~/.zshrc is read by every interactive shell. If you&#39;re on something else, the commands still work but the config file names differ.</p><h3>Step 2: Install Homebrew</h3><p>Homebrew is the standard package manager for macOS. It installs command-line tools from one place and keeps them updatable with one command.</p><p>Go to <a href="https://brew.sh/">brew.sh</a> and copy the install command from the front page. It’s a single line that downloads and runs Homebrew’s installer. Copy it from the site rather than from this post, because it’s the one command here that I’d rather you took from the source.</p><p>The installer asks for your Mac password and installs Apple’s Command Line Tools if they’re missing, which takes a few minutes. When it finishes it prints a “Next steps” block. Run those lines. They look like this:</p><pre>echo &gt;&gt; ~/.zprofile<br>echo &#39;eval &quot;$(/opt/homebrew/bin/brew shellenv)&quot;&#39; &gt;&gt; ~/.zprofile<br>eval &quot;$(/opt/homebrew/bin/brew shellenv)&quot;</pre><p>Then check it worked:</p><pre>brew --version</pre><p>What the “Next steps” lines do:</p><ul><li><strong>&gt;&gt; ~/.zprofile</strong> appends a line to your zsh login startup file, creating it if needed.</li><li><strong>brew shellenv</strong> prints the settings Homebrew needs, mainly adding /opt/homebrew/bin to your PATH. PATH is the list of folders the shell searches when you type a command.</li><li><strong>eval</strong> runs that output in the current terminal, so Homebrew works immediately, not only in new windows.</li></ul><p><strong>Why Homebrew:</strong> it puts tools in one predictable place, and brew upgrade updates them all. On Apple Silicon Macs that place is /opt/homebrew, which isn&#39;t on your PATH by default. Skip the &quot;Next steps&quot; block and brew will install fine but the shell won&#39;t find it afterwards.</p><h3>Step 3: Install git</h3><pre>brew install git<br>which git<br>git --version</pre><ul><li><strong>brew install git</strong> downloads and installs the latest release.</li><li><strong>which git</strong> prints the path of the git the shell will actually run. You want /opt/homebrew/bin/git.</li><li><strong>git --version</strong> confirms the version. Mine printed 2.56.1, newer than the 2.54 I listed in Part 1. Read the requirement as &quot;2.54 or later&quot;.</li></ul><p><strong>Why not the git that comes with macOS:</strong> Apple ships its own build, which lags behind upstream releases. The Homebrew version tracks the real project.</p><p><strong>Why not a version manager for git:</strong> version managers earn their place when different projects need different versions of a tool. Git doesn’t work that way. One current version is right for every project, so Homebrew is the simplest tool for the job.</p><h3>Step 4: Install mise with the official script</h3><p>A version manager installs several versions of a runtime side by side and switches between them. That matters because the project pins Node in a .nvmrc file (Part 1, Step 3). You want the laptop to follow that pin automatically instead of whichever Node happened to be installed last.</p><p>I chose <a href="https://mise.jdx.dev/">mise</a> over the alternatives:</p><ul><li><strong>nvm</strong> is the most widely used. It’s a shell script that adds a little time to every new terminal, and it only manages Node.</li><li><strong>fnm</strong> is a fast, Node-only manager written in Rust. A good choice if Node is all you’ll ever need.</li><li><strong>mise</strong> is also written in Rust, and manages Node plus other runtimes such as Python through one tool. That suits a series that will reach beyond Node.</li></ul><p>Install it with the project’s own script:</p><pre>curl https://mise.run | sh<br>~/.local/bin/mise --version</pre><ul><li><strong>curl https://mise.run</strong> downloads the install script.</li><li><strong>| sh</strong> hands it straight to the shell to run. This is a common pattern, but it does run code from the internet. If you&#39;d rather read it first, open https://mise.run in a browser. It&#39;s the project&#39;s official installer.</li><li><strong>~/.local/bin/mise --version</strong> runs the new binary by its full path. I got 2026.11.9 macos-arm64.</li></ul><p>The script puts mise in ~/.local/bin. That folder isn&#39;t on your PATH, which is why the next step exists.</p><p><strong>Why the script and not </strong><strong>brew install mise:</strong> it&#39;s the one place in this post where Homebrew is the wrong tool. The mise documentation recommends the install script on macOS. The Homebrew formula builds mise from source with its own settings, so it can be slower and larger, and releases reach it later. If you install it that way anyway, mise prints a hint telling you to switch. The trade-off is that mise updates itself (mise self-update) instead of through brew upgrade, so there&#39;s one more update command to remember.</p><h3>Step 5: Activate mise in your shell</h3><pre>echo &#39;eval &quot;$(~/.local/bin/mise activate zsh)&quot;&#39; &gt;&gt; ~/.zshrc<br>grep -n mise ~/.zshrc</pre><ul><li><strong>mise activate zsh</strong> prints shell code that hooks into your prompt. Each time you change directory, the hook checks for a version file and puts the right tools on your PATH.</li><li><strong>eval &quot;$(...)&quot;</strong> runs that output in every new shell.</li><li><strong>&gt;&gt; ~/.zshrc</strong> appends the line to the file zsh reads for every interactive terminal.</li><li><strong>The full </strong><strong>~/.local/bin/mise path</strong> means the line works even though that folder isn&#39;t on your PATH.</li><li><strong>grep -n mise ~/.zshrc</strong> prints the matching line with its line number. You want exactly one.</li></ul><p>Run the echo once only. Running it twice adds a duplicate line. Now open a new terminal tab, so the file is read again, and run:</p><pre>mise --version</pre><p><strong>Why activation is a separate step:</strong> installing mise only puts a program on disk. Activation is what makes your shell switch Node versions as you move between projects. Without it, mise can install Node but you’ll get command not found: node.</p><h3>Step 6: Install Node 24</h3><pre>mise use --global node@24<br>node -v<br>npm -v<br>which node</pre><ul><li><strong>mise use</strong> installs a tool and records the choice in a config file.</li><li><strong>--global</strong> writes that choice to ~/.config/mise/config.toml, so Node 24 becomes your default everywhere.</li><li><strong>node@24</strong> means the latest 24.x release. Mine installed v24.22.3.</li><li><strong>npm -v</strong> should print 11.19.1</li><li><strong>which node</strong> should print a path inside ~/.local/share/mise/installs/node/, which confirms mise is supplying Node and not some other install.</li></ul><p>There’s no separate step for npm. npm 11 is bundled with Node 24.</p><p><strong>Why Node 24:</strong> as I explained in Part 1, use an even-numbered release, because those become Long Term Support versions. Node 24 is the LTS line the pipeline will run.</p><p><strong>Why not upgrade npm separately:</strong> npm will occasionally print a notice that a newer major version exists. Ignore it. The bundled npm is the one that’s tested with your Node, and it’s the one CI will use. Upgrading it globally makes your laptop differ from the pipeline.</p><h3>Step 7: Make mise follow the project’s .nvmrc</h3><p>The repo pins Node in a .nvmrc file. mise reads that format, but only for tools you&#39;ve told it to. Switch it on for Node:</p><pre>mise settings add idiomatic_version_file_enable_tools node</pre><p><strong>Why:</strong> .nvmrc is the single source of truth for the Node version, shared by your laptop and, later, GitHub Actions. If mise ignored it, you&#39;d silently run your global default, and the two environments could drift apart without anyone noticing.</p><p>You’ll prove this works in Step 9.</p><h3>Step 8: Set up your git identity and the GitHub CLI</h3><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;you@example.com&quot;<br>git config --global init.defaultBranch main<br>brew install gh<br>gh auth login</pre><ul><li><strong>git config --global</strong> writes to ~/.gitconfig, so the setting applies to every repo on this Mac.</li><li><strong>user.name and </strong><strong>user.email</strong> are stamped on every commit. Use the email address attached to your GitHub account, or commits won&#39;t link to your profile.</li><li><strong>init.defaultBranch main</strong> makes new repos start on main, matching GitHub&#39;s default.</li><li><strong>brew install gh</strong> installs the GitHub command-line tool.</li><li><strong>gh auth login</strong> walks you through signing in. Choose GitHub.com and your preferred protocol, then authenticate in the browser.</li></ul><p>Check it with:</p><pre>gh auth status</pre><p><strong>Why the GitHub CLI:</strong> pushing to GitHub needs authentication, and the usual alternative is generating and registering SSH keys by hand. gh auth login handles that for you and also gives you gh repo clone, which is what we use next. The trade-off is one more tool to install, in return for a setup a newcomer can&#39;t easily get wrong.</p><h3>Step 9: Clone the repo and prove the setup works</h3><p>This is the real test. If a fresh Mac can go from nothing to a passing build, the prerequisites are complete.</p><pre>mkdir -p ~/code &amp;&amp; cd ~/code<br>gh repo clone mood-check<br>cd mood-check<br>cat .nvmrc<br>node -v<br>mise ls node</pre><ul><li><strong>mkdir -p ~/code</strong> creates a folder for projects. -p means no error if it already exists.</li><li><strong>gh repo clone mood-check</strong> clones your own repo of that name.</li><li><strong>cat .nvmrc</strong> prints the pinned version, which is 24.</li><li><strong>mise ls node</strong> lists installed Node versions and, in its Source column, where the active one comes from. You want it to say .nvmrc in the project folder, not ~/.config/mise/config.toml. That is the proof that Step 7 worked.</li></ul><p>Now install and test:</p><pre>npm ci<br>npm test</pre><p><strong>Why </strong><strong>npm ci and not </strong><strong>npm install:</strong> npm ci installs exactly what package-lock.json records and fails if the lockfile and package.json disagree. It&#39;s the command the pipeline will use, so running it here checks that a clean machine reproduces the build from the lockfile alone.</p><p>If the tests pass, the setup is done.</p><h3>Where we are, and what’s next</h3><p>A new Mac now has everything Part 1 assumes:</p><ul><li>Homebrew for general command-line tools: git and the GitHub CLI.</li><li>mise for runtimes, with Node 24 as the default and the repo’s .nvmrc respected.</li><li>git with an identity, GitHub authentication and a working clone of Mood Check, with npm ci and npm test passing.</li></ul><p>In terms of the reference architecture, this isn’t a pipeline stage. It’s the groundwork under the <strong>Local Development</strong> column: a developer environment that can be recreated from a list of commands and matches what CI will run.</p><p>Two update commands are worth remembering. brew upgrade updates Homebrew&#39;s tools, including git, and mise self-update updates mise itself. Node&#39;s version is controlled by .nvmrc, not by either of them.</p><p>Feel free to continue onto <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part one of this series</a> if you haven’t already seen it where we start work on our React web app and add a unit test to running locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a730c09b255" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage— Part 2: Linting and Formatting as Quality…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-2-linting-and-formatting-as-quality-gates-cebacf336130?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/cebacf336130</guid>
            <category><![CDATA[qa-engineering]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 15:56:30 GMT</pubDate>
            <atom:updated>2026-11-24T21:00:49.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Quality In: A CI/CD Pipeline, Stage by Stage— Part 2: Linting and Formatting as Quality Gates</h3><p>By the end of this post your repo will have two new quality gates, linting and code formatting. Each runs with one command from the repo root and returns a clear pass or fail. This follows on from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part 1: A Tested Hello World</a>, which set up the repo, the React app and a first unit test.</p><p>A CI/CD pipeline is, at heart, a chain of commands. Each one exits with 0 (pass) or anything else (fail), and the pipeline stops at the first failure. So before writing any pipeline, I want every check to exist as a single command I can run on my laptop and trust. This post adds two of them.</p><ul><li><strong>Linting</strong> (ESLint) reads the code without running it and flags patterns that cause bugs. It catches a class of problems before a single test runs.</li><li><strong>Formatting</strong> (Prettier) makes every file look the same. That sounds cosmetic, but it removes style debates and whitespace noise from every future code review, so reviews focus on behaviour.</li></ul><p>In the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, both sit under the Build stage’s <strong>Code Quality</strong> action. The same page says every Build action should also run on the developer’s machine before code is committed. That’s the order we follow: build the gates locally now, and call the exact same commands from the pipeline later.</p><h3>Step 1: Understand the ESLint config the scaffold gave us</h3><p>The Vite React template already installs ESLint and creates web/eslint.config.js. Before changing anything, lets look at it line by line:</p><pre>import js from &#39;@eslint/js&#39;<br>import globals from &#39;globals&#39;<br>import reactHooks from &#39;eslint-plugin-react-hooks&#39;<br>import reactRefresh from &#39;eslint-plugin-react-refresh&#39;<br>import tseslint from &#39;typescript-eslint&#39;<br>import { defineConfig, globalIgnores } from &#39;eslint/config&#39;<br><br>export default defineConfig([<br>  globalIgnores([&#39;dist&#39;]),<br>  {<br>    files: [&#39;**/*.{ts,tsx}&#39;],<br>    extends: [<br>      js.configs.recommended,<br>      tseslint.configs.recommended,<br>      reactHooks.configs.flat.recommended,<br>      reactRefresh.configs.vite,<br>    ],<br>    languageOptions: {<br>      globals: globals.browser,<br>    },<br>  },<br>])</pre><p>This is ESLint’s “flat config” format, the only one ESLint 10 supports.</p><ul><li><strong>globalIgnores([&#39;dist&#39;])</strong> skips the build output. Linting generated code produces findings nobody can fix.</li><li><strong>files: [&#39;**/*.{ts,tsx}&#39;]</strong> applies the rules to TypeScript source only.</li><li><strong>js.configs.recommended</strong> is ESLint&#39;s core set of rules for genuine bugs, such as unreachable code and duplicate object keys.</li><li><strong>tseslint.configs.recommended</strong> adds TypeScript-aware rules, such as no unused variables and no any. There&#39;s a stricter recommendedTypeChecked variant that uses the type checker to catch things like unawaited promises. It&#39;s slower and needs more setup, so I&#39;ll revisit it when the async Lambda code arrives.</li><li><strong>reactHooks.configs.flat.recommended</strong> enforces the rules of hooks. Calling a hook inside an if is a real runtime bug that unit tests often miss.</li><li><strong>reactRefresh.configs.vite</strong> warns when a file exports something that breaks Vite&#39;s hot reload. It protects the developer experience rather than correctness.</li><li><strong>globals.browser</strong> tells ESLint that window, document and friends exist, so it doesn&#39;t report them as undefined.</li></ul><p>Run it from the root:</p><pre>npm run lint -w web</pre><p>It prints nothing after the script name. ESLint is silent when there’s nothing to report.</p><p><strong>Why read a config you didn’t write:</strong> once lint is a pipeline gate, it will block builds. When it does, I need to know whether the rule is guarding against a real bug or enforcing a preference. That decides whether I fix the code or change the rule. A gate nobody understands gets switched off the first time it’s inconvenient.</p><h3>Step 2: Prove lint can fail</h3><p>A silent pass proves nothing on its own. In web/src/App.tsx, add a line inside the function, above return:</p><pre>const unused = &#39;nobody reads me&#39;</pre><p>Then run lint and print its exit code:</p><pre>npm run lint -w web; echo &quot;exit code: $?&quot;</pre><p>$? holds the exit code of the previous command. The output shows the file, the position (2:9), the severity and the rule:</p><pre>2:9  error  &#39;unused&#39; is assigned a value but never used  @typescript-eslint/no-unused-vars<br><br>✖ 1 problem (1 error, 0 warnings)<br>...<br>exit code: 1</pre><p><strong>Why watch it fail:</strong> it’s the same principle as watching a test fail before making it pass. A gate you’ve never seen fail might not be wired up at all. Seeing exit code 1 for the right reason proves this command can stop a pipeline, because exit code 1 is exactly what a CI runner checks.</p><p>Leave the line in place for the next step.</p><h3>Step 3: Make warnings fail too</h3><p>Look again at the summary line: 1 error, 0 warnings. ESLint has two severities, and only errors change the exit code. Warnings are printed, then ignored. The react-refresh rule in this config is a warning, so as things stand it could never stop a build.</p><p>Delete the const unused line from App.tsx. Then change the lint script in web/package.json:</p><pre>&quot;lint&quot;: &quot;eslint . --max-warnings 0&quot;</pre><p>--max-warnings 0 makes ESLint exit non-zero if it finds even one warning.</p><p><strong>Why:</strong> a quality gate should be binary. The code meets the bar or it doesn’t. In a pipeline, nobody reads the logs of a passing build, so “warnings allowed” really means “warnings accumulate”. The trade-off is that you can’t leave a warning in as a reminder. You either fix it, or you turn the rule off in the config, where the decision is visible and reviewable. I acknowledge this is my personal opinion, formed by years or witnessing warnings slowly building up and being ignored by the development team. Specifically in the age of AI-assisted development, I don’t think there is an excuse to allow un-actioned warnings anymore.</p><h3>Step 4: Run lint from the root</h3><p>In the root package.json, add a lint script beside test:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npm test --workspaces --if-present&quot;,<br>  &quot;lint&quot;: &quot;npm run lint --workspaces --if-present&quot;<br>}</pre><p>It’s the same pattern as test from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part 1</a>. It runs lint in every workspace that defines one and skips any that don&#39;t. Note the slight difference in form: npm test is a built-in shorthand, but lint isn&#39;t, so it needs npm run lint.</p><pre>npm run lint; echo &quot;exit code: $?&quot;</pre><p>This should run ESLint in web and end with exit code: 0.</p><p><strong>Why at the root:</strong> the pipeline should call one command per check, npm run lint, without knowing which workspaces exist. When the api and infra workspaces arrive with their own lint rules, they&#39;re picked up automatically. Adding a workspace will never mean editing the pipeline.</p><h3>Step 5: Install Prettier at the root, pinned</h3><p>From the repo root:</p><pre>npm install -D --save-exact prettier</pre><ul><li>-D saves it as a dev dependency.</li><li>Running it at the root without -w adds it to the <strong>root</strong> package.json, not the web workspace.</li><li>--save-exact records the exact version, with no ^ range in front.</li></ul><p><strong>Why at the root:</strong> linting is per workspace, because a React app and a Lambda API need different rules. Formatting is the opposite. I want one style across the whole repo, including root files like package.json, the README and, later, the pipeline&#39;s YAML. One tool and one config, owned by the root.</p><p><strong>Why pin exactly:</strong> <a href="https://prettier.io/docs/install">Prettier’s own documentation recommends it</a>. A minor release can change how code is formatted. With a ^ range, a fresh install could pull a newer version and the format check would fail on files nobody touched. The lockfile mostly protects against this already, but an exact pin makes the intent explicit. A gate that fails for reasons unrelated to the change being tested teaches people to distrust it.</p><h3>Step 6: Configure Prettier</h3><p>Create .prettierrc at the root:</p><pre>{<br>  &quot;semi&quot;: false,<br>  &quot;singleQuote&quot;: true<br>}</pre><p>This matches the style the Vite template and the code from <a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3">Part 1</a> already use: no semicolons, single quotes. Prettier’s defaults are the reverse.</p><p><strong>Why only two options:</strong> matching the existing style means the first format run fixes genuine inconsistencies rather than rewriting every line. Beyond that, every option you add is a style debate Prettier exists to end. Having the file at all also tells editors and CI that this repo is formatted by Prettier, so everyone gets identical output.</p><p>Create .prettierignore at the root:</p><pre>package-lock.json</pre><p>Prettier 3 already skips everything in .gitignore, which covers node_modules and dist. The lockfile is committed, so git doesn&#39;t ignore it, but npm generates and owns it.</p><p><strong>Why ignore the lockfile:</strong> reformatting a generated file creates diffs that npm undoes on the next install. A format check should only judge files people write.</p><p>You might expect to install eslint-config-prettier here, so the two tools don&#39;t fight. I didn&#39;t. That package only switches off ESLint&#39;s formatting rules, and since ESLint 9 none of the configs extended in Step 1 include any. With no overlap there&#39;s nothing to switch off.</p><p><strong>Why leave it out:</strong> every dependency is something to update, audit and understand. A tool earns its place by protecting against something real. If I ever add a stylistic ESLint plugin, I’ll revisit this.</p><h3>Step 7: Add format scripts and watch the check fail</h3><p>Add two scripts to the root package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;npm test --workspaces --if-present&quot;,<br>  &quot;lint&quot;: &quot;npm run lint --workspaces --if-present&quot;,<br>  &quot;format&quot;: &quot;prettier . --write&quot;,<br>  &quot;format:check&quot;: &quot;prettier . --check&quot;<br>}</pre><ul><li><strong>format</strong> rewrites files in place. It&#39;s for your laptop.</li><li><strong>format:check</strong> changes nothing. It lists unformatted files and exits non-zero. It&#39;s for the pipeline.</li></ul><p>These call Prettier directly across the whole repo (.), not through --workspaces, because formatting belongs to the root.</p><p><strong>Why two scripts:</strong> a pipeline must never modify the code it’s testing. If CI reformatted files, what it tested would differ from what’s in the repo. So CI only checks, and fixing is done locally, before pushing.</p><p>Run the check before formatting anything:</p><pre>npm run format:check; echo &quot;exit code: $?&quot;</pre><p>Mine listed five files and exited with code 1. To optionally see exactly what Prettier objected to, without changing anything:</p><pre>npx prettier --find-config-path web/src/App.tsx<br>npx prettier web/src/App.tsx | diff web/src/App.tsx -</pre><ul><li><strong>--find-config-path</strong> prints which config file Prettier uses for that file. It should print .prettierrc.</li><li><strong>The second line</strong> formats the file to standard output and diffs it against the original. Lines starting &lt; are the current file; lines starting &gt; are what Prettier wants.</li></ul><p>In my case the only difference was a missing newline at the end of each file I’d created, reported as \ No newline at end of file.</p><p><strong>Why look before fixing:</strong> a failing check is only useful if you know why it failed. Checking the config path proves Prettier is applying my style, not its defaults. If I’d run --write blind, the check would pass either way and I&#39;d never know which.</p><h3>Step 8: Format and review the diff</h3><pre>npm run format<br>npm run format:check; echo &quot;exit code: $?&quot;<br>git diff --stat</pre><ul><li>npm run format lists every file it checked and marks the ones it left (unchanged).</li><li>The check should now report All matched files use Prettier code style! and exit 0.</li><li>git diff --stat summarises the changes, one line per file.</li></ul><p>The stat should show small numbers: a line or two for each reformatted file, plus the dependency and script changes from earlier steps. New files such as .prettierrc don&#39;t appear, because git diff only covers files git already tracks.</p><p>Set your editor to add a final newline to files, too. In VS Code that’s files.insertFinalNewline. Prettier would catch it anyway, but there&#39;s no point creating the problem. A quick Google search should help you configure this in your IDE of choice.</p><p><strong>Why review the diff:</strong> you’re about to commit changes a tool made, not you. Always look at what a tool changed before committing it. Small numbers confirm the config does what you think. Hundreds of changed lines would mean something was wrong, and it’s far easier to spot now than in a later review.</p><h3>Step 9: Run every check, then commit</h3><pre>npm test &amp;&amp; npm run lint &amp;&amp; npm run format:check</pre><p>&amp;&amp; runs each command only if the one before it succeeded, so the first failure stops the chain.</p><p><strong>Why chain them:</strong> this one line is a rough local preview of the pipeline’s Build stage. Three commands, three gates, each a pass or fail. When the pipeline arrives, it will run these same commands in the same order. If they pass here, they should pass there.</p><p>If all three pass, commit and push:</p><pre>git status<br>git add .<br>git commit -m &quot;Add root lint script, fail lint on warnings, add Prettier with format check&quot;<br>git push</pre><p>In git status, check that .prettierrc and .prettierignore appear as new files and that nothing unexpected is listed.</p><h3>Where we are, and what’s next</h3><p>The repo now has three local quality gates, each a single command from the root with a binary result:</p><ul><li>npm test runs the unit tests.</li><li>npm run lint runs static analysis, and fails on warnings as well as errors.</li><li>npm run format:check checks formatting without changing anything.</li></ul><p>In the <a href="https://aws-samples.github.io/aws-deployment-pipeline-reference-architecture/application-pipeline/">AWS Deployment Pipeline Reference Architecture</a>, lint and format checks belong to the Build stage’s <strong>Code Quality</strong> action, run locally before commit as the guidance asks. When the pipeline arrives, these become Build-stage steps with no changes to the commands.</p><p>The Local Development column itself is about <strong>pre-commit hooks</strong>: checks that run automatically when you commit, so they don’t rely on anyone remembering to run them. Next time I’ll add the first one, a gitleaks secrets check that blocks a commit containing something like an access key. In a public repo, that’s the most important local gate of all. After that comes the AWS side, with infrastructure as code and a first deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cebacf336130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Quality In: A CI/CD Pipeline, Stage by Stage - Part 1: A Tested Hello World]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-ci-cd-part-1-a-tested-hello-world-f42d835b73d3?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42d835b73d3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[quality-engineering]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 14:51:11 GMT</pubDate>
            <atom:updated>2026-11-24T21:00:23.256Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this post you’ll have a public GitHub repo with a React hello world that runs locally and has one passing unit test. That’s deliberately small. It’s the first step in a series where I build a best-practice CI/CD pipeline on AWS, one stage at a time.</p><h3>Why this series</h3><p>When I coached QA Engieers on modern delivery pipelines, I found a lot of good theory but little practical examples. My goal for this series is to address that with a step by step example including local development, automated tests at every stage, a beta environment, and a production deploy behind a manual approval. The target is the <a href="https://pipelines.devops.aws.dev/">AWS Deployment Pipeline Reference Architecture</a> and the test types in AWS’s guidance on <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/strategy-cicd-litmus/tests-for-cicd-pipelines.html">tests for CI/CD pipelines</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lQlxZfrFHQ_pjvxsoFWOA.png" /></figure><p>The vehicle is a tiny web app called <strong>Mood Check</strong>. Eventually users will pick one of five emojis each day to say how they feel, and an admin view will chart the trend. The app is deliberately simple because the learning is in the pipeline, not the features.</p><p>The stack is TypeScript throughout: React with Vite for the frontend, Lambda and API Gateway for the API, DynamoDB for storage, AWS CDK for infrastructure, and GitHub Actions for CI/CD.</p><p>Part 1 starts with the foundations: a repo, a workspace layout, a running frontend, and a test that proves something.</p><h3>Step 1: Check your tooling</h3><p>Before writing anything, confirm what’s installed on your machine:</p><pre>node -v<br>npm -v<br>git --version</pre><p>At the time of writing, I’m on Node 24, npm 11 and git 2.54.</p><p><strong>Why it matters:</strong> use an even-numbered Node release (22 or 24). Even-numbered releases become Long Term Support (LTS) versions with years of security fixes. Odd-numbered releases are short-lived, and many libraries don’t fully support them. Your CI pipeline will run an LTS version, so your laptop should too.</p><h3>Step 2: Create the repo</h3><p>On github.com, create a new repository:</p><ul><li><strong>Name:</strong> mood-check</li><li><strong>Visibility:</strong> Public</li><li><strong>Add .gitignore:</strong> Node</li><li><strong>Licence:</strong> MIT</li></ul><p>Then clone it and move into it:</p><pre>git clone git@github.com:&lt;your-username&gt;/mood-check.git<br>cd mood-check</pre><p><strong>Why a .gitignore from the very first commit:</strong> the Node template stops node_modules and .env files from being committed. In a public repo this matters more than anywhere. A secret committed once stays in the git history even if you delete the file later, so the only safe secret is one that never gets committed.</p><h3>Step 3: Set up a monorepo workspace root</h3><p>The repo will eventually hold four parts: /web (frontend), /api (Lambda functions), /infra (CDK) and /e2e (Playwright tests). npm workspaces let them share one node_modules and one install.</p><p><strong>Why a monorepo for a one-person project:</strong> one pipeline covers the whole system, and a frontend, API and infrastructure change ships in a single commit, so they can’t drift out of step. The cost is slightly more care with tooling config.</p><p>Pin the Node version and create the root package.json:</p><pre>echo &quot;24&quot; &gt; .nvmrc<br>npm init -y</pre><p>Replace the generated package.json with:</p><pre>{<br>  &quot;name&quot;: &quot;mood-check&quot;,<br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: [&quot;web&quot;],<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;npm test --workspaces --if-present&quot;<br>  }<br>}</pre><p>What each piece does:</p><ul><li><strong>.nvmrc</strong> records the Node version. GitHub Actions will read the same file later, so the laptop and the pipeline use identical Node. That removes a whole class of &quot;works on my machine&quot; bugs.</li><li><strong>&quot;private&quot;: true</strong> stops the root package being published to npm by accident.</li><li><strong>&quot;workspaces&quot;: [&quot;web&quot;]</strong> lists workspace folders explicitly. We add api, infra and e2e as we create them, rather than using a wildcard that could pick up stray folders.</li><li><strong>The root </strong><strong>test script</strong> runs every workspace&#39;s tests. --if-present skips workspaces without a test script. This becomes the single command the pipeline calls.</li></ul><h3>Step 4: Scaffold the frontend with Vite</h3><p>Now we will generate a React + TypeScript app in /web. If it offers to install and start, say <strong>no</strong>. We install from the root instead:</p><pre>npm create vite@latest web -- --template react-ts</pre><pre>npm install</pre><p><strong>Why install from the root:</strong> npm sees the workspace and installs everything into a single node_modules at the repo root. You should not see a node_modules folder inside web/. It also creates package-lock.json, which records the exact version of every package installed. That file gets committed, and later the pipeline installs from it strictly with npm ci, so CI builds with the same versions you tested locally.</p><p>Check it runs:</p><pre>npm run dev -w web</pre><p>-w web runs a script in a specific workspace from the root. Open the URL it prints, check the page loads, then stop it with Ctrl+C.</p><p><strong>Why Vite:</strong> it starts in well under a second, reloads instantly as you edit, and its config is reused by Vitest in the next step, so there’s only one build setup to maintain.</p><h3>Step 5: Add unit testing and write a failing test</h3><p>Install the test tools into the web workspace:</p><pre>npm install -D vitest jsdom @testing-library/react -w web</pre><ul><li><strong>Vitest</strong> is the test runner. It reuses Vite’s config, so tests compile exactly as the app does.</li><li><strong>jsdom</strong> simulates a browser DOM inside Node, so component tests run in milliseconds without launching a real browser. Real browsers come later, with Playwright.</li><li><strong>Testing Library</strong> renders components and finds elements the way a user would: by role and visible text, not CSS classes or internal structure. Tests written this way survive refactoring, because they only break when behaviour a user can see changes.</li></ul><p>-D saves them as dev dependencies: needed to build and test, never shipped to users.</p><p>Replace web/vite.config.ts so Vitest knows to use jsdom:</p><pre>import { defineConfig } from &#39;vitest/config&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>export default defineConfig({<br>  plugins: [react()],<br>  test: { environment: &#39;jsdom&#39; },<br>})</pre><p>In web/package.json, add a test script:</p><pre>&quot;test&quot;: &quot;vitest run&quot;</pre><p>vitest run runs once and exits, which is what a pipeline needs. Plain vitest stays in watch mode.</p><p>Now write the test <strong>before</strong> changing the app (some good old Test Driven Development). Create web/src/App.test.tsx:</p><pre>import { render, screen } from &#39;@testing-library/react&#39;<br>import { describe, it, expect } from &#39;vitest&#39;<br>import App from &#39;./App&#39;<br><br>describe(&#39;App&#39;, () =&gt; {<br>  it(&#39;shows the app heading&#39;, () =&gt; {<br>    render(&lt;App /&gt;)<br>    expect(screen.getByRole(&#39;heading&#39;, { name: &#39;Mood Check&#39; })).toBeTruthy()<br>  })<br>})</pre><p>Run it from the root:</p><pre>npm test</pre><p>It <em>should</em> fail with Unable to find an accessible element with the role &quot;heading&quot; and name &quot;Mood Check&quot;, because the Vite template&#39;s page says &quot;Get started&quot;. That&#39;s the point.</p><p><strong>Why watch it fail first:</strong> a test you’ve never seen fail might not be testing anything. Seeing it fail <em>for the right reason</em> (the heading is missing, not a broken import) proves it can catch a real problem.</p><p>Three things worth noticing in the output:</p><ul><li>Testing Library prints every accessible role it found. That’s a handy debugging aid, and it shows the test is reading the page the way a screen reader would. Querying by heading role is also a small free accessibility check: swap the &lt;h1&gt; for a styled &lt;div&gt; and this test fails.</li><li>The command ends with code 1. A non-zero exit code is how CI knows to stop. That single number is the whole mechanism behind a quality gate.</li><li>It ran in under a second. Fast unit tests are what make it practical to run them on every commit.</li></ul><h3>Step 6: Make it pass, then tidy up</h3><p>Replace web/src/App.tsx with the simplest thing that satisfies the test:</p><pre>export default function App() {<br>  return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Mood Check&lt;/h1&gt;<br>      &lt;p&gt;How are you feeling today?&lt;/p&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><p>Run npm test again. You should see 1 passed and no npm error at the end.</p><p>Then delete the template leftovers the new page no longer uses: web/src/App.css and the demo images in web/src/assets. Keep index.css and main.tsx, because main.tsx imports index.css. Run npm test and npm run dev -w web once more to confirm nothing broke.</p><p><strong>Why tidy now:</strong> every tool added later (linting, static analysis, coverage) has to read unused code too. Dead files create noise in reports and false findings. Starting clean costs a minute; cleaning up later costs more.</p><h3>Step 7: Commit and push</h3><p>Check what’s about to be committed:</p><pre>git status</pre><p>You want to see package-lock.json listed and node_modules absent. If node_modules appears, the .gitignore isn&#39;t working; fix that before committing.</p><pre>git add .<br>git commit -m &quot;Scaffold web workspace with Vite, React and a first Vitest test&quot;<br>git push</pre><p><strong>Why commit the lockfile:</strong> without it, two installs a week apart can pull different dependency versions, and a build can break with no code change. Committing it makes every install reproducible. It’s the foundation the pipeline’s quality gates stand on.</p><h3>Where we are, and what’s next</h3><p>After one session the repo has a pinned Node version, a workspace layout ready for the API and infrastructure, a running React app, and a unit test that’s been seen to fail and then pass. In terms of the reference architecture, that’s the start of the <strong>Local Development</strong> column: build code and unit tests.</p><p><a href="https://medium.com/@robert_mcbryde/building-a-ci-cd-part-2-linting-and-formatting-as-quality-gates-cebacf336130">Next time</a>: linting, code formatting and a pre-commit secrets check, which complete that column. After that comes the AWS side, with infrastructure as code and a first deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42d835b73d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Root, IAM Users or SSO? How Access to AWS Actually Works]]></title>
            <link>https://medium.com/@robert_mcbryde/root-iam-users-or-sso-how-access-to-aws-actually-works-6e38de49828e?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e38de49828e</guid>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 16:24:31 GMT</pubDate>
            <atom:updated>2026-10-13T16:24:31.929Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to the three ways people get into an AWS account, why the industry moved to SSO, and what you’ll actually be handed on your first day at a company.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bBryPf2Mx9k8_ijS" /><figcaption>Photo by <a href="https://unsplash.com/@sarahdorweiler?utm_source=medium&amp;utm_medium=referral">Sarah Dorweiler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>The short version</strong>: use the root user almost never, avoid IAM users for people, and use SSO (IAM Identity Center) for every human who logs in. The rest of this post explains why.</p><h3>1. The root user: the keys to the kingdom</h3><p>When you sign up for AWS with an email address and password, you create the <strong>root user</strong>. It’s the account’s owner identity, and it can do anything. No IAM policy can restrict it. The one exception is in an AWS Organization, where guardrail policies (service control policies, or SCPs) can restrict root in member accounts. They can’t restrict it in the management account.</p><p>You only genuinely need root for a handful of jobs:</p><ul><li>Changing the account’s email address or contact details</li><li>Closing the account</li><li>Some billing settings, such as letting IAM identities see billing data</li><li>Recovering access if every admin identity is locked out</li></ul><p>Everything else should be done by another identity.</p><h3>Locking it down</h3><ul><li><strong>Use a strong, unique password</strong>, kept in a password manager.</li><li><strong>Turn on MFA.</strong> A passkey or hardware security key is best; an authenticator app is fine. AWS lets you register more than one device, so losing your phone doesn’t lock you out of your own account.</li><li><strong>Never create root access keys.</strong> A leaked root key is about as bad as AWS security failures get.</li><li><strong>Set alternate contacts</strong> for billing, security and operations, so AWS can reach the right person if something goes wrong.</li><li><strong>Sign in as root rarely</strong>, and treat every sign-in as unusual.</li></ul><p>If you use AWS Organizations, there’s now a further option: centralised root access management, which removes root credentials from member accounts entirely. Accounts created through Organizations don’t get a usable root password unless someone goes through password recovery.</p><h3>2. The traditional way: an IAM admin user</h3><p>For years the standard advice was: create an IAM user for yourself, give it admin rights, and stop using root.</p><ol><li>Signed in as root, create an IAM user such as admin.</li><li>Put it in an Admins group with the AdministratorAccess managed policy attached. Attach policies to groups rather than individual users, so access is easier to audit and change.</li><li>Give the user a console password and MFA.</li><li>For command-line access, create an access key and store it in ~/.aws/credentials.</li></ol><p>This works, and it’s much better than using root. But it has structural weaknesses:</p><ul><li><strong>The access key never expires.</strong> It stays valid until someone deletes it, and rotation relies on someone remembering to do it.</li><li><strong>The key sits in plain text on disk.</strong> Long-lived keys are exactly the credentials that end up in .env files, screenshots and git history.</li><li><strong>MFA protects the console, not the CLI.</strong> You can require MFA for CLI calls, but it involves sts get-session-token and policy conditions, and few people bother.</li><li><strong>It doesn’t scale across accounts.</strong> An IAM user exists in one account. Five accounts means five users, five passwords and five sets of keys.</li></ul><h3>3. IAM Identity Center: SSO for AWS</h3><p>IAM Identity Center is AWS’s SSO service. It runs from your Organization’s management account and gives people one login across every AWS account they’re allowed into. It is the successor to AWS Single Sign-On.</p><p><em>What is SSO? — skip this section if you are already familiar with SSO</em></p><p><em>Single sign-on (SSO) means you prove who you are once, to one trusted system, and other systems accept that proof instead of keeping their own passwords for you.</em></p><p><em>You already use it. When you click “Sign in with Google” on a website, or log in to your work laptop and find Slack, Jira and email already open, that’s SSO.</em></p><p><em>There are two roles in every SSO arrangement:</em></p><ul><li><strong><em>The identity provider (IdP)</em></strong><em> holds your identity: username, password, MFA, group memberships. Examples are Okta, Microsoft Entra ID (formerly Azure AD) and Google Workspace.</em></li><li><strong><em>The service provider</em></strong><em> is the application you want to use. It doesn’t store your password. It trusts a signed message from the IdP that says who you are and which groups you belong to.</em></li></ul><p><em>That signed message travels using a standard protocol, usually SAML 2.0 or OpenID Connect (OIDC). You don’t need the protocol details to use SSO, but the names come up in every enterprise setup conversation.</em></p><p><em>Why organisations care:</em></p><ul><li><strong><em>One place to enforce security.</em></strong><em> Password rules and MFA are set once, at the IdP.</em></li><li><strong><em>One place to remove access.</em></strong><em> When someone leaves, disabling their IdP account cuts them off from everything at once.</em></li><li><strong><em>Fewer passwords.</em></strong><em> Fewer credentials to phish, reuse or leak.</em></li></ul><h3>Back to the AWS approach to SSO — AWS Identity Centre</h3><p>Four terms make it click:</p><ul><li><strong>User:</strong> you, the human. You live in Identity Center’s own directory, or in your company’s IdP.</li><li><strong>Permission set:</strong> a reusable bundle of policies, such as AdministratorAccess or ReadOnlyAccess.</li><li><strong>Assignment:</strong> a <em>user</em> or <em>group</em>, plus a <em>permission set</em>, plus an <em>account</em>. Identity Center turns each assignment into an IAM role in that account, named AWSReservedSSO_&lt;PermissionSet&gt;_&lt;random&gt;.</li><li><strong>Access portal:</strong> the web page where you log in and pick an account and role. The CLI uses the same login.</li></ul><p>The key shift: you never “are” an IAM user. You <strong>assume a role</strong> and get temporary credentials that expire after the permission set’s session duration (one hour by default, up to twelve).</p><p>On the command line it looks like this:</p><pre>aws configure sso            # one-off, configure an IAM Identity Center profile via CLI wizard<br>aws sso login --sso-session &lt;name&gt;<br>aws sts get-caller-identity --profile &lt;profile&gt;</pre><p>The last command is the most useful one in AWS. It tells you which account and role you’re using, and it needs no permissions, so it works whenever your credentials are valid.</p><h3>IAM users vs Identity Center: the security comparison</h3><p><strong>Credential lifetime.</strong> IAM user keys last until deleted. Identity Center credentials last hours.</p><p><strong>If a credential leaks.</strong> A leaked IAM key works until someone notices. A leaked SSO credential expires on its own.</p><p><strong>MFA.</strong> IAM users get MFA on the console if you set it up. Identity Center enforces MFA at every login, CLI included.</p><p><strong>Multiple accounts.</strong> IAM users need one identity per account. Identity Center gives one login with an account picker.</p><p><strong>Offboarding.</strong> With IAM users, you hunt down users and keys in every account. With Identity Center, you disable one identity.</p><p><strong>Audit.</strong> CloudTrail shows the IAM user name in one case, and the role plus the person’s username in the other.</p><h3>When an IAM user is still reasonable</h3><ul><li>A third-party tool that only accepts static keys</li><li>A deliberately locked-away break-glass identity</li><li>A legacy system you’re not allowed to change</li></ul><p>For any human who logs in regularly, use SSO, even on a personal account. That’s AWS’s own recommendation.</p><h3>4. Personal setup vs company setup</h3><h3>A sensible personal or learning setup</h3><ul><li>A small Organization: a management account for billing and identity, plus one or two workload accounts (for example, a sandbox and a production account).</li><li>Identity Center with its built-in directory, and two permission sets: one admin, one read-only.</li><li>Root locked down with MFA on every account.</li><li>A budget alarm before anything else. A budget is an alert, not a spending cap; AWS won’t switch anything off for you.</li><li>Building and experimenting in a workload account, not the management account.</li></ul><h3>A typical company setup</h3><ul><li><strong>Many accounts in an Organization</strong>, often built with AWS Control Tower as a “landing zone”. Typically a management account used only for billing, separate log-archive and security accounts, shared-services accounts, and workload accounts split by environment (dev, staging, prod) and often by team.</li><li><strong>SCPs as guardrails</strong>, for example blocking unapproved regions or stopping anyone from turning off CloudTrail logging.</li><li><strong>Identity Center federated with the corporate IdP</strong>, so your laptop login is your AWS login.</li><li><strong>Graduated access</strong>: broad permissions in dev, read-only in prod, and temporary, approved elevation in prod when an incident needs it.</li><li><strong>No human-style credentials for machines.</strong> CI/CD pipelines authenticate with OIDC roles (GitHub Actions supports this natively), and running workloads use roles, such as a Lambda function’s execution role.</li></ul><h3>6. What you need on day one as an engineer</h3><ol><li><strong>AWS CLI v2</strong> on your laptop. Version 1 has no built-in SSO login.</li><li><strong>The access portal URL and SSO region</strong>, usually from the team’s onboarding page.</li><li><strong>Membership of the right group</strong> in the IdP, which grants your permission sets. This normally means an access request.</li><li><strong>One CLI profile per account and role</strong> in ~/.aws/config, named by environment, such as acme-dev-developer and acme-prod-readonly.</li><li><strong>aws sso login each morning.</strong> CDK, Terraform, the AWS SDKs and the Serverless Framework all pick up the AWS_PROFILE environment variable.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e38de49828e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Best Practice Test Automation Pipeline with CI/CD: Part 2 — GitHub Integration and…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-best-practice-test-automation-pipeline-with-ci-cd-part-2-github-integration-and-eb6fb5545f73?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6fb5545f73</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 10:52:20 GMT</pubDate>
            <atom:updated>2025-03-11T10:52:20.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Best Practice Test Automation Pipeline with CI/CD: Part 2 — GitHub Integration and Cloud Deployment with Infrastructure as Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeWufOvnTC94ep67" /><figcaption>Photo by <a href="https://unsplash.com/@jxndreas?utm_source=medium&amp;utm_medium=referral">Andreas Kind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In <a href="https://medium.com/@robert_mcbryde/building-a-best-practice-test-automation-pipeline-with-ci-cd-part-1-creating-a-spring-boot-rest-5ada5c18a4b8">Part 1 of our series</a>, we created a solid foundation for our test automation pipeline by building a Spring Boot REST API with robust testing capabilities. We implemented a /hello endpoint along with actuator-enabled health monitoring through /health and /info endpoints. We incorporated static code analysis using the maven-checkstyle-plugin with Google&#39;s style guides, wrote unit tests for our controller, containerised our application with Docker, and used Testcontainers with REST Assured to run API tests against our containerised application.</p><p>While these capabilities allowed us to develop and test our application locally, a production-ready application needs more: source control, automated CI/CD pipelines, and deployment to cloud environments. In this post, we’ll take our application to the next level by implementing these essential practices using Git, GitHub Actions, Terraform, and Google Cloud Platform (GCP).</p><p><em>Warning</em>: this is long post, but covers a lot of content.</p><h3>Prerequisites</h3><p>Before diving into this tutorial, you’ll need to have Git, Terraform and Google Cloud CLI properly configured on your machine. This includes having Git installed and setting up your user information for commits. I won’t be covering the Git or Terraform installations and configuration process in this article, as there are many excellent resources available online that provide detailed instructions for different operating systems. I have previously written about how to setup <a href="https://medium.com/@robert_mcbryde/installing-the-gloud-cli-ae66ec00d2e9">Google Cloud CLI on a mac</a>.</p><h3>What We’ll Accomplish</h3><p>By the end of this tutorial, we’ll have:</p><ol><li>Added Git-based source control to our project</li><li>Created a GitHub repository and configured it for our CI/CD needs</li><li>Implemented a CI/CD pipeline using GitHub Actions</li><li>Set up infrastructure as code using Terraform to provision our GCP resources</li><li>Deployed our Spring Boot application to Google Cloud Run in three separate environments, Dev, Staging and Production</li><li>Implemented smoke tests to validate our deployments</li></ol><p>Let’s get started on the journey from local development to cloud deployment!</p><h3>Setting Up Source Control with Git</h3><p>Version control is essential for any software project. Git allows us to track changes, collaborate effectively, and maintain a history of our codebase. Let’s initialise our project as a Git repository.</p><h4>Initialising Git Repository</h4><p>First, navigate to our project’s root directory and initialise a Git repository:</p><pre>cd automation-demo<br>git init</pre><h4>Creating a .gitignore File</h4><p>Next, let’s create a .gitignore file to exclude files and directories that shouldn&#39;t be tracked in our repository. Create this file in the root of your project:</p><pre>HELP.md<br>target/<br>!.mvn/wrapper/maven-wrapper.jar<br>!**/src/main/**/target/<br>!**/src/test/**/target/<br><br>### STS ###<br>.apt_generated<br>.classpath<br>.factorypath<br>.project<br>.settings<br>.springBeans<br>.sts4-cache<br><br>### IntelliJ IDEA ###<br>.idea<br>*.iws<br>*.iml<br>*.ipr<br><br>### NetBeans ###<br>/nbproject/private/<br>/nbbuild/<br>/dist/<br>/nbdist/<br>/.nb-gradle/<br>build/<br>!**/src/main/**/build/<br>!**/src/test/**/build/<br><br>### VS Code ###<br>.vscode/<br><br># Terraform<br>*.tfvars<br>*.tfstate<br>*.tfstate.*<br>.terraform/<br>.terraform.lock.hcl<br>!*.tfvars.example<br><br># Specific tfvars exclusion<br>terraform/service-accounts/terraform.tfvars</pre><p>The .gitignore file we&#39;ve created covers a wide range of files that shouldn&#39;t be committed to our repository, including build outputs, IDE-specific files, local configuration, and generated Terraform files. This keeps our repository clean and prevents sensitive or environment-specific information from being shared.</p><h4>Initial Commit</h4><p>Now, let’s add our existing files and make our first commit:</p><pre>git add .<br>git commit -m &quot;Initial commit: Spring Boot API with testing infrastructure&quot;</pre><p>This captures the current state of our project in Git, creating a reference point we can always return to if needed.</p><h3>Setting Up GitHub Repository</h3><p>Now that we have our local Git repository set up, let’s create a remote repository on GitHub.</p><ol><li>Go to <a href="https://github.com/">GitHub</a> and log in to your account</li><li>Click the “+” icon in the top-right corner and select “New repository”</li><li>Name your repository (e.g., “automation-demo”)</li><li>Add a description (optional)</li><li>Choose “Public” or “Private” visibility based on your needs</li><li>Skip the initialisation options since we already have files locally</li><li>Click “Create repository”</li></ol><p>After creating the repository, connect your local repository to the remote GitHub repository (note to add your GitHub username in the URL):</p><pre>git remote add origin https://github.com/&lt;your_user_name&gt;/automation-demo.git<br>git branch -M main<br>git push -u origin main</pre><p>The commands above establish a connection between your local repository and the GitHub repository, rename your main branch (if it’s not already called “main”), and push your code to GitHub. Now your code is safely backed up and ready for collaborative development 🚀.</p><h3>Implementing CI/CD with GitHub Actions</h3><p>Now that our code is on GitHub, let’s set up a CI/CD pipeline using GitHub Actions. This will automate our build, test, and deployment processes.</p><h4>Common Development Strategies</h4><p>Before we start to construct our CI/CD pipeline, we need to decide upon our Software development strategy. Such strategies exist to manage code changes efficiently, reduce integration issues, and balance stability with fast iteration. The right strategy depends on factors like team size, release cadence, and deployment process. In this series we will be using <strong>Trunk-Based Development</strong>, I have summarised my thoughts on TBD below and justified, in my opinion, why it will work for our project.</p><p><em>Side note: when working with mobile development, I tend to favour GitFlow given the requirement for app review stages by Apple and Google. I won’t go into it in this article, but if you are embarking on a mobile project, I advise looking into GitFlow as an alternative to TBD.</em></p><h3>Trunk-Based Development (TBD)</h3><ul><li>Developers commit directly to the main branch (trunk) or use <strong>short-lived</strong> feature branches that merge quickly (often within a day or two), reducing the risk of large, long-lived branches creating merge hell.</li><li>Continuous Integration (CI) runs automated tests to ensure stability.</li><li>Frequent, small releases minimise risk and enable rapid feedback.</li><li>Suits High-paced, CI/CD-driven environments like web development, cloud services, and DevOps teams.</li><li>Automated testing and feature flags allow for safe, incremental releases.</li><li>Encourages fast iteration and faster time-to-market.</li><li>Works well in cloud-based and SaaS environments where deployments are frequent.</li></ul><h3>Trunk-Based Development with Deployment Gates</h3><p>We will be implementing a CI/CD pipeline across numerous environments, <strong>Dev</strong>, <strong>Staging</strong> and <strong>Production. </strong>This is a<strong> </strong>very common pattern and fits well with DevOps best practices.</p><p>Here’s how it typically works:</p><ul><li><strong>Single Source Branch</strong>: All development happens in a single branch, in our case the main branch.</li><li><strong>Short-Lived Feature Branches</strong>: Developers create short-lived feature branches for changes, then merge back to main quickly.</li><li><strong>Deployment Pipeline with Gates</strong>: A single pipeline deploys to all environments sequentially, with approval gates between environments.</li></ul><p>For example, we make a change to our code base and run it locally to confirm we are happy it achieves our intention. We then push this change to our main branch in GitHub. This will automatically trigger our CI/CD pipeline that will run our static analysis, unit tests, create a Docker image of our application and create a containerised version of our application.</p><p>It will then run our API tests on this running container and provided all our tests pass, it will automatically deploy our Spring Boot application to our Dev environment in hosted in Google Cloud and run our automated smoke tests to ensure that it has deployed successfully. Our pipeline will then pause until we manually approve it to continue to proceed with the deployment to our Staging environment.</p><p>In a real world environment this allows us to perform further manual testing within our shared development environment with our colleagues to further verify we are happy with the changes we have introduced and that they work in the wider context of other teams applications running in conjunction as a system.</p><p>Once we approve the gateway, then the pipeline continues to deploy our application into our Staging environment in Google Cloud, again running automated smoke tests on completion. It is commonplace for manual QA colleagues to then be able to perform further testing in the Staging environment to verify correctness of our deployed code in accordance with acceptance criteria and user requirements.</p><p>Once again our pipeline hits our production gateway, awaiting further review and manual confirmation that the deployment should continue to our Production environment, again hosted in Google Cloud.</p><h3>Setting Up GitHub Environment Protection Rules</h3><p>The key to implementing deployment gates in GitHub Actions is using environments with protection rules. Here’s how to set it up:</p><ol><li>Within GitHub, go to your repository settings</li><li>Click on “Environments” in the sidebar</li><li>Create three environments: development, staging, and production</li><li>For each environment, configure appropriate protection rules:</li></ol><ul><li><strong>Development</strong>: Minimal protection (optional approvals)</li><li><strong>Staging</strong>: Required reviewers (1–2 people)</li><li><strong>Production</strong>: Required reviewers (2+ people)</li></ul><p>This creates deployment gates between environments. When the workflow runs:</p><ol><li>It will deploy to the development environment automatically</li><li>Then it will pause before the staging deployment, requiring approval from designated reviewers</li><li>Finally, it will pause again before the production deployment, potentially requiring approval from more senior reviewers</li></ol><h4>Advantages of This Approach</h4><ol><li><strong>Simplified Branching Strategy</strong>: All development happens in a single branch, reducing merge conflicts and complexity</li><li><strong>Continuous Deployment</strong>: Changes are automatically deployed to development for early testing</li><li><strong>Manual Approval Gates</strong>: Human judgment is required before deploying to higher environments</li><li><strong>Consistent Build Artifacts</strong>: The same build artifact moves through all environments, reducing “it works on my machine” issues</li><li><strong>Auditable Deployment Process</strong>: Approvals are recorded in GitHub, creating an audit trail</li></ol><h4>Creating the GitHub Actions Workflow File</h4><p>GitHub Actions workflows are defined in YAML files stored in the .github/workflows directory. Let&#39;s create this directory in the root of our project and a workflows file:</p><pre>mkdir -p .github/workflows</pre><p>Now, let’s create our workflow file called ci-cd-pipeline.yml and place it inside the workflowsdirectory we just created. It’s this code that defines the jobs and stages that make up our CI/CD pipeline, all captured in code. I will provide this in it’s entirety, before breaking it down into smaller sections to explain what it’s doing.</p><pre>name: CI/CD Pipeline with Gates<br><br>on:<br>  push:<br>    branches: [ main ]<br>  pull_request:<br>    branches: [ main ]<br>  workflow_dispatch:  # Allows manual triggering<br><br>jobs:<br>  build-and-test:<br>    name: Build and Test<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Set up JDK 17<br>      uses: actions/setup-java@v4<br>      with:<br>        java-version: &#39;17&#39;<br>        distribution: &#39;temurin&#39;<br>        cache: maven<br><br>    - name: Validate Maven project<br>      run: mvn validate<br><br>    - name: Static Code Analysis<br>      run: mvn checkstyle:check<br><br>    - name: Build with Maven<br>      run: mvn -B package -DskipTests<br><br>    - name: Run Unit Tests<br>      run: mvn test<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br><br>    - name: Build Docker image for testing<br>      run: docker build -t spring-boot-api:test .<br><br>    - name: Run API Tests with Testcontainers<br>      run: mvn verify -Dskip.unit.tests=true<br><br>    - name: Upload build artifact<br>      uses: actions/upload-artifact@v4<br>      with:<br>        name: app-jar<br>        path: target/*.jar<br>        retention-days: 1<br><br>  deploy-to-dev:<br>    name: Deploy to Development<br>    needs: build-and-test<br>    runs-on: ubuntu-latest<br>    if: github.ref == &#39;refs/heads/main&#39; &amp;&amp; (github.event_name == &#39;push&#39; || github.event_name == &#39;workflow_dispatch&#39;)<br>    environment: development <br>    env:<br>      ENVIRONMENT: dev<br>      PROJECT_ID: ${{ secrets.GCP_PROJECT_DEV }}<br>      SERVICE_NAME: spring-boot-api-dev<br>      REGION: us-central1<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Download build artifact<br>      uses: actions/download-artifact@v4<br>      with:<br>        name: app-jar<br>        path: target<br><br>    - name: Setup Cloud SDK<br>      uses: google-github-actions/setup-gcloud@v1<br>      with:<br>        project_id: ${{ env.PROJECT_ID }}<br><br>    - name: Authenticate to Google Cloud<br>      uses: google-github-actions/auth@v1<br>      with:<br>        credentials_json: ${{ secrets.GCP_SA_KEY_DEV }}<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br><br>    - name: Build and Push Docker image<br>      run: |<br>        # Configure Docker for Artifact Registry<br>        gcloud auth configure-docker ${{ env.REGION }}-docker.pkg.dev<br>        <br>        # Build with environment-specific Spring profile<br>        docker build \<br>          --build-arg SPRING_PROFILES_ACTIVE=${{ env.ENVIRONMENT }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest .<br>          <br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest<br><br>    - name: Setup Terraform<br>      uses: hashicorp/setup-terraform@v2<br>      with:<br>        terraform_version: 1.5.0<br><br>    - name: Initialize Terraform<br>      run: |<br>        cd terraform/environments/dev<br>        terraform init<br><br>    - name: Apply Terraform<br>      run: |<br>        cd terraform/environments/dev<br>        terraform apply -auto-approve<br>      env:<br>        TF_VAR_project_id: ${{ env.PROJECT_ID }}<br>        TF_VAR_region: ${{ env.REGION }}<br>        TF_VAR_service_name: ${{ env.SERVICE_NAME }}<br>        TF_VAR_environment: ${{ env.ENVIRONMENT }}<br><br>    - name: Deploy to Cloud Run<br>      uses: google-github-actions/deploy-cloudrun@v1<br>      with:<br>        service: ${{ env.SERVICE_NAME }}<br>        region: ${{ env.REGION }}<br>        image: ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br><br>    - name: Smoke Test Development<br>      run: |<br>        export SERVICE_URL=$(gcloud run services describe ${{ env.SERVICE_NAME }} --region ${{ env.REGION }} --format &#39;value(status.url)&#39;)<br>        echo &quot;DEV Service URL: $SERVICE_URL&quot;<br>        <br>        # Wait for service to be fully deployed<br>        sleep 30<br>        <br>        # Test health endpoint<br>        HEALTH_STATUS=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; $SERVICE_URL/actuator/health)<br>        if [ &quot;$HEALTH_STATUS&quot; != &quot;200&quot; ]; then<br>          echo &quot;Health check failed with status $HEALTH_STATUS&quot;<br>          exit 1<br>        fi<br>        <br>        # Test hello endpoint<br>        HELLO_RESPONSE=$(curl -s $SERVICE_URL/api/hello)<br>        if [[ &quot;$HELLO_RESPONSE&quot; != *&quot;Hello&quot;* ]]; then<br>          echo &quot;Hello endpoint check failed. Response: $HELLO_RESPONSE&quot;<br>          exit 1<br>        fi<br>        echo &quot;DEV deployment smoke test passed successfully!&quot;<br><br>  deploy-to-staging:<br>    name: Deploy to Staging<br>    needs: deploy-to-dev<br>    runs-on: ubuntu-latest<br>    environment: staging  <br>    env:<br>      ENVIRONMENT: staging<br>      PROJECT_ID: ${{ secrets.GCP_PROJECT_STAGING }}<br>      SERVICE_NAME: spring-boot-api-staging<br>      REGION: us-central1<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Download build artifact<br>      uses: actions/download-artifact@v4<br>      with:<br>        name: app-jar<br>        path: target<br><br>    - name: Setup Cloud SDK<br>      uses: google-github-actions/setup-gcloud@v1<br>      with:<br>        project_id: ${{ env.PROJECT_ID }}<br><br>    - name: Authenticate to Google Cloud<br>      uses: google-github-actions/auth@v1<br>      with:<br>        credentials_json: ${{ secrets.GCP_SA_KEY_STAGING }}<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br><br>    - name: Build and Push Docker image<br>      run: |<br>        # Configure Docker for Artifact Registry<br>        gcloud auth configure-docker ${{ env.REGION }}-docker.pkg.dev<br>        <br>        # Build with environment-specific Spring profile<br>        docker build \<br>          --build-arg SPRING_PROFILES_ACTIVE=${{ env.ENVIRONMENT }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest .<br>          <br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest<br><br>    - name: Setup Terraform<br>      uses: hashicorp/setup-terraform@v2<br>      with:<br>        terraform_version: 1.5.0<br><br>    - name: Initialize Terraform<br>      run: |<br>        cd terraform/environments/staging<br>        terraform init<br><br>    - name: Apply Terraform<br>      run: |<br>        cd terraform/environments/staging<br>        terraform apply -auto-approve<br>      env:<br>        TF_VAR_project_id: ${{ env.PROJECT_ID }}<br>        TF_VAR_region: ${{ env.REGION }}<br>        TF_VAR_service_name: ${{ env.SERVICE_NAME }}<br>        TF_VAR_environment: ${{ env.ENVIRONMENT }}<br><br>    - name: Deploy to Cloud Run<br>      uses: google-github-actions/deploy-cloudrun@v1<br>      with:<br>        service: ${{ env.SERVICE_NAME }}<br>        region: ${{ env.REGION }}<br>        image: ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br><br>    - name: Smoke Test Staging<br>      run: |<br>        export SERVICE_URL=$(gcloud run services describe ${{ env.SERVICE_NAME }} --region ${{ env.REGION }} --format &#39;value(status.url)&#39;)<br>        echo &quot;STAGING Service URL: $SERVICE_URL&quot;<br>        <br>        # Wait for service to be fully deployed<br>        sleep 30<br>        <br>        # Test health endpoint<br>        HEALTH_STATUS=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; $SERVICE_URL/actuator/health)<br>        if [ &quot;$HEALTH_STATUS&quot; != &quot;200&quot; ]; then<br>          echo &quot;Health check failed with status $HEALTH_STATUS&quot;<br>          exit 1<br>        fi<br>        <br>        # Test hello endpoint<br>        HELLO_RESPONSE=$(curl -s $SERVICE_URL/api/hello)<br>        if [[ &quot;$HELLO_RESPONSE&quot; != *&quot;Hello&quot;* ]]; then<br>          echo &quot;Hello endpoint check failed. Response: $HELLO_RESPONSE&quot;<br>          exit 1<br>        fi<br>        echo &quot;STAGING deployment smoke test passed successfully!&quot;<br><br>  deploy-to-production:<br>    name: Deploy to Production<br>    needs: deploy-to-staging<br>    runs-on: ubuntu-latest<br>    environment: production  <br>    env:<br>      ENVIRONMENT: prod<br>      PROJECT_ID: ${{ secrets.GCP_PROJECT_PROD }}<br>      SERVICE_NAME: spring-boot-api<br>      REGION: us-central1<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Download build artifact<br>      uses: actions/download-artifact@v4<br>      with:<br>        name: app-jar<br>        path: target<br><br>    - name: Setup Cloud SDK<br>      uses: google-github-actions/setup-gcloud@v1<br>      with:<br>        project_id: ${{ env.PROJECT_ID }}<br><br>    - name: Authenticate to Google Cloud<br>      uses: google-github-actions/auth@v1<br>      with:<br>        credentials_json: ${{ secrets.GCP_SA_KEY_PROD }}<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br><br>    - name: Build and Push Docker image<br>      run: |<br>        # Configure Docker for Artifact Registry<br>        gcloud auth configure-docker ${{ env.REGION }}-docker.pkg.dev<br>        <br>        # Build with environment-specific Spring profile<br>        docker build \<br>          --build-arg SPRING_PROFILES_ACTIVE=${{ env.ENVIRONMENT }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest .<br>          <br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest<br><br>    - name: Setup Terraform<br>      uses: hashicorp/setup-terraform@v2<br>      with:<br>        terraform_version: 1.5.0<br><br>    - name: Initialize Terraform<br>      run: |<br>        cd terraform/environments/prod<br>        terraform init<br><br>    - name: Apply Terraform<br>      run: |<br>        cd terraform/environments/prod<br>        terraform apply -auto-approve<br>      env:<br>        TF_VAR_project_id: ${{ env.PROJECT_ID }}<br>        TF_VAR_region: ${{ env.REGION }}<br>        TF_VAR_service_name: ${{ env.SERVICE_NAME }}<br>        TF_VAR_environment: ${{ env.ENVIRONMENT }}<br><br>    - name: Deploy to Cloud Run<br>      uses: google-github-actions/deploy-cloudrun@v1<br>      with:<br>        service: ${{ env.SERVICE_NAME }}<br>        region: ${{ env.REGION }}<br>        image: ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br><br>    - name: Smoke Test Production<br>      run: |<br>        export SERVICE_URL=$(gcloud run services describe ${{ env.SERVICE_NAME }} --region ${{ env.REGION }} --format &#39;value(status.url)&#39;)<br>        echo &quot;PRODUCTION Service URL: $SERVICE_URL&quot;<br>        <br>        # Wait for service to be fully deployed<br>        sleep 30<br>        <br>        # Test health endpoint<br>        HEALTH_STATUS=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; $SERVICE_URL/actuator/health)<br>        if [ &quot;$HEALTH_STATUS&quot; != &quot;200&quot; ]; then<br>          echo &quot;Health check failed with status $HEALTH_STATUS&quot;<br>          exit 1<br>        fi<br>        <br>        # Test hello endpoint<br>        HELLO_RESPONSE=$(curl -s $SERVICE_URL/api/hello)<br>        if [[ &quot;$HELLO_RESPONSE&quot; != *&quot;Hello&quot;* ]]; then<br>          echo &quot;Hello endpoint check failed. Response: $HELLO_RESPONSE&quot;<br>          exit 1<br>        fi<br>        echo &quot;PRODUCTION deployment smoke test passed successfully!&quot;</pre><p>Our pipeline code contains a<strong> lot</strong> of code! Let’s break it down to what it is doing.</p><pre>name: CI/CD Pipeline with Gates<br><br>on:<br>  push:<br>    branches: [ main ]<br>  pull_request:<br>    branches: [ main ]<br>  workflow_dispatch:  # Allows manual triggering</pre><p>Our pipeline begins by defining when it should run. The workflow triggers on three events:</p><ol><li>When code is pushed directly to the main branch</li><li>When a pull request is opened against the main branch (allowing for validation before merging)</li><li>When manually triggered via the GitHub interface</li></ol><p>By focusing on the main branch, we enforce the trunk-based development principle that all work revolves around a single, canonical source of truth. Unlike branch-based strategies where different environments live on different branches, our approach keeps everything in one place, reducing complexity and merge conflicts.</p><h4>Job 1: Build and Test</h4><pre>build-and-test:<br>  name: Build and Test<br>  runs-on: ubuntu-latest<br><br>  steps:<br>  - name: Checkout repository<br>    uses: actions/checkout@v4<br><br>  - name: Set up JDK 17<br>    uses: actions/setup-java@v4<br>    with:<br>      java-version: &#39;17&#39;<br>      distribution: &#39;temurin&#39;<br>      cache: maven<br><br>  - name: Validate Maven project<br>      run: mvn validate<br>  <br>  - name: Static Code Analysis<br>    run: mvn checkstyle:check<br><br>  - name: Build with Maven<br>    run: mvn -B package -DskipTests<br><br>  - name: Run Unit Tests<br>    run: mvn test<br><br>  - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br>  <br>  - name: Build Docker image for testing<br>    run: docker build -t spring-boot-api:test .<br><br>  - name: Run API Tests with Testcontainers<br>    run: mvn verify -Dskip.unit.tests=true<br><br>  - name: Upload build artifact<br>    uses: actions/upload-artifact@v4<br>    with:<br>      name: app-jar<br>      path: target/*.jar<br>      retention-days: 1</pre><p>The first job in our pipeline focuses on validation. Before deploying to any environment, we need to confirm that our code is sound. This job runs on the latest Ubuntu runner and starts by checking out our code and setting up Java 17.</p><p>The subsequent steps progressively validate our code through multiple lenses:</p><ol><li>First, we validate the Maven project structure</li><li>Then, we run static code analysis to catch style and potential quality issues</li><li>Next, we build the application to verify it compiles correctly</li><li>Finally, we run unit tests to verify the code’s functional correctness</li></ol><p>Then we move to container-based testing. This sequence sets up Docker, builds a test image of our application, and runs API tests using Testcontainers. This is a critical step that verifies our application works correctly when containerised, exactly as it will be in our deployment environments.</p><p>Finally, we save the build artifact for later jobs in Upload Build Artifact. This step is essential for our deployment strategy. By preserving the exact same artifact throughout all environments, we reduce the likelihood of inconsistencies. This is a key advantage of trunk-based deployment with gates — the same validated build moves through all environments.</p><p><strong>Job 2: Deploy to Development</strong></p><pre>deploy-to-dev:<br>  name: Deploy to Development<br>  needs: build-and-test<br>  runs-on: ubuntu-latest<br>  if: github.ref == &#39;refs/heads/main&#39; &amp;&amp; (github.event_name == &#39;push&#39; || github.event_name == &#39;workflow_dispatch&#39;)<br>  environment: development<br>  env:<br>    ENVIRONMENT: dev<br>    PROJECT_ID: ${{ secrets.GCP_PROJECT_DEV }}<br>    SERVICE_NAME: spring-boot-api-dev<br>    REGION: us-central1<br><br>  steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br>  <br>    - name: Download build artifact<br>      uses: actions/download-artifact@v4<br>      with:<br>        name: app-jar<br>        path: target<br>  <br>    - name: Setup Cloud SDK<br>      uses: google-github-actions/setup-gcloud@v1<br>      with:<br>        project_id: ${{ env.PROJECT_ID }}<br>  <br>    - name: Authenticate to Google Cloud<br>      uses: google-github-actions/auth@v1<br>      with:<br>        credentials_json: ${{ secrets.GCP_SA_KEY_DEV }}<br>  <br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v3<br>  <br>    - name: Build and Push Docker image<br>      run: |<br>        # Configure Docker for Artifact Registry<br>        gcloud auth configure-docker ${{ env.REGION }}-docker.pkg.dev<br>        <br>        # Build with environment-specific Spring profile<br>        docker build \<br>          --build-arg SPRING_PROFILES_ACTIVE=${{ env.ENVIRONMENT }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }} \<br>          -t ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest .<br>          <br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br>        docker push ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:latest<br><br>    - name: Setup Terraform<br>    uses: hashicorp/setup-terraform@v2<br>    with:<br>      terraform_version: 1.5.0<br><br>    - name: Initialize Terraform<br>      run: |<br>        cd terraform/environments/dev<br>        terraform init<br>  <br>    - name: Apply Terraform<br>      run: |<br>        cd terraform/environments/dev<br>        terraform apply -auto-approve<br>      env:<br>        TF_VAR_project_id: ${{ env.PROJECT_ID }}<br>        TF_VAR_region: ${{ env.REGION }}<br>        TF_VAR_service_name: ${{ env.SERVICE_NAME }}<br>        TF_VAR_environment: ${{ env.ENVIRONMENT }}<br><br>    - name: Deploy to Cloud Run<br>    uses: google-github-actions/deploy-cloudrun@v1<br>    with:<br>      service: ${{ env.SERVICE_NAME }}<br>      region: ${{ env.REGION }}<br>      image: ${{ env.REGION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/spring-boot-api/${{ env.SERVICE_NAME }}:${{ github.sha }}<br><br>    - name: Smoke Test Development<br>      run: |<br>        export SERVICE_URL=$(gcloud run services describe ${{ env.SERVICE_NAME }} --region ${{ env.REGION }} --format &#39;value(status.url)&#39;)<br>        echo &quot;DEV Service URL: $SERVICE_URL&quot;<br>        <br>        # Wait for service to be fully deployed<br>        sleep 30<br>        <br>        # Test health endpoint<br>        HEALTH_STATUS=$(curl -s -o /dev/null -w &quot;%{http_code}&quot; $SERVICE_URL/actuator/health)<br>        if [ &quot;$HEALTH_STATUS&quot; != &quot;200&quot; ]; then<br>          echo &quot;Health check failed with status $HEALTH_STATUS&quot;<br>          exit 1<br>        fi<br>        <br>        # Test hello endpoint<br>        HELLO_RESPONSE=$(curl -s $SERVICE_URL/api/hello)<br>        if [[ &quot;$HELLO_RESPONSE&quot; != *&quot;Hello&quot;* ]]; then<br>          echo &quot;Hello endpoint check failed. Response: $HELLO_RESPONSE&quot;<br>          exit 1<br>        fi<br>        echo &quot;DEV deployment smoke test passed successfully!&quot;</pre><p>This job begins our deployment phase, starting with the development environment. Several key elements define this job’s purpose:</p><ol><li>The needs: build-and-test ensures this job only runs if the previous validation job succeeds</li><li>The conditional if statement restricts deployment to pushes to main or manual triggers</li><li>The environment: development line is crucial – it activates any protection rules configured for the development environment</li><li>Environment variables set context-specific values for this deployment</li></ol><p>Next, we prepare for deployment. These steps retrieve our configuration and the previously built artifact. We then set up the Google Cloud SDK and authenticate to our development GCP project. Notice we’re using environment-specific credentials — this enforces separation between environments at the cloud provider level.</p><p>Next comes the Docker image creation. This step builds our Docker image specifically for the development environment. Note the use of SPRING_PROFILES_ACTIVE=${{ env.ENVIRONMENT }} – this ensures our application runs with the development configuration. We then push this image to Google&#39;s Artifact Registry with both a version-specific tag (the Git commit SHA) and a latest tag.</p><p>The next section handles infrastructure provisioning. Using Terraform, we provision or update the required infrastructure in our development environment. This infrastructure-as-code approach ensures our cloud resources are consistently defined and can be recreated identically if needed. We use environment-specific Terraform configuration located in terraform/environments/dev.</p><p>Finally, we deploy the application and verify its health. The deployment step uses the <a href="https://cloud.google.com/run?hl=en">Google Cloud Run</a> action to deploy our container. The smoke test is crucial — it verifies our deployment is actually functional by checking endpoints. If either test fails, the pipeline stops, preventing progression to staging with a broken deployment.</p><p><strong>Job 3: Deploy to Staging</strong></p><p>The staging deployment job follows a similar pattern to development, but with two critical differences:</p><ol><li>It depends on successful deployment to development (needs: deploy-to-dev)</li><li>It uses the environment: staging specification</li></ol><p>This environment specification is where our deployment gate comes into play. In GitHub, you can configure the staging environment to require manual approval. When the workflow reaches this point, it pauses and waits for an authorised person to review and approve the deployment to staging.</p><p>The remaining steps mirror the development deployment but use staging-specific variables and secrets. This maintains environment isolation while using the same deployment procedure.</p><h4>Job 4: Deploy to Production</h4><p>The production deployment represents our final deployment gate. It depends on successful deployment to staging and specifies the production environment, which typically has the strictest approval requirements. Organisations often require multiple approvers and sometimes a waiting period before production deployments.</p><p>The steps for production deployment again mirror previous environments but use production-specific variables. In many organisations, production might have additional security measures or scaling configurations applied through the environment-specific Terraform configuration.</p><p>Take a moment to acknowledge that the last stage was a lot, well done for following so far!</p><h3>The Complete Deployment Flow — Summary</h3><p>Stepping back to see the full picture, our deployment flows through these stages:</p><ol><li>Code is merged or pushed to the main branch</li><li>The code is built and thoroughly tested</li><li>If tests pass, it’s automatically deployed to development</li><li>After review and approval, it’s deployed to staging</li><li>After additional review and approval, it’s deployed to production</li></ol><p>Each environment is deployed using the same artifact and process, but with environment-specific configurations. The gates between environments ensure appropriate oversight at each stage.</p><h3>Terraform: Infrastructure as Code — what is it?</h3><p>At its essence, Terraform enables you to treat your infrastructure configuration like software code. This means your entire GCP setup — including service accounts, Cloud Run instances, storage buckets, and cross-project permissions — is defined in text files with a clear syntax. These files can be:</p><ul><li><strong>Version controlled</strong> alongside your application code</li><li><strong>Reviewed</strong> through the same PR process as your application changes</li><li><strong>Tested</strong> before being applied to your environments</li><li><strong>Replicated</strong> consistently across environments</li></ul><h4>Why Terraform is Essential for Modern Cloud Deployments</h4><h4>Consistency and Reproducibility</h4><p>One of the most significant benefits of using Terraform is the guarantee of consistent environments. When you manually configure resources through the Google Cloud Console, subtle differences inevitably emerge between your Dev, Staging, and Production environments. These differences can lead to the dreaded “it works on my environment” problem.</p><p>With our Terraform configuration, we’ll define a single source of truth for all three environments. Any differences between Dev, Staging, and Production are intentional and explicitly documented in your code, not accidental byproducts of manual configuration.</p><h4>Documentation as Code</h4><p>Our Terraform files serve as living documentation of our infrastructure. New team members no longer need to piece together our architecture by navigating through the Google Cloud Console or relying on outdated wiki pages. Instead, they can examine your .tf files to understand:</p><ul><li>Which resources exist</li><li>How those resources are configured</li><li>How resources relate to one another</li><li>Which permissions are granted to which service accounts</li></ul><p>This self-documenting nature of IaC significantly reduces the onboarding time for new team members and helps maintain architectural knowledge even as team composition changes.</p><h4>Change Management and Auditability</h4><p>When you make changes to your infrastructure through Terraform:</p><ol><li>Terraform generates an execution plan showing exactly what will change</li><li>You can review these changes before applying them</li><li>All changes are recorded in your version control system</li><li>Changes can be rolled back by reverting to a previous version</li></ol><p>This process provides a robust audit trail that’s invaluable for compliance purposes and for debugging issues that arise after infrastructure changes.</p><h4>Scalability and Maintainability</h4><p>As our application grows, managing infrastructure manually becomes increasingly error-prone and time-consuming. With Terraform, scaling our infrastructure — whether that means adding more resources or replicating our setup in new regions — becomes a matter of modifying your code rather than clicking through console interfaces.</p><p>This approach aligns perfectly with modern DevOps practices and complements our CI/CD pipeline to create a robust, automated deployment process for our applications.</p><p>Enough theory, lets start defining our Terraform code!</p><h3>Setting Up Terraform as Infrastructure as Code</h3><p>Terraform allows us to define our infrastructure as code, making it versioned, reproducible, and automated. Our Terraform structure supports multi-environment deployments. I.e. development , staging , and production .</p><h4>Step 1: Create the Terraform Directory Structure</h4><p>First, we’ll need to create the necessary directories for our modular Terraform setup. Run the following code in your terminal from your project root in order to create new directories that will store our Terraform code:</p><pre>mkdir -p terraform/modules/spring-boot-api<br>mkdir -p terraform/environments/dev<br>mkdir -p terraform/environments/staging<br>mkdir -p terraform/environments/prod</pre><h4>Step 2: Create the Reusable Module</h4><p>The module will contain the core infrastructure components that are common across all environments. Let’s create the necessary files:</p><h4>Module Main File (terraform/modules/spring-boot-api/main.tf)</h4><pre>resource &quot;google_project_service&quot; &quot;run_api&quot; {<br>  project            = var.project_id<br>  service            = &quot;run.googleapis.com&quot;<br>  disable_on_destroy = false<br>}<br><br>resource &quot;google_project_service&quot; &quot;artifactregistry_api&quot; {<br>  project            = var.project_id<br>  service            = &quot;artifactregistry.googleapis.com&quot;<br>  disable_on_destroy = false<br>}<br><br># Create service account for Cloud Run<br>resource &quot;google_service_account&quot; &quot;cloud_run_service_account&quot; {<br>  project      = var.project_id<br>  account_id   = &quot;${var.service_name}-sa&quot;<br>  display_name = &quot;Service Account for ${var.service_name}&quot;<br>}<br><br># Grant necessary permissions to service account<br>resource &quot;google_project_iam_member&quot; &quot;cloud_run_invoker&quot; {<br>  project = var.project_id<br>  role    = &quot;roles/run.invoker&quot;<br>  member  = &quot;serviceAccount:${google_service_account.cloud_run_service_account.email}&quot;<br>}<br><br># Cloud Run service<br>resource &quot;google_cloud_run_service&quot; &quot;spring_boot_api&quot; {<br>  name     = var.service_name<br>  location = var.region<br>  project  = var.project_id<br><br>  template {<br>    spec {<br>      containers {<br>        image = &quot;${var.region}-docker.pkg.dev/${var.project_id}/spring-boot-api/${var.service_name}:latest&quot;<br>        <br>        resources {<br>          limits = {<br>            cpu    = var.cpu<br>            memory = var.memory<br>          }<br>        }<br>        <br>        env {<br>          name  = &quot;SPRING_PROFILES_ACTIVE&quot;<br>          value = var.environment<br>        }<br>        <br>        # Environment-specific env variables<br>        dynamic &quot;env&quot; {<br>          for_each = var.env_variables<br>          content {<br>            name  = env.key<br>            value = env.value<br>          }<br>        }<br>      }<br>      service_account_name = google_service_account.cloud_run_service_account.email<br>    }<br>  }<br><br>  traffic {<br>    percent         = 100<br>    latest_revision = true<br>  }<br><br>  depends_on = [<br>    google_project_service.run_api<br>  ]<br><br>  autogenerate_revision_name = true<br>}<br><br># Make the Cloud Run service publicly accessible<br>resource &quot;google_cloud_run_service_iam_member&quot; &quot;public_access&quot; {<br>  project  = var.project_id<br>  service  = google_cloud_run_service.spring_boot_api.name<br>  location = google_cloud_run_service.spring_boot_api.location<br>  role     = &quot;roles/run.invoker&quot;<br>  member   = &quot;allUsers&quot;<br>}</pre><p>This file is a reusable Terraform module that defines the core infrastructure for deploying our Spring Boot API to Google Cloud Run. It serves as the central infrastructure definition that is referenced by each environment-specific configuration (dev/staging/prod). Here’s what it does:</p><ol><li>Enables the required GCP APIs for our project the Cloud Run API and the Artifact Registry API.</li><li>Creates service account infrastructure. A dedicated service account for Cloud Run and grants it the necessary “run.invoker” role.</li><li>Defines the Cloud Run Service. Configures the service with environment-specific parameters (passed from the environment modules). Sets up container specifications including the Image reference from Artifact Registry, resource limits (CPU and memory) that can vary per environment. Environment variables including Spring profiles and custom variables. Associates the service with the created service account and sets traffic routing to the latest revision</li><li>Configures public access by granting the “run.invoker” role to “allUsers”</li></ol><p>By doing so we are creating reusable, parameterised modules that can be called with environment-specific values. For example, we will define a terraform/environments/dev/main.tf file that calls this module passing in dev environment specific parameters, allowing us maintain consistent infrastructure with appropriate variations across environments (Dev/Staging/Prod).</p><h4>Module Variables (terraform/modules/spring-boot-api/variables.tf)</h4><p>This file defines all the input variables that the Spring Boot API Terraform module accepts, allowing each environment (dev/staging/prod) to pass in different values when calling the module:</p><pre>variable &quot;project_id&quot; {<br>  description = &quot;The ID of the GCP project&quot;<br>  type        = string<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The region to deploy resources to&quot;<br>  type        = string<br>}<br><br>variable &quot;service_name&quot; {<br>  description = &quot;The name of the Cloud Run service&quot;<br>  type        = string<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;The deployment environment (dev, staging, prod)&quot;<br>  type        = string<br>}<br><br>variable &quot;cpu&quot; {<br>  description = &quot;CPU allocation for Cloud Run service&quot;<br>  type        = string<br>  default     = &quot;1&quot;<br>}<br><br>variable &quot;memory&quot; {<br>  description = &quot;Memory allocation for Cloud Run service&quot;<br>  type        = string<br>  default     = &quot;512Mi&quot;<br>}<br><br>variable &quot;env_variables&quot; {<br>  description = &quot;Environment variables to pass to the container&quot;<br>  type        = map(string)<br>  default     = {}<br>}</pre><h4>Module Outputs (terraform/modules/spring-boot-api/outputs.tf)</h4><p>This file defines the values that the Spring Boot API Terraform module exposes after deployment, making critical information available to the calling environment modules (dev/staging/prod). It exports three key pieces of information: the deployed service’s URL (which is referenced in the environment-specific outputs), the service name, and the service account email. These outputs enable other parts of our infrastructure to reference and interact with the deployed Cloud Run service, supporting our multi-environment deployment pipeline by providing consistent access to deployment results across all environments:</p><pre>output &quot;service_url&quot; {<br>  value = google_cloud_run_service.spring_boot_api.status[0].url<br>}<br><br>output &quot;service_name&quot; {<br>  value = google_cloud_run_service.spring_boot_api.name<br>}<br><br>output &quot;service_account_email&quot; {<br>  value = google_service_account.cloud_run_service_account.email<br>}</pre><h4>Step 3: Create Environment-Specific Configurations</h4><p>Now, create the configuration for each environment, starting with development:</p><h4>Development Environment (terraform/environments/dev/main.tf)</h4><pre>module &quot;spring_boot_api&quot; {<br>  source = &quot;../../modules/spring-boot-api&quot;<br><br>  project_id  = var.project_id<br>  region      = var.region<br>  service_name = var.service_name<br>  environment = var.environment<br>  <br>  # Dev-specific resource allocations<br>  cpu    = &quot;1&quot;<br>  memory = &quot;512Mi&quot;<br>  <br>  # Dev-specific environment variables<br>  env_variables = {<br>    LOG_LEVEL = &quot;DEBUG&quot;<br>    # Add other dev-specific variables here<br>  }<br>}<br><br>output &quot;service_url&quot; {<br>  value = module.spring_boot_api.service_url<br>}</pre><p>This file is the first environment specific configuration file, in this case for our development environment. It instantiates the reusable Spring Boot API module with development-specific parameters, including reduced resource allocations (1 CPU, 512Mi memory) and development-specific environment variables like DEBUG logging.</p><h4>Development Variables (terraform/environments/dev/variables.tf)</h4><pre>variable &quot;project_id&quot; {<br>  description = &quot;The ID of the GCP project&quot;<br>  type        = string<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The region to deploy resources to&quot;<br>  type        = string<br>  default     = &quot;us-central1&quot;<br>}<br><br>variable &quot;service_name&quot; {<br>  description = &quot;The name of the Cloud Run service&quot;<br>  type        = string<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;The deployment environment (dev, staging, prod)&quot;<br>  type        = string<br>  default     = &quot;dev&quot;<br>}</pre><p>This variables file declares the mandatory variables needed for the development environment deployment, including the GCP project ID, region (defaulting to us-central1), service name, and environment type (with a default value of “dev”). These variables are passed to the Spring Boot API module when it’s called from the development environment’s main.tf file, allowing for environment-specific customisation while maintaining a consistent infrastructure pattern across our three-environment deployment pipeline.</p><h4>Development Backend Configuration (terraform/environments/dev/backend.tf)</h4><pre>terraform {<br>  backend &quot;gcs&quot; {<br>    bucket = &quot;tf-automation-demo-state-spring-boot-api&quot;<br>    prefix = &quot;terraform/state/dev&quot;<br>  }<br>}</pre><p>This file defines where and how Terraform stores its state for the development environment, specifically using a Google Cloud Storage (GCS) bucket named tf-automation-demo-state-spring-boot-apiwith the environment-specific prefix “terraform/state/dev”.</p><p><em>(We’ll cover the creation of this bucket later in this post at the “Create a Cloud Storage Bucket for Terraform State” section)</em></p><h4>Step 4: Repeat for Staging and Production</h4><p>We create similar files for staging and production environments, adjusting values as needed. For example, production might have higher resource allocations or additional security measures.</p><h4>Staging Environment (terraform/environments/staging/main.tf)</h4><pre>module &quot;spring_boot_api&quot; {<br>  source = &quot;../../modules/spring-boot-api&quot;<br><br>  project_id  = var.project_id<br>  region      = var.region<br>  service_name = var.service_name<br>  environment = var.environment<br>  <br>  # Staging-specific resource allocations<br>  cpu    = &quot;1&quot;<br>  memory = &quot;768Mi&quot;<br>  <br>  # Staging-specific environment variables<br>  env_variables = {<br>    LOG_LEVEL = &quot;INFO&quot;<br>    # Add other staging-specific variables here<br>  }<br>}<br><br>output &quot;service_url&quot; {<br>  value = module.spring_boot_api.service_url<br>}</pre><h4>(terraform/environments/staging/variables.tf)</h4><pre>variable &quot;project_id&quot; {<br>  description = &quot;The ID of the GCP project&quot;<br>  type        = string<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The region to deploy resources to&quot;<br>  type        = string<br>  default     = &quot;us-central1&quot;<br>}<br><br>variable &quot;service_name&quot; {<br>  description = &quot;The name of the Cloud Run service&quot;<br>  type        = string<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;The deployment environment (dev, staging, prod)&quot;<br>  type        = string<br>  default     = &quot;staging&quot;<br>}</pre><h4>(terraform/environments/staging/backend.tf)</h4><pre>terraform {<br>  backend &quot;gcs&quot; {<br>    bucket = &quot;tf-automation-demo-state-spring-boot-api&quot;<br>    prefix = &quot;terraform/state/staging&quot;<br>  }<br>}</pre><h4>Production Environment (terraform/environments/prod/main.tf)</h4><pre>module &quot;spring_boot_api&quot; {<br>  source = &quot;../../modules/spring-boot-api&quot;<br><br>  project_id  = var.project_id<br>  region      = var.region<br>  service_name = var.service_name<br>  environment = var.environment<br>  <br>  # Production-specific resource allocations<br>  cpu    = &quot;2&quot;<br>  memory = &quot;1Gi&quot;<br>  <br>  # Production-specific environment variables<br>  env_variables = {<br>    LOG_LEVEL = &quot;WARN&quot;<br>    # Add other production-specific variables here<br>  }<br>}<br><br># You might add additional production-specific resources here<br># For example, monitoring, alerts, or additional security measures<br><br>output &quot;service_url&quot; {<br>  value = module.spring_boot_api.service_url<br>}</pre><h4>(terraform/environments/prod/variables.tf)</h4><pre>variable &quot;project_id&quot; {<br>  description = &quot;The ID of the GCP project&quot;<br>  type        = string<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The region to deploy resources to&quot;<br>  type        = string<br>  default     = &quot;us-central1&quot;<br>}<br><br>variable &quot;service_name&quot; {<br>  description = &quot;The name of the Cloud Run service&quot;<br>  type        = string<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;The deployment environment (dev, staging, prod)&quot;<br>  type        = string<br>  default     = &quot;prod&quot;<br>}</pre><h4>(terraform/environments/prod/backend.tf)</h4><pre>terraform {<br>  backend &quot;gcs&quot; {<br>    bucket = &quot;tf-automation-demo-state-spring-boot-api&quot;<br>    prefix = &quot;terraform/state/prod&quot;<br>  }<br>}</pre><h3>Setting Up GCP Projects for Deployment</h3><p>Before we can use our CI/CD pipeline, we need to set up some resources in GCP:</p><h4>1. Create x3 GCP Projects (one for each environment)</h4><p>This approach will give us proper isolation between environments and follow cloud best practices.</p><p>First, let’s create our three projects. You can do this through the Google Cloud Console:</p><ol><li>Go to <a href="https://console.cloud.google.com/">Google Cloud Console</a></li><li>Click on the project dropdown at the top of the page</li><li>Click “New Project”</li><li>Create three separate projects with descriptive names:</li></ol><ul><li>automation-demo-dev (for development)</li><li>automation-demo-staging (for staging)</li><li>automation-demo-prod (for production)</li></ul><p>When creating these projects, take note of the project IDs, as they might differ slightly from the names you choose</p><p>This gives us an isolated environment for our application, with its own billing, resources, and permissions.</p><h3>Creating a Service Accounts for GitHub Actions with Infrastructure as Code.</h3><p>Next, we will create service accounts that GitHub Actions will use to interact with GCP. We create separate service accounts for each environment (dev, staging, and production).</p><p>In a multi-environment setup, isolation between environments is crucial. If you used a single service account with access to all environments, a misconfiguration in your pipeline could potentially affect your production environment during a development deployment.</p><p>By creating environment-specific service accounts, you establish strong security boundaries. The development pipeline can only affect development resources, the staging pipeline can only affect staging resources, and so on.</p><p>We could create each of these manually via the Google Cloud Web Console, however, we strive to have all configuration and infrastructure captured in code and safely available within source control. This will help mitigate any accidental deletion/amendments of our Service Accounts in the Web Console and provides us the ability to completely re-provision our entire estate via code.</p><p>Let’s start by creating a reusable module in Terraform and then showing how to apply it to each environment.</p><h4>Create the Service Account Module</h4><p>Create a new main.tf file within our terraform modules directoryterraform/modules/github-actions-sa/ . This is a resuable Terraform module that defines the infrastructure for a single GitHub Actions service account in a GCP project. We will call this module 3 times via a Service-Account root Terraform module that orchestrates the creation of our service accounts for each environment, dev, staging and prod.</p><pre><br># Enable required APIs<br>resource &quot;google_service_account&quot; &quot;github_actions&quot; {<br>  project      = var.project_id<br>  account_id   = var.service_account_id<br>  display_name = &quot;GitHub Actions Service Account for ${var.environment}&quot;<br>  description  = &quot;Service account used by GitHub Actions to deploy to ${var.environment}&quot;<br>}<br><br># Enable Service Usage API first using terraform-provider-google-beta<br># This is required before we can enable other APIs<br>resource &quot;google_project_service&quot; &quot;enable_service_usage&quot; {<br>  project = var.project_id<br>  service = &quot;serviceusage.googleapis.com&quot;<br>  <br>  # Do not disable the API on destroy<br>  disable_on_destroy = false<br>  <br>  # Skip the initial check for API enablement<br>  # This is necessary since we&#39;re enabling the API that would perform the check<br>  provisioner &quot;local-exec&quot; {<br>    command = &quot;sleep 60&quot;<br>  }<br>}<br><br># First, assign the Service Usage Admin role<br>resource &quot;google_project_iam_member&quot; &quot;service_usage_admin&quot; {<br>  depends_on = [google_project_service.enable_service_usage]<br>  <br>  project = var.project_id<br>  role    = &quot;roles/serviceusage.serviceUsageAdmin&quot;<br>  member  = &quot;serviceAccount:${google_service_account.github_actions.email}&quot;<br>}<br><br># Then enable required APIs<br>resource &quot;google_project_service&quot; &quot;required_apis&quot; {<br>  depends_on = [<br>    google_project_iam_member.service_usage_admin,<br>    google_project_service.enable_service_usage<br>  ]<br>  <br>  for_each = toset([<br>    &quot;artifactregistry.googleapis.com&quot;,<br>    &quot;run.googleapis.com&quot;,<br>    &quot;iam.googleapis.com&quot;,<br>    &quot;cloudresourcemanager.googleapis.com&quot;<br>  ])<br>  <br>  project = var.project_id<br>  service = each.value<br>  <br>  disable_dependent_services = false<br>  disable_on_destroy        = false<br>}<br><br># Create Artifact Registry Repository<br>resource &quot;google_artifact_registry_repository&quot; &quot;app_repository&quot; {<br>  depends_on = [google_project_service.required_apis]<br>  <br>  project       = var.project_id<br>  location      = var.region<br>  repository_id = &quot;spring-boot-api&quot;<br>  description   = &quot;Docker repository for Spring Boot API&quot;<br>  format        = &quot;DOCKER&quot;<br>}<br><br># Assign remaining required roles<br>resource &quot;google_project_iam_member&quot; &quot;service_account_roles&quot; {<br>  depends_on = [google_project_service.required_apis]<br>  <br>  for_each = toset([<br>    &quot;roles/run.admin&quot;,                # Manage Cloud Run services<br>    &quot;roles/artifactregistry.writer&quot;,  # Push to Artifact Registry<br>    &quot;roles/storage.admin&quot;,            # Full access to GCS (for Terraform state)<br>    &quot;roles/iam.serviceAccountUser&quot;,   # Use service accounts<br>    &quot;roles/iam.serviceAccountAdmin&quot;,  # Create and manage service accounts<br>    &quot;roles/resourcemanager.projectIamAdmin&quot;  # Manage project IAM bindings<br>  ])<br>  <br>  project = var.project_id<br>  role    = each.value<br>  member  = &quot;serviceAccount:${google_service_account.github_actions.email}&quot;<br>}<br><br># Additional environment-specific roles<br>resource &quot;google_project_iam_member&quot; &quot;environment_specific_roles&quot; {<br>  depends_on = [google_project_service.required_apis]<br>  <br>  for_each = var.environment == &quot;production&quot; ? toset([<br>    &quot;roles/monitoring.viewer&quot;,    # View monitoring in production<br>    &quot;roles/logging.viewer&quot;        # View logs in production<br>  ]) : toset([])<br>  <br>  project = var.project_id<br>  role    = each.value<br>  member  = &quot;serviceAccount:${google_service_account.github_actions.email}&quot;<br>}<br><br># Create a service account key<br>resource &quot;google_service_account_key&quot; &quot;github_actions_key&quot; {<br>  service_account_id = google_service_account.github_actions.name<br>  public_key_type    = &quot;TYPE_X509_PEM_FILE&quot;<br>}</pre><p>This Terraform module creates environment-specific GitHub Actions service accounts with all necessary permissions for our three-environment deployment pipeline (dev/staging/prod). It enables required Google Cloud APIs (including Service Usage, Artifact Registry, Cloud Run, IAM, and Cloud Resource Manager), creates an Artifact Registry repository for our Docker images, and assigns the precise set of IAM roles needed for deployment (run.admin, artifactregistry.writer, storage.admin, iam.serviceAccountUser, and resourcemanager.projectIamAdmin).</p><p>The module also generates service account keys for GitHub Secrets and applies additional monitoring permissions specifically for production, following the principle of least privilege while ensuring your CI/CD pipeline has all necessary permissions to deploy your Spring Boot API across all environments.</p><p>Now let’s create the variables file for this module in the new file terraform/modules/github-actions-sa/variables.tf :</p><pre><br>variable &quot;project_id&quot; {<br>  description = &quot;The GCP project ID where the service account will be created&quot;<br>  type        = string<br>}<br><br>variable &quot;environment&quot; {<br>  description = &quot;The environment (development, staging, production)&quot;<br>  type        = string<br>  <br>  validation {<br>    condition     = contains([&quot;development&quot;, &quot;staging&quot;, &quot;production&quot;], var.environment)<br>    error_message = &quot;Environment must be one of: development, staging, production&quot;<br>  }<br>}<br><br>variable &quot;service_account_id&quot; {<br>  description = &quot;The ID to use for the service account&quot;<br>  type        = string<br>  default     = &quot;github-actions-sa&quot;<br>}<br><br>variable &quot;region&quot; {<br>  description = &quot;The region where resources will be created&quot;<br>  type        = string<br>  default     = &quot;us-central1&quot;<br>}</pre><p>This file declares the variables required by the GitHub Actions service account module, establishing the interface for environment-specific configurations across our three-environment deployment pipeline. It defines four key parameters: the GCP project ID where resources will be created, the deployment environment (with validation to ensure it’s one of “development”, “staging”, or “production”), the service account ID (defaulting to “github-actions-sa”), and the region for resource creation (defaulting to “us-central1”). These variables enable the module to be reused across our dev/staging/prod environments while enforcing consistency and allowing for environment-specific customisation.</p><p>And finally, the outputs file to expose important values, terraform/modules/github-actions-sa/outputs.tf :</p><pre>output &quot;email&quot; {<br>  description = &quot;The email address of the service account&quot;<br>  value       = google_service_account.github_actions.email<br>}<br><br>output &quot;key&quot; {<br>  description = &quot;The base64 encoded service account key&quot;<br>  value       = google_service_account_key.github_actions_key.private_key<br>  sensitive   = true<br>}<br><br>output &quot;artifact_registry_repository&quot; {<br>  description = &quot;The Artifact Registry repository details&quot;<br>  value = {<br>    name     = google_artifact_registry_repository.app_repository.name<br>    location = google_artifact_registry_repository.app_repository.location<br>  }<br>}</pre><p>This file specifies three critical outputs from the GitHub Actions service account module that are essential for our CI/CD pipeline: the service account email address for reference in IAM policies, the base64-encoded service account key (marked as sensitive to prevent accidental exposure in logs) which needs to be added to our GitHub repository secrets, and the Artifact Registry repository details for Docker image storage. These outputs align with our project’s requirements for GitHub Secrets (GCP_SA_KEY_DEV, GCP_SA_KEY_STAGING, GCP_SA_KEY_PROD) that we will configure next to allow our pipeline to deploy to our GCP environments.</p><h4>Create a Cloud Storage Bucket for Terraform State</h4><p>Despite having our infrastructure defined as code with Terraform, we still need a persistent place to store Terraform’s state information. This is a critical component that many newcomers to Terraform overlook. Let’s create one in our development project. (You may want to do this in your production project if it contains more stringent security in a real world scenario)</p><p>Terraform state is a JSON file that maps the resources defined in your configuration files to the real-world resources they represent in your cloud provider. When you run Terraform commands like terraform plan or terraform apply, Terraform compares the desired state (from your configuration files) with the current state (stored in the state file) to determine what changes need to be made.</p><ul><li><strong>Resource Tracking</strong>: It tracks all resources Terraform has created, enabling it to know what it’s responsible for managing.</li><li><strong>Metadata Storage</strong>: It stores metadata about your resources that isn’t available from the API, such as resource dependencies.</li><li><strong>Performance Optimisation</strong>: It caches resource attributes to improve performance for large infrastructures.</li><li><strong>Concurrency Control</strong>: When using a remote backend like Google Cloud Storage, it enables locking to prevent multiple users from modifying infrastructure simultaneously.</li></ul><p>Let’s create this bucket using the Cloud Shell in GCP:</p><ol><li>Go to the <a href="https://console.cloud.google.com/">GCP web console</a> and navigate to your production project</li><li>Click on the Cloud Shell icon (&gt;_) in the top-right corner of the page, which opens a terminal at the bottom of the screen</li><li>Wait for the Cloud Shell to initialise (this might take a few moments the first time)</li><li>Once ready, run the following command to create the bucket (note that buckets must have a globally unique name, so you’ll need to name yours personally to achieve this):</li></ol><pre>gsutil mb -l us-central1 gs://tf-automation-demo-state-spring-boot-api</pre><p>The Cloud Shell comes pre-installed with all the Google Cloud tools you need, including gsutil for interacting with Cloud Storage. This command creates a new bucket named tf-automation-demo-state-spring-boot-api in the us-central1 region.</p><p>If you need to enable versioning on your bucket for additional protection against state corruption or accidental deletions, you can run:</p><pre>gsutil versioning set on gs://tf-automation-demo-state-spring-boot-api</pre><p>This ensures that even if the state file is accidentally modified or deleted, you can recover a previous version.</p><p>Using Cloud Shell is convenient because:</p><ul><li>You don’t need to install any software on your local machine</li><li>Authentication is handled automatically</li><li>It provides a consistent environment regardless of your local setup</li><li>It has fast network connectivity to GCP services</li></ul><p>With our state bucket created, Terraform can now safely store and manage its state remotely, enabling collaboration and providing a backup of our infrastructure configuration.</p><p>We will reference this bucket within our Terraform module for setting up our service accounts in our environments later in this post.</p><h4>Create a Separate Terraform Configuration for Service Accounts</h4><p>To keep service account management separate from our application infrastructure, let’s create a dedicated Terraform configuration. Create the new directory and file terraform/service-accounts/main.tf :</p><pre><br><br>provider &quot;google&quot; {<br>  # No default project specified here, as we&#39;ll define different projects for each environment<br>}<br><br># Service account for development environment<br>module &quot;github_actions_dev&quot; {<br>  source = &quot;../modules/github-actions-sa&quot;<br>  <br>  project_id        = var.dev_project_id<br>  environment       = &quot;development&quot;<br>  service_account_id = &quot;github-actions-sa&quot;<br>}<br><br># Service account for staging environment<br>module &quot;github_actions_staging&quot; {<br>  source = &quot;../modules/github-actions-sa&quot;<br>  <br>  project_id        = var.staging_project_id<br>  environment       = &quot;staging&quot;<br>  service_account_id = &quot;github-actions-sa&quot;<br>}<br><br># Service account for production environment<br>module &quot;github_actions_prod&quot; {<br>  source = &quot;../modules/github-actions-sa&quot;<br>  <br>  project_id        = var.prod_project_id<br>  environment       = &quot;production&quot;<br>  service_account_id = &quot;github-actions-sa&quot;<br>}<br><br># Output the keys (these will be sensitive)<br>output &quot;dev_service_account_key&quot; {<br>  value     = module.github_actions_dev.key<br>  sensitive = true<br>}<br><br>output &quot;staging_service_account_key&quot; {<br>  value     = module.github_actions_staging.key<br>  sensitive = true<br>}<br><br>output &quot;prod_service_account_key&quot; {<br>  value     = module.github_actions_prod.key<br>  sensitive = true<br>}</pre><p>The terraform/service-accounts/main.tf file orchestrates the creation of GitHub Actions service accounts across all three environments (development, staging, and production) by instantiating the reusable github-actions-sa module for each environment and exposing the resulting service account keys as sensitive outputs that will be used as GitHub Secrets for ourCI/CD pipeline.</p><p>Let’s also create the variables file, terraform/service-accounts/variables.tf :</p><pre>variable &quot;dev_project_id&quot; {<br>  description = &quot;The GCP project ID for development environment&quot;<br>  type        = string<br>}<br><br>variable &quot;staging_project_id&quot; {<br>  description = &quot;The GCP project ID for staging environment&quot;<br>  type        = string<br>}<br><br>variable &quot;prod_project_id&quot; {<br>  description = &quot;The GCP project ID for production environment&quot;<br>  type        = string<br>}</pre><p>The terraform/service-accounts/variables.tf file defines the three project ID variables (dev_project_id, staging_project_id, and prod_project_id) that are required by the service accounts root module to create environment-specific service accounts across our three-environment deployment pipeline, serving as the input interface for the centralised service account management configuration.</p><p>We also create a terraform/service-account/backend.tf file:</p><pre>terraform {<br>  backend &quot;gcs&quot; {<br>    bucket = &quot;tf-automation-demo-state-spring-boot-api&quot;<br>    prefix = &quot;terraform/service-accounts&quot;<br>  }<br>}</pre><p>The terraform/service-accounts/backend.tf file configures the remote state storage for the service accounts root module, specifying that Terraform should store its state in the Google Cloud Storage bucket that we define earlier, tf-automation-demo-state-spring-boot-apiunder the prefix &quot;terraform/service-accounts&quot;, ensuring that the service account infrastructure state is stored separately from the environment-specific states while still using the same centralised bucket for state management across our multi-environment deployment pipeline.</p><p>And now we create a sample for better readability in our project terraform/service-accounts/terraform.tfvarsfile:</p><pre><br>dev_project_id  = &quot;automation-demo-dev&quot;<br>staging_project_id  = &quot;automation-demo-staging&quot;<br>prod_project_id  = &quot;automation-demo-prod&quot;<br>region            = &quot;us-central1&quot;     </pre><p>In each instance in this file, replace the value with the actual GCP project ID, you can find these via the GCP Web Console.</p><p>Note: earlier in this post we created a .gitignore file that included Terraform omissions from our version control, this *.tfvars file is one such file.</p><h4>Apply the Terraform Configuration</h4><p>Now it’s time to apply our configuration to have Terraform create our Service accounts consistently for each environment. This is something we do once for our project and won’t be applied each time our CI/CD pipeline is executed. However, it means that if our Service Accounts within GCP were ever accidentally deleted or amended, we can consistently and easily recreate them again:</p><pre>cd terraform/service-accounts<br>terraform init<br>terraform plan<br>terraform apply</pre><h4>Add GitHub Secrets</h4><p>Now, we need to add the necessary secrets to your GitHub repository:</p><ol><li>Go to your GitHub repository</li><li>Click on “Settings” &gt; “Secrets and variables” &gt; “Actions”</li><li>Click “New repository secret”</li><li>Add the following secrets:</li></ol><ul><li>GCP_PROJECT_DEV: The GCP project ID for development</li><li>GCP_PROJECT_STAGING: The GCP project ID for staging</li><li>GCP_PROJECT_PROD: The GCP project ID for production</li><li>GCP_SA_KEY_DEV: The service account key for the development project. You can obtain this via running the following in our terminal. It will generate a dev_key.json file in your terraform/service-accounts/ directory</li></ul><pre>terraform output -raw dev_service_account_key &gt; dev_key.json</pre><ul><li>GCP_SA_KEY_STAGING: The service account key for the staging project. The service account key for the staging project. You can obtain this via running the following in our terminal. It will generate a staging_key.jsonfile in your terraform/service-accounts/ directory</li></ul><pre>terraform output -raw staging_service_account_key &gt; staging_key.json</pre><ul><li>GCP_SA_KEY_PROD: The service account key for the staging project. The service account key for the production project. You can obtain this via running the following in our terminal. It will generate a prod_key.jsonfile in your terraform/service-accounts/ directory</li></ul><pre>terraform output -raw prod_service_account_key &gt; prod_key.json</pre><p>GitHub Secrets provide a secure way to store sensitive information like API keys and credentials, making them available to our workflows without exposing them in our code. This is a critical security practice, as it ensures that sensitive credentials are not visible in our repository history or logs.</p><p>After adding these secrets, make sure you delete the local key files to maintain security:</p><pre>rm dev_key.json staging_key.json prod_key.json</pre><h4>Making your Bucket that contains Terraform State accessible across projects</h4><p>In order to adhere to cloud best practices we created three separate GCP projects, one for development, one for staging and finally another for production.</p><p>When our CI/CD pipeline runs, we purposefully want to re-use the same assets across all of our environments, for consistency and efficiency.</p><p>This poses as a slight problem we need to address as by default our staging and production service accounts are not able to access the Cloud Storage Bucket we store our Terraform state tf-automation-demo-state-spring-boot-api in as it’s in our Dev GCP project.</p><p>We can resolve this by adding this following cross-project-permissions.tf file in our terraform/service-accounts directory:</p><pre># Grant cross-project permissions to the Terraform state bucket<br><br># Reference to the bucket in the dev project<br>data &quot;google_storage_bucket&quot; &quot;terraform_state&quot; {<br>  name    = &quot;tf-automation-demo-state-spring-boot-api&quot;<br>  project = var.dev_project_id<br>}<br><br># Grant the staging service account access to the bucket<br>resource &quot;google_storage_bucket_iam_member&quot; &quot;staging_bucket_access&quot; {<br>  bucket = data.google_storage_bucket.terraform_state.name<br>  role   = &quot;roles/storage.admin&quot;<br>  member = &quot;serviceAccount:github-actions-sa@${var.staging_project_id}.iam.gserviceaccount.com&quot;<br>}<br><br># Grant the production service account access to the bucket<br>resource &quot;google_storage_bucket_iam_member&quot; &quot;prod_bucket_access&quot; {<br>  bucket = data.google_storage_bucket.terraform_state.name<br>  role   = &quot;roles/storage.admin&quot;<br>  member = &quot;serviceAccount:github-actions-sa@${var.prod_project_id}.iam.gserviceaccount.com&quot;<br>}</pre><p>Once you have created this, you will need to navigate to the terraform/service-accounts directory and apply the changes in Terraform:</p><pre>cd terraform/service-accounts<br>terraform init<br>terraform apply</pre><h3>Initial Environment Setup</h3><p>You need to manually run the Terraform for each environment once to set up the initial infrastructure:</p><pre># Initialize and apply development environment<br>cd terraform/environments/dev<br>terraform init<br>terraform apply<br><br># Repeat for staging and production<br>cd ../staging<br>terraform init<br>terraform apply<br><br>cd ../prod<br>terraform init<br>terraform apply</pre><h3>Updating Our Spring Boot Application for Production</h3><p>Let’s make a few adjustments to ensure our Spring Boot application is ready for production deployment in GCP Cloud Run.</p><p>First, let’s update our application.properties to support different environments. Create a new file named application-prod.properties located at src/main/resources/ within your Spring Project:</p><pre># Production environment settings<br>server.port=${PORT:8080}<br><br># Actuator endpoints<br>management.endpoints.web.exposure.include=health,info<br>management.endpoint.health.show-details=always<br><br># Application info<br>info.app.name=Spring Boot Test Automation API<br>info.app.description=Spring Boot REST API for test automation demo<br>info.app.version=1.0.0<br>info.app.environment=production<br><br># Logging<br>logging.level.root=INFO<br>logging.level.org.springframework=INFO<br>logging.level.com.example=INFO<br><br># This is important for Cloud Run to know when your app is ready<br>server.shutdown=graceful<br>spring.lifecycle.timeout-per-shutdown-phase=20s</pre><p>This production-specific configuration file contains settings optimised for our Cloud Run environment. The most important setting is server.port=${PORT:8080}, which configures our application to listen on the port provided by Cloud Run through the PORT environment variable (defaulting to 8080 if not specified).</p><p>We’ve also configured Actuator to expose only the health and info endpoints, which is a security best practice for production environments. The detailed health information will help us diagnose issues, while the application info provides useful metadata about our deployed application.</p><p>Finally, we’ve set appropriate logging levels to ensure we have enough information for monitoring without overwhelming our logs with debug information.</p><h3>Putting It All Together: Testing the CI/CD Pipeline</h3><p>Now that we have set up all the necessary components, let’s commit our changes and push them to GitHub to trigger our CI/CD pipeline:</p><pre>git add .<br>git commit -m &quot;Add CI/CD pipeline with GitHub Actions and Terraform&quot;<br>git push origin main</pre><p>After pushing, go to the “Actions” tab in your GitHub repository to monitor the progress of your workflow. If everything is set up correctly, you should see your workflow running through the stages:</p><ol><li>Building and testing the application</li><li>Planning the Terraform infrastructure</li><li>Deploying to Google Cloud Run</li></ol><p>Once the workflow completes successfully, you can access our deployed application at the URL provided in the Terraform output. This URL will be displayed in the logs of your GitHub Actions workflow, or you can find it in the GCP Console under Cloud Run.</p><p>Once our pipeline has successfully deployed to our Dev environment, we reach our first gate. Within GitHub Actions we will be prompted to manually ‘Review deployments’ to staging before the pipeline will proceed to deploy our Spring Boot service to our Staging environment as we desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FecGZhPjCWw9drQBmwVjSA.png" /><figcaption>Staging gate in GitHub</figcaption></figure><p>You are able to configure GitHub to send email/Slack notifications to reviewers to alert them to the fact that there are reviews pending of a deployment. Handy in a collaborative setting.</p><h3>Verifying Our Deployment</h3><p>Let’s verify that our application is working correctly in the Cloud Run environment:</p><ol><li>Go to the Google Cloud Console and navigate to Cloud Run</li><li>Click on your service (spring-boot-api)</li><li>Click on the URL displayed at the top of the page</li><li>Append “/hello” to the URL to test our API endpoint</li><li>Append “/actuator/health” to check the health endpoint</li></ol><p>You should see the appropriate responses from both endpoints, confirming that our application is deployed and functioning correctly. The /hello endpoint should return our greeting message, while the /actuator/health endpoint should show that our application is &quot;UP&quot; and running properly.</p><p>This verification step is crucial — it confirms that our entire pipeline is working as expected, from code commit to cloud deployment. It’s also worth noting that our CI/CD pipeline includes automated smoke tests that perform similar checks, giving us confidence that our deployment was successful even without manual verification.</p><h3>Best Practices Used in This Pipeline</h3><p>Let’s highlight the best practices we’ve implemented in our CI/CD pipeline:</p><ol><li><strong>Infrastructure as Code</strong>: All our infrastructure is defined using Terraform, making it versioned, reproducible, and automated. This ensures consistency across environments and allows us to track changes to our infrastructure over time.</li><li><strong>Multi-Stage Pipeline</strong>: Our pipeline has distinct stages for building, testing, and deploying, ensuring that we don’t proceed to the next stage if the current one fails. This catch issues early in the process, saving time and resources.</li><li><strong>Static Code Analysis</strong>: We run static code analysis using Checkstyle to maintain code quality. This helps us catch potential issues before they become problems and ensures consistent code style across our team.</li><li><strong>Comprehensive Testing</strong>: We run unit tests and API tests before deployment to catch issues early. By testing at multiple levels, we increase our confidence in the quality of our code.</li><li><strong>Smoke Testing</strong>: After deployment, we run smoke tests to verify that the application is functioning correctly in the production environment. This gives us immediate feedback on the success of our deployment.</li><li><strong>Environment Separation</strong>: We use Spring profiles to configure our application differently for different environments. This allows us to optimize our application for each environment without changing the code.</li><li><strong>Secure Secrets Management</strong>: We store sensitive information like service account keys as GitHub secrets. This ensures that our credentials are never exposed in our code or logs.</li><li><strong>Limited Permissions</strong>: Our service account has only the permissions it needs to perform its tasks. This follows the principle of least privilege, reducing the potential impact of a security breach.</li><li><strong>Immutable Deployments</strong>: We tag our Docker images with the Git commit SHA, enabling easy rollbacks and ensuring reproducibility. If we need to revert to a previous version, we can simply redeploy the previous image.</li><li><strong>Automated Rollouts</strong>: Cloud Run automatically manages the rollout of new versions without downtime. This ensures a seamless experience for our users, even during deployments.</li><li><strong>Scalability</strong>: Cloud Run automatically scales our application based on load, from zero to many instances. This means we can handle traffic spikes without over-provisioning resources.</li><li><strong>Cost Efficiency</strong>: We only pay for what we use with Cloud Run’s serverless model. When our application isn’t receiving traffic, it scales down to zero, ensuring we’re not paying for idle resources.</li><li><strong>Remote State Management</strong>: We store Terraform state in a Cloud Storage bucket, enabling collaboration and providing a backup of our infrastructure configuration. This is essential for team environments and ensures that everyone is working with the same state information.</li></ol><p>By implementing these best practices, we’ve created a robust, secure, and efficient CI/CD pipeline that gives us confidence in our deployments and allows us to focus on delivering value to our users.</p><h3>Conclusion</h3><p>In this post, we’ve built a robust CI/CD pipeline for our Spring Boot application using GitHub Actions, Terraform, and Google Cloud Platform. Our pipeline automatically builds, tests, and deploys our application whenever we push changes to our main branch, ensuring that our code is always in a deployable state.</p><p>This approach not only saves us time and reduces the risk of human error, but it also gives us confidence that our application is working correctly at every step of the development process. The use of infrastructure as code with Terraform ensures that our infrastructure is consistent, versioned, and reproducible, while Cloud Run provides a scalable and cost-effective platform for our application.</p><p>Congratulations for making it through this post, it was a long one, but contains a huge piece of the work for our automated CI/CD pipeline.</p><p>In the next article we’ll start building out our backend code and introduce persistence via a database ensuring we continue to introduce and maintain automated testing throughout.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6fb5545f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Best Practice Test Automation Pipeline with CI/CD: Part 1- Creating a Spring Boot REST…]]></title>
            <link>https://medium.com/@robert_mcbryde/building-a-best-practice-test-automation-pipeline-with-ci-cd-part-1-creating-a-spring-boot-rest-5ada5c18a4b8?source=rss-b49cd92f1dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ada5c18a4b8</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Rob McBryde]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 19:44:53 GMT</pubDate>
            <atom:updated>2025-03-26T15:52:10.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Best Practice Test Automation Pipeline with CI/CD: Part 1- Creating a Spring Boot REST API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*34eqy1x0NnBiRHuy" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the <a href="https://medium.com/@robert_mcbryde/building-a-best-practice-test-automation-pipeline-with-ci-cd-an-introduction-5a4939bd2c93">previous post</a>, we introduced the concept of a test automation pipeline using CI/CD. Now, let’s dive into creating the foundation of our application: a Spring Boot REST API. While any backend technology could serve our purpose, Spring Boot offers a robust, well-documented framework that’s ideal for demonstrating best practices.</p><p>By the end of this tutorial, you’ll have:</p><ul><li>A running Spring Boot REST API with a simple “Hello World” endpoint</li><li>Unit and API tests to ensure quality</li><li>A containerised application using Docker</li></ul><p>Let’s get started!</p><h3>Prerequisites</h3><ul><li>Java 17 installed</li><li>Maven installed</li><li>Git installed</li><li>Docker installed</li></ul><p>I don’t plan to cover a how to guide on the above prerequisites, as there are great resources on the web for doing so, but reach out if you are having any issues and I’m happy to help.</p><h3>Part 1: Creating a Spring Boot Application</h3><h3>Using Spring Initializer</h3><ol><li>Navigate to <a href="https://start.spring.io/">Spring Initializer</a> in your web browser.</li><li>Configure your project with the following settings:</li></ol><ul><li>Project: Maven</li><li>Language: Java</li><li>Spring Boot: Latest stable version (3.4.x as of writing)</li><li>Project Metadata:</li><li>Group: com.example.automationdemo</li><li>Artifact: automation-demo</li><li>Name: automation-demo</li><li>Description: Demo REST API for CI/CD pipeline</li><li>Package name: com.example.automationdemo.automation-demo</li><li>Packaging: Jar</li><li>Java: 17</li></ul><p>3. Add the following dependencies:</p><ul><li>Spring Web</li><li>Spring Boot DevTools</li><li>Spring Boot Actuator</li></ul><p>4. Click “Generate” to download the project as a ZIP file.</p><p>5. Extract the ZIP file to your preferred location and open with you IDE of choice. I am using InteliJ by Jetbrains.</p><h3>Creating a Simple REST Controller</h3><p>Let’s add a simple REST controller to handle our “Hello World” endpoint:</p><pre>package com.example.automationdemo.automation_demo.controller;<br><br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class HelloController {<br><br>    @GetMapping(&quot;/hello&quot;)<br>    public String hello() {<br>        return &quot;Hello, World!&quot;;<br>    }<br>}</pre><p>Create a new directory called “controller” and create this file called HelloController.java at the following path: src/main/java/com/example/automationdemo/automation_demo/controller/HelloController.java.</p><p>When building software, DevOps teaches us to do the hard things often. Even though all we have right now is a simple <strong>“Hello, World!”</strong> REST API in Spring Boot, our goal is to get it to production on <strong>Google Cloud Platform (GCP)</strong> via a <strong>GitHub CI/CD pipeline</strong>. By setting up our deployment pipeline early, we maximise learning opportunities and ensure that our system design remains pipeline-friendly from the start. Once we have our API service all setup and running locally in this post, we’ll move onto getting it deploying to GCP via a CI/CD pipeline in GitHub in the next blog post.</p><p>A crucial first step is writing <strong>unit tests</strong> — even if they’re basic at this stage. These tests not only validate our API but also serve a bigger purpose: they allow us to refine and stress-test our CI/CD pipeline. As our system evolves, we’ll refactor these tests to be more domain-relevant, but for now, they provide immense value in ensuring we can reliably build, test, and deploy. Let’s get started. 🚀</p><h3>Unit Testing the Controller</h3><p>Now, let’s create a unit test for our controller:</p><pre>package com.example.demoapi.controller;<br><br>import static org.hamcrest.Matchers.equalTo;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;<br>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;<br><br>import org.junit.jupiter.api.Test;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;<br>import org.springframework.http.MediaType;<br>import org.springframework.test.web.servlet.MockMvc;<br>import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;<br><br>@WebMvcTest(HelloController.class)<br>public class HelloControllerTest {<br><br>    @Autowired<br>    private MockMvc mvc;<br><br>    @Test<br>    public void getHello() throws Exception {<br>        mvc.perform(MockMvcRequestBuilders.get(&quot;/api/hello&quot;)<br>                .accept(MediaType.APPLICATION_JSON))<br>                .andExpect(status().isOk())<br>                .andExpect(content().string(equalTo(&quot;Hello, World!&quot;)));<br>    }<br>}</pre><p>Create this “HelloControllerTest” file in src/test/java/com/example/automationdemo/automation_demo/controller/.</p><p>We can run our unit tests via maven in our terminal /.mvnw testto ensure they work. They are currently verifying that when we hit /api/hello we receive a 200 response that contains the string “Hello, World!”.</p><p>We are currently achieving this with the WebMvcTest decorator. Unlike theSpringBootTest decorator, which loads the entire application context, WebMvcTest only loads the web layer. This includes the controller we are testing. A MockMvc instance is automatically injected into our test by Spring’s Dependency Injection and provides a powerful way to test MVC controllers without starting a full HTTP server. More on this in future posts when we start adding more unit testing around more complex business logic that requires mocking out further data.</p><h4>Running locally</h4><p>At this stage we are already able to run and unit test our REST API endpoint locally.</p><p>One of the great advantages of <strong>Spring Boot</strong> is that it comes with an embedded application server, allowing us to run our service locally with minimal setup. Since Spring Boot produces a <strong>self-contained unit</strong> — combining our application code with a built-in server like <strong>Tomcat, Jetty, or Undertow</strong> — we don’t need to install or configure an external server to get started. This means we can execute our service right away using a simple command, making local development and testing fast and seamless. This self-sufficiency is a key reason why Spring Boot is so popular for microservices and cloud-native applications, as it simplifies deployment and reduces operational overhead.</p><p>Since we used Spring Initialzr we have mvnw already installed in our project. The <strong>mvnw (Maven Wrapper)</strong> included with Spring Boot allows us to run Maven commands without requiring a separate Maven installation, ensuring consistent builds across different environments.</p><p>To package, test and run our app locally, ensure you are in the root of your project in your terminal and run the following commands (I am using mac):</p><pre>./mvnw package<br>./mvnw spring-boot:run</pre><p>The package command will make the JAR file for our application which is created in the target subdirectory. As part of the process it will automatically find and run our unit test.</p><p>spring-boot:run starts our local application server which you can navigate to in your web browser of choice at http://localhost:8080/api/hello</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei4_6WDwTcGE1ygCdETE_Q.png" /><figcaption>Running Spring Boot locally</figcaption></figure><p>Running locally is great for development work, but let’s get back on track with getting this API into production via a CI/CD pipeline. Next up some static code quality checks.</p><h3>Part 2: Adding Code Quality Tools</h3><h4>Configuring Maven for Linting</h4><p>Let’s add the CheckStyle plugin to our pom.xml for code linting. Add the following to your &lt;build&gt; section:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-checkstyle-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.3.0&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;configLocation&gt;google_checks.xml&lt;/configLocation&gt;<br>        &lt;consoleOutput&gt;true&lt;/consoleOutput&gt;<br>        &lt;failsOnError&gt;true&lt;/failsOnError&gt;<br>        &lt;linkXRef&gt;false&lt;/linkXRef&gt;<br>    &lt;/configuration&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;id&gt;validate&lt;/id&gt;<br>            &lt;phase&gt;validate&lt;/phase&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;check&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>Anytime you make changes to your pom.xml file, ensure you sync the changes to allow maven to pull the dependencies into your project. In Intelij this can be done via the sync changes button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*97ufVSlmhzPBjX6987yHXQ.png" /><figcaption>sync maven changes icon</figcaption></figure><h4>What Does the maven-checkstyle-plugin Do in a Spring Boot Project?</h4><p>The <strong>maven-checkstyle-plugin</strong> is a <strong>static code analysis tool</strong> that helps enforce <strong>coding standards</strong> in a Maven project. It integrates <strong>Checkstyle</strong>, which scans Java source files for style violations based on predefined or custom rules (e.g., Google Java Style).</p><h4>In a Spring Boot Project, It Can:</h4><ol><li><strong>Ensure Code Consistency</strong> — Enforce style rules across the team.</li><li><strong>Improve Code Quality</strong> — Catch formatting issues early (e.g., naming conventions, indentation, Javadoc compliance).</li><li><strong>Fail Builds on Violations</strong> — If configured strictly, it prevents merging non-compliant code.</li></ol><p>It runs Checkstyle during the validate phase and you can use a <strong>custom </strong><strong>checkstyle.xml configuration</strong> to tailor rules for your team. It is best practice as it helps maintain code consistency and quality, espcially in large projects.</p><p>As with everything in software there are alternatives available, such as Prettier which relies more on IDE-based formatting. Once more, I’m purely covering the principle of adding automatic code quality tooling to your project as a best practice. The type of linter is up to you!</p><p>You can run the above checkstyle locally via your terminal ./mvnw checkstyle:check Once again we will run this as part of our CI/CD pipeline when deploying our Spring Service to production.</p><h3>Spring Boot Actuator: Health and Info Endpoints</h3><p>Spring Boot Actuator is a powerful tool that provides production-ready features to monitor and manage applications. It exposes various built-in endpoints that give insights into the application’s health, configuration, and runtime behaviour. Among these, the /health and /info endpoints are particularly useful for assessing service status and providing relevant metadata.</p><p>In order to make both endpoints available you need to add the following line to your application.properties file which you can find at src/main/resources/application.properties.</p><pre>management.endpoints.web.exposure.include=health,info</pre><h4>The /health Endpoint</h4><p>The /health endpoint is crucial for monitoring the availability of a Spring Boot application. It returns information about the application&#39;s current state, which can be as simple as &quot;status&quot;: &quot;UP&quot; or more detailed, including database connectivity, disk space, and external service statuses. This is especially useful when integrating with container orchestrators like Kubernetes, which rely on health checks for service management.</p><p>By default, /health provides a basic status, but you can configure it to expose more details. For now the default is perfect for us. When your service is running locally you can see the /health endpoint in action by visiting: `<a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/health</a>` in your web browser.</p><h4>The /info Endpoint</h4><p>The /info endpoint is used to expose arbitrary application metadata, such as version numbers, build information, or environment details. By default, it returns an empty JSON object, but you can populate it with useful data by entering the following in the application.properties</p><pre>...<br><br>info.app.name=Automation Demo App<br>info.app.description=An example Spring Boot Rest API application to demonstrate testing via a modern CI/CD pipeline.<br>info.app.version=1.0.0<br>info.app.java.version=${java.version}<br>info.app.spring-boot.version=${spring-boot.version}</pre><p>When your service is running locally you can see the /info endpoint in action by visiting: `<a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/i</a>nfo` in your web browser.</p><h3>Adding API Tests</h3><p>Let’s create an API test using RestAssured. First, add the dependency to your pom.xml remembering to sync maven after doing so.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;<br>    &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>What is RestAssured?</h3><p><strong>RestAssured</strong> is a <strong>Java library</strong> used for <strong>testing RESTful APIs</strong>. It simplifies the process of sending HTTP requests and validating responses, making it an excellent choice for <strong>integration testing</strong> of API endpoints in Spring Boot applications.</p><h3>Why Use RestAssured for Spring Boot API Testing?</h3><ul><li><strong>Fluent API</strong>: Provides a <strong>DSL-style syntax</strong> to write expressive tests.</li><li><strong>Built-in Assertions</strong>: Easily validate response status, body, headers, etc.</li><li><strong>Seamless Integration</strong>: Works well with <strong>JUnit</strong> and <strong>Spring Boot Test</strong> frameworks.</li><li><strong>Supports JSON &amp; XML</strong>: Simplifies request and response handling.</li></ul><h3>Creating our first API test class</h3><pre>package com.example.automationdemo.automation_demo;<br><br>import static io.restassured.RestAssured.*;<br>import static io.restassured.specification.ProxySpecification.port;<br>import static org.hamcrest.Matchers.*;<br><br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.boot.test.web.server.LocalServerPort;<br><br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>public class HelloApiTest {<br><br>    @LocalServerPort<br>    private int port;<br><br>    @BeforeEach<br>    public void setUp() {<br>        baseURI = &quot;http://localhost&quot;;<br>        port(port);<br>    }<br><br>    @Test<br>    public void testHelloEndpoint() {<br>        given()<br>                .when()<br>                .get(&quot;/api/hello&quot;)<br>                .then()<br>                .statusCode(200)<br>                .body(equalTo(&quot;Hello, World!&quot;));<br>    }<br>}</pre><p>Create this “HelloApiTest” file in src/test/java/com/example/automationdemo/automation_demo/.</p><p>Let’s talk about running API tests in bit more detail. API tests differ from unit tests in <strong>how they interact with your running application</strong> because they test <strong>the system as a whole</strong>, rather than individual components in isolation.</p><p>API tests require a running instance of the application (or at least a test instance of it) where as unit tests run in isolation, without needing the full application to start.</p><p>There are a few different approaches you can take when running API tests and I’ll explain both local testing and containerised options. (Spoiler alert: I advise containerising your application).</p><h3>Option 1: Running the API Tests Locally</h3><p>The API tests we created using RestAssured (the HelloApiTest class) are designed to work with a running instance of your Spring Boot application. Here&#39;s how you can run them locally:</p><h4>Using Maven’s test phase directly</h4><p>When you run this type of test with Maven, Spring Boot’s test framework automatically:</p><ol><li>Starts your application on a random port (@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT))</li><li>Injects that port into your test (@LocalServerPort private int port;)</li><li>Runs your tests against the running application</li><li>Shuts down the application when tests are complete</li></ol><p>To run these tests:</p><pre>./mvnw test -Dtest=HelloApiTest</pre><p>You don’t need to manually start your application or have it containerised — the test framework handles this for you.</p><p>However, for real world applications, I personally advise to containerise your application with Docker. To do this we will use the <a href="https://testcontainers.com/">Testcontainers</a>.</p><h3>Option 2: Implementing Testcontainers for Spring Boot API Testing</h3><p>Testcontainers is a third party library that will automatically manage our Docker containers during testing. First we have to add these dependencies to our pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>    &lt;artifactId&gt;testcontainers&lt;/artifactId&gt;<br>    &lt;version&gt;1.19.3&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;<br>    &lt;version&gt;1.19.3&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h4>Replace HelloApiTest API test using a TestContainer version</h4><pre>package com.example.automationdemo.automation_demo;<br><br>import static io.restassured.RestAssured.*;<br>import static org.hamcrest.Matchers.*;<br><br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import org.testcontainers.containers.GenericContainer;<br><br>import org.testcontainers.junit.jupiter.Container;<br>import org.testcontainers.junit.jupiter.Testcontainers;<br><br><br><br>@Testcontainers<br>public class HelloApiContainerIT {<br>    <br>    // Retrieve pre-build image for use in our tests<br>    @Container<br>    public static GenericContainer&lt;?&gt; container = new GenericContainer&lt;&gt;(&quot;demo-api:latest&quot;)<br>            .withExposedPorts(8080);<br><br>    @BeforeEach<br>    public void setUp() {<br>        baseURI = &quot;http://localhost&quot;;<br>        port = container.getMappedPort(8080);<br>        System.out.println(&quot;Container started at port: &quot; + port);<br>    }<br><br>    @Test<br>    public void testHelloEndpoint() {<br>        given()<br>                .when()<br>                .get(&quot;/api/hello&quot;)<br>                .then()<br>                .statusCode(200)<br>                .body(equalTo(&quot;Hello, World!&quot;));<br>    }<br><br>    @Test<br>    public void testHealthEndpoint() {<br>        given()<br>                .when()<br>                .get(&quot;/actuator/health&quot;)<br>                .then()<br>                .statusCode(200)<br>                .body(&quot;status&quot;, equalTo(&quot;UP&quot;));<br>    }<br>}</pre><p>Create this in HelloApiContainerIT.java file in src/test/java/com/example/automationdemo/automation_demo/ ensuring that you no longer have the HelloApiTest for the previous step. The IT stands for Integration Test and is an important naming convention we will use via maven profiles to allow us to distinguish our testing phases and run via our CI/CD pipeline, or locally.</p><h3>Containerisation of our application via Docker</h3><p>Docker is a whole topic in itself, and not one I’m going to deep dive into in this article as there are some great free resources on the web where you can learn more. In my opinion it is a fairly standard practice in modern software engineering.</p><p>A <strong>Dockerfile</strong> is a script that contains a set of instructions for building a <strong>Docker image</strong>, which is a lightweight, portable, and self-sufficient package that includes everything needed to run an application. In the context of our <strong>Spring Boot</strong> application, a Dockerfile allows us to containerise our service, bundling the Java runtime, dependencies, and application code into a single deployable unit. This ensures consistency across environments, from local development to production. By defining a base image (e.g., Eclipse Temurin for Java 17), copying the application JAR, and specifying how to run it, we create a reproducible and scalable deployment model. Containerizing our Spring Boot API with Docker also makes it easy to integrate into a CI/CD pipeline, allowing us to build, test, and deploy in a structured and automated way.</p><p>Create a Dockerfile in the root of your project and save the following inside it:</p><pre>FROM eclipse-temurin:17-jdk AS build<br>WORKDIR /workspace/app<br><br>COPY mvnw .<br>COPY .mvn .mvn<br>COPY pom.xml .<br>COPY src src<br><br>RUN ./mvnw package -DskipTests<br>RUN mkdir -p target/dependency &amp;&amp; (cd target/dependency; jar -xf ../*.jar)<br><br>FROM eclipse-temurin:17-jre<br>VOLUME /tmp<br>ARG DEPENDENCY=/workspace/app/target/dependency<br>COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib<br>COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF<br>COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app<br>ENTRYPOINT [&quot;java&quot;,&quot;-cp&quot;,&quot;app:app/lib/*&quot;,&quot;com.example.demoapi.DemoApiApplication&quot;]</pre><h4>Adding Maven Profiles to distinguish our tests</h4><p>Add the following profiles to your pom.xml typical convention is to add this block to the bottom of your pom.xml, just before the closing project tag.</p><pre>&lt;profiles&gt;<br>    &lt;!-- Unit Tests Profile (default) --&gt;<br>    &lt;profile&gt;<br>        &lt;id&gt;unit-tests&lt;/id&gt;<br>        &lt;activation&gt;<br>            &lt;activeByDefault&gt;true&lt;/activeByDefault&gt;<br>        &lt;/activation&gt;<br>        &lt;build&gt;<br>            &lt;plugins&gt;<br>                &lt;plugin&gt;<br>                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>                    &lt;configuration&gt;<br>                        &lt;includes&gt;<br>                            &lt;include&gt;**/*Test.java&lt;/include&gt;<br>                        &lt;/includes&gt;<br>                        &lt;excludes&gt;<br>                            &lt;exclude&gt;**/*IT.java&lt;/exclude&gt;<br>                            &lt;exclude&gt;**/*ContainerIT.java&lt;/exclude&gt;<br>                        &lt;/excludes&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/plugin&gt;<br>            &lt;/plugins&gt;<br>        &lt;/build&gt;<br>    &lt;/profile&gt;<br>    <br>    &lt;!-- Container Tests Profile --&gt;<br>    &lt;profile&gt;<br>        &lt;id&gt;container-tests&lt;/id&gt;<br>        &lt;build&gt;<br>            &lt;plugins&gt;<br>                &lt;plugin&gt;<br>                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                    &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;<br>                    &lt;executions&gt;<br>                        &lt;execution&gt;<br>                            &lt;goals&gt;<br>                                &lt;goal&gt;integration-test&lt;/goal&gt;<br>                                &lt;goal&gt;verify&lt;/goal&gt;<br>                            &lt;/goals&gt;<br>                        &lt;/execution&gt;<br>                    &lt;/executions&gt;<br>                    &lt;configuration&gt;<br>                        &lt;includes&gt;<br>                            &lt;include&gt;**/*ContainerIT.java&lt;/include&gt;<br>                        &lt;/includes&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/plugin&gt;<br>            &lt;/plugins&gt;<br>        &lt;/build&gt;<br>    &lt;/profile&gt;<br>&lt;/profiles&gt;</pre><p>These profiles allow us to specify which tests to run via command line arguments, for example:</p><pre># Runs all test files whose filename end in Test.java which we can use for our unit test naming convention<br>/.mvnw test -Punit-tests   <br><br># Runs all test files whose filename end in ContainerIT.java which we can use for our integreation test naming convention<br>./mvnw verify -Pcontainer-tests </pre><p><em>Note: Why the distinction between </em><em>mvn test and </em><em>mvn verify ?</em></p><p>Maven has defined build lifecycle phase. The test phase is specifically designed for running unit tests. When you run mvn test Maven compiles your main and test code then runs tests using the surefire plugin.</p><p>The verify phase within Mavens lifecycle runs after the package phase which is important as we want to test the actual packaged artifact for our integration tests.</p><h3>Running our Integration tests</h3><p>Because we have opted to use a pre-built Docker image in our API tests in order to prevent it being rebuilt in every set of integration tests, we need to build the image before running the tests:</p><pre># Build our application<br>mvn package -DskipTests<br># build the Docker image of of application <br>docker build -t demo-api:latest .<br># Run our container tests identified in our maven profile<br>mvn verify -Pcontainer-tests</pre><h3>Benefits of Using Testcontainers</h3><ol><li><strong>Automated lifecycle management</strong> — Testcontainers automatically starts and stops containers</li><li><strong>Realistic testing environment</strong> — Tests run against the actual containerized application</li><li><strong>Isolation</strong> — Each test run gets a fresh container</li><li><strong>Parallel test execution</strong> — Different tests can use different containers</li><li><strong>No manual setup</strong> — You don’t need to manually start/stop containers</li></ol><h3>Conclusion</h3><p>We’ve now built a simple REST API with a /hello endpoint using Spring Boot, leveraging its embedded web server to run the service locally.</p><p>To monitor our service, we&#39;ve exposed Actuator endpoints (/health and /info) for future use in health checks.</p><p>Our Unit test, powered by @WebMvcTest, ensures efficiency by mocking dependencies, while our API test, using Rest Assured, interacts with a real instance of our service running in a Docker container. With our Dockerfile in place, we can package and run our API consistently across environments. But running locally isn&#39;t enough—we need to make our service accessible to teammates and end users.</p><p>The next step is committing our code to a remote repository and setting up a CI/CD pipeline with Infrastructure as Code to automate building, testing, and deploying our API. 🚀 <a href="https://medium.com/@robert_mcbryde/building-a-best-practice-test-automation-pipeline-with-ci-cd-part-2-github-integration-and-eb6fb5545f73">See you in Part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ada5c18a4b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>