Skip to Content
Cloud Engineering Academy
15. Multi-Account Governance & FinOps

Lab 15.1: design, test and attach organisation guardrails

Describe Harbourline's organisation as a file, prove with 50 tests that its guardrails block what they should and allow what they must, then attach them to your sandbox OU with Terraform and watch a real explicit deny.

advanced⏱ 2 h 🟢 FreeSCS-C03SAP-C03SOA-C03

Assumes: .NET 10 LTS · xUnit v3 4.0.3 (Microsoft.Testing.Platform) · Terraform 1.14 / AWS provider v6 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.

This is the Module 15 lab. You treat an AWS Organizations design the way you treat code: written down, linted, unit tested and only then applied. The first three-quarters needs no AWS account at all. The last quarter is optional and attaches the guardrails to the Sandbox OU of your own organisation.

Learning objectives

By the end of this lab you can:

  • Read and change an organisation design written as JSON: OUs, accounts, purposes and the SCPs attached to each node.
  • Run an SCP evaluator and linter, and explain each result in terms of the rules from Guardrails with SCPs and RCPs.
  • Write a new guardrail together with the tests that say what must be denied and what must still work.
  • Break a design on purpose and see the validator catch it.
  • Apply the guardrails to a real Sandbox OU with Terraform, observe the change with a before-and-after CLI call, and roll back.
  • Clean up so no OU, policy or lab resource remains.

Prerequisites

  • AWS Organizations structure and Guardrails with SCPs and RCPs. This lab is where their ideas run.
  • Module 0 secure account lesson: the optional part needs the organisation, the Sandbox OU and the cea-sandbox account you created there. (If you chose the free-plan path, do the offline part only.)
  • Tools: .NET 10 SDK or Docker Desktop for the tests; for the optional part, AWS CLI v2 with learn-management and learn-sandbox, and Terraform 1.10 or later.
  • Lab code: labs/m15-org-guardrails in this repository. Its README is the short version of this page.

Why this matters in banking

A bank's organisation policy is a change to the foundation of every system. Nobody wants to discover in production that "deny everything outside the UK Regions" also blocks the IAM calls the deployment pipeline makes. The way to avoid that is the way you avoid it with any critical code: tests that capture intent, reviewed in a pull request, run in CI, and only then applied. This lab gives you that loop for the part of AWS governance where mistakes are most expensive.

The idea in plain language

You will work with three kinds of file:

  1. The organisation (org/harbourline-org.json): the tree. Every node lists the policy names attached to it.
  2. The policies (policies/*.json): real SCP JSON, exactly what you would paste into AWS.
  3. The tests (tests/...): sentences like "a developer cannot stop CloudTrail in any member account" and "a developer in the sandbox can still run a small instance".

A small program reads the files and answers questions: Would this call be allowed? Is this tree valid? Is this policy sensible? It is a model, so it is not the final authority, but it is fast, runs anywhere and catches mistakes before AWS does.

Analogy: an architect's scale model of a building. You test the fire exits on the model, cheaply, before you pour concrete. You still inspect the real building, but you no longer discover that the stairs lead nowhere.

What the lab covers

PartWhat you doNeeds AWS?
ARun the 50 tests and read the evaluatorNo
BValidate the design, lint good and bad policiesNo
CBreak the design on purpose, fix itNo
DAdd a guardrail G10 with testsNo
EApply to your Sandbox OU with Terraform, verify, roll backYes (free)
FTear downYes

Microsoft / Azure comparison

You know (Microsoft/Azure)In this labWhat's different
Unit-testing Azure Policy definitions with a test harness or az policy what-ifThe evaluator and its testsAzure Policy can evaluate resource properties; SCPs filter API actions and conditions, so the tests are about calls
Management group hierarchy in Bicep or Terraformorg/harbourline-org.json and infra/terraformHere the design file is validated by your own code before Terraform runs
Policy exemptionshl-security-breakglass condition inside each policyThe exemption is part of the policy text, so a reviewer sees it
Azure Policy compliance scanhl-org validate probesThe probe asks "could an ordinary role do the forbidden thing?" for every member account

Architecture

Security-boundary view for Part E: the guardrails attach only to the Sandbox and Suspended OUs (the default), so the blast radius of a mistake is your sandbox account. The management account is exempt from SCPs, so you can always detach a policy from there.

Step-by-step implementation

Part A: run the tests

From labs/m15-org-guardrails:

dotnet test --solution OrgGuardrails.slnx

No .NET SDK? Use Docker with your own NuGet cache volume (change the path to yours):

MSYS_NO_PATHCONV=1 docker run --rm --memory 3g \
  -v "C:/Users/you/Documents/AWS-tutorial/labs/m15-org-guardrails:/src" \
  -v cea-nuget-m15:/root/.nuget/packages \
  -w /src mcr.microsoft.com/dotnet/sdk:10.0 \
  sh -c "dotnet test --solution OrgGuardrails.slnx; find . -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} +"

Expected: total: 50, failed: 0, succeeded: 50. Then open tests/Harbourline.Governance.Tests/EvaluatorTests.cs and read three tests slowly: Developer_cannot_switch_off_the_safety_net_in_any_member_account, Global_services_survive_the_region_guardrail and Removing_FullAWSAccess_leaves_an_allow_list_that_blocks_everything_else. Each one is a sentence about intent.

Part B: validate the design and lint the policies

dotnet run --project src/Harbourline.Governance.Tool -- validate org/harbourline-org.json policies

Expected:

[WARNING] HL-SCP-004 (scp-suspended-deny-all/SuspendedAccountDenyAll) Unconditional deny of every action. Only correct for a Suspended OU; anywhere else it locks the account.
OK: no errors (1 finding(s) in total).

Now lint the deliberately bad policies:

dotnet run --project src/Harbourline.Governance.Tool -- lint policies/bad/bad-region-deny.json
dotnet run --project src/Harbourline.Governance.Tool -- lint policies/bad/bad-wide-exemption.json
dotnet run --project src/Harbourline.Governance.Tool -- lint policies/bad/bad-allow-arn-and-principal.json

Match each result to the rule and the reason in the troubleshooting section of the guardrails lesson.

Ask the evaluator questions

# A developer tries to stop CloudTrail in payments-prod: denied by the baseline
dotnet run --project src/Harbourline.Governance.Tool -- check org/harbourline-org.json policies \
  payments-prod cloudtrail:StopLogging arn:aws:iam::666666666666:role/hl-developer eu-west-2

# The break-glass role may (exit code 0)
dotnet run --project src/Harbourline.Governance.Tool -- check org/harbourline-org.json policies \
  payments-prod cloudtrail:StopLogging arn:aws:iam::666666666666:role/hl-security-breakglass eu-west-2

# A call in an unapproved Region: denied by the Region guardrail
dotnet run --project src/Harbourline.Governance.Tool -- check org/harbourline-org.json policies \
  payments-dev ec2:RunInstances arn:aws:iam::888888888888:role/hl-developer ap-southeast-1

# The management account is never restricted (exit code 0)
dotnet run --project src/Harbourline.Governance.Tool -- check org/harbourline-org.json policies \
  harbourline-management organizations:LeaveOrganization arn:aws:iam::111111111111:role/anyone eu-west-2

Predict each answer before you run it. Wrong predictions teach more than right ones.

Part C: break the design on purpose

Copy org/harbourline-org.json to org/broken.json and make one change at a time. After each, run validate org/broken.json policies and note the finding:

  1. Delete the log-archive account.
  2. Move payments-prod to be a direct child of the root.
  3. In the Workloads OU, remove scp-baseline-protect from policies.
  4. Add a policy name that does not exist, such as "scp-typo".
  5. Add 11 copies of "FullAWSAccess" to the root's policies.

Item 3 is the interesting one: the tree looks fine, the policies are fine, and only the probe (HL-ORG-010) notices that an ordinary role can now stop CloudTrail in every account below Workloads. Delete org/broken.json afterwards.

Part D: add guardrail G10

Goal: only the break-glass role may change S3 Block Public Access settings.

  1. Create policies/scp-protect-public-access-block.json with one statement, Sid: ProtectPublicAccessBlock, a Deny on s3:PutBucketPublicAccessBlock and s3:PutAccountPublicAccessBlock, resource *, and the same ArnNotLike break-glass exemption used in the baseline. Check the action names against the S3 documentation ⚠ VERIFY.
  2. Attach it in org/harbourline-org.json to the Workloads OU (add it to that node's policies array).
  3. Add three tests in a new file tests/Harbourline.Governance.Tests/Guardrail10Tests.cs: developer denied in payments-prod; break-glass allowed; developer still allowed s3:GetObject.
  4. Run lint on your file, validate, then the tests.

If a test throws because the policy file is not found, check that the test project's <None Include="..\..\policies\**\*.json" ...> item still copies the file to the output folder (it should, since the pattern is a wildcard).

Part E (optional): apply to your Sandbox OU

Only continue if you have the Module 0 organisation. Sign in and find the IDs:

aws sso login --profile learn-management
aws organizations list-roots --profile learn-management --query "Roots[0].Id" --output text
aws organizations list-organizational-units-for-parent --parent-id r-xxxx --profile learn-management \
  --query "OrganizationalUnits[].{Id:Id,Name:Name}" --output table

Before attaching anything, prove the baseline: in the sandbox account, try to stop a trail that does not exist.

aws sso login --profile learn-sandbox
aws cloudtrail stop-logging --name hl-does-not-exist --profile learn-sandbox

Expected now: TrailNotFoundException (the call was authorised, the trail simply is not there).

Apply:

cd infra/terraform
terraform init
terraform plan  -var owner=<your-name> -var root_id=r-xxxx -var existing_sandbox_ou_id=ou-xxxx-xxxxxxxx
terraform apply -var owner=<your-name> -var root_id=r-xxxx -var existing_sandbox_ou_id=ou-xxxx-xxxxxxxx

Read the plan before you type yes: it should create 4 or so OUs (Security, Infrastructure, Workloads with Prod and NonProd, Suspended), 4 policies and attach 4 of them to Sandbox and Suspended. It must not touch your account or your existing cea-region-guardrail.

After, repeat the same call:

aws cloudtrail stop-logging --name hl-does-not-exist --profile learn-sandbox

Expected: AccessDeniedException ... with an explicit deny in a service control policy ⚠ VERIFY exact wording. That is your SCP, in real AWS, doing what the evaluator predicted. The nonexistent trail is deliberate: authorisation (including the SCP) happens before the service looks for the trail, so nothing real is touched.

Roll back and clean up

cd infra/terraform
terraform destroy -var owner=<your-name> -var root_id=r-xxxx -var existing_sandbox_ou_id=ou-xxxx-xxxxxxxx

Repeat the stop-logging call: it should return TrailNotFoundException again. Then delete local build output (see Cost and cleanup).

AWS Console instructions

For Part E, you can watch the same change in the console:

  1. Management account → AWS Organizations → Policies → Service control policies. You should see scp-baseline-protect, scp-deny-outside-regions, scp-sandbox-limits and scp-suspended-deny-all after apply.
  2. Open scp-baseline-protect → Targets: the Sandbox OU only (with the default safety switch).
  3. AWS accounts: the new OUs appear under the root. Select your sandbox OU and open the Policies tab to see inherited and direct SCPs.
  4. In the sandbox account, CloudTrail → Event history, filter Event name = StopLogging: your denied call appears with an error code.

AWS CLI

# Which SCPs are attached directly to the Sandbox OU?
aws organizations list-policies-for-target --target-id ou-xxxx-xxxxxxxx --filter SERVICE_CONTROL_POLICY --profile learn-management

# Which targets use one policy?
aws organizations list-targets-for-policy --policy-id p-xxxxxxxx --profile learn-management

# Emergency rollback without Terraform: detach one policy from the OU
aws organizations detach-policy --policy-id p-xxxxxxxx --target-id ou-xxxx-xxxxxxxx --profile learn-management

# Find the denied call in the sandbox account's CloudTrail
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=StopLogging \
  --max-results 3 --profile learn-sandbox --query "Events[].CloudTrailEvent" --output text

Infrastructure as Code

The lab's infra/terraform folder (passes terraform validate on 1.14). The core attachment logic, with the safety switch:

locals {
  # With the safety switch on, only the Sandbox and Suspended OUs receive guardrails.
  active_attachments = {
    for k, v in local.attachments : k => v
    if !var.attach_to_sandbox_only || contains(["Sandbox", "Suspended"], v.ou)
  }
}

resource "aws_organizations_policy" "scp" {
  for_each    = local.scp_files
  name        = each.key
  description = "Harbourline guardrail ${each.key} (lab m15-l1)"
  type        = "SERVICE_CONTROL_POLICY"
  content     = file(each.value)
}

resource "aws_organizations_policy_attachment" "scp" {
  for_each  = local.active_attachments
  policy_id = aws_organizations_policy.scp[each.value.policy].id
  target_id = local.ou_ids[each.value.ou]
}

To add your G10 policy, add one line to scp_files and one or more lines to attachments.

Complete code

The lab is complete in labs/m15-org-guardrails. The pieces, in the order you will read them:

FileWhat it does
src/Harbourline.Governance.Org/OrgModel.csOrganization, OrgNode: the tree, PathFromRoot(), OuDepth
src/Harbourline.Governance.Org/PolicyModel.csScpParser, ScpDocument, PolicyCatalog (FullAWSAccess built in)
src/Harbourline.Governance.Org/ScpEvaluator.csThe evaluation rules (see the lesson for the core method)
src/Harbourline.Governance.Org/ScpLinter.csRules HL-SCP-001 to 009
src/Harbourline.Governance.Org/OrgValidator.csRules HL-ORG-001 to 010, including the probe
src/Harbourline.Governance.Tool/Program.csThe hl-org command line
tests/Harbourline.Governance.Tests/*.cs50 xUnit v3 tests

The test project file shows how the policies reach the tests as fixtures, which is a pattern worth stealing:

tests/Harbourline.Governance.Tests/Harbourline.Governance.Tests.csproj (excerpt)
<ItemGroup>
  <!-- The policies and the organisation file are test fixtures: copy them next to the test binary. -->
  <None Include="..\..\policies\**\*.json" LinkBase="policies" CopyToOutputDirectory="PreserveNewest" />
  <None Include="..\..\org\*.json" LinkBase="org" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

The probe in OrgValidator, which is the idea to remember:

OrgValidator.cs (the HL-ORG-010 probe)
// HL-ORG-010: probe the guardrails with an ordinary engineer role
if (findings.All(f => f.Code != "HL-ORG-009"))
{
    var evaluator = new ScpEvaluator(catalog);
    foreach (var account in org.Accounts.Where(a => a.Purpose != "management"))
    {
        var engineer = $"arn:aws:iam::{account.Id}:role/hl-developer";
        foreach (var action in ProtectedActions)
        {
            var decision = evaluator.Evaluate(account, new AuthRequest(action, engineer, "eu-west-2"));
            if (decision.Allowed)
                findings.Add(new("HL-ORG-010", Severity.Error, $"An ordinary role can call {action}: the guardrail is not effective.", account.Name));
        }
    }
}

Code explained line by line

  1. The probe only runs if every policy name resolves (HL-ORG-009 absent), because evaluating a node that references a missing policy would throw.
  2. It loops over every member account (not the management account: SCPs do not apply there) and every protected action.
  3. engineer is a role ARN for an ordinary developer. Nothing about it is special, which is the point: an ordinary role must not be able to do these things anywhere.
  4. AuthRequest(action, engineer, "eu-west-2") is a request in an approved Region, so the Region guardrail does not hide the result.
  5. If decision.Allowed is true, the guardrail is missing or too narrow in that account's path. The finding names the account and the action, so the fix is obvious.
  6. The same method feeds the unit tests, hl-org validate and the CI job, so there is one definition of "the guardrails work".
  7. In the test csproj, LinkBase="policies" and CopyToOutputDirectory put the fixtures beside the compiled test, so tests read them from AppContext.BaseDirectory and run the same on any machine.

Security considerations

⚠ Learning shortcut — not for production

You apply guardrails from your laptop with one SSO profile, to a sandbox OU that contains one account, and the evaluator is a teaching model of SCPs. In production you would apply through a pipeline role after a reviewed pull request, test in a Policy Staging OU with real traffic for weeks, and validate also with IAM Access Analyzer. You would also test RCPs and the effect of IAM and resource policies, none of which this model covers.

  • You can lock yourself out. An over-broad SCP on the Sandbox OU can block the very role you use. Keep the management account path open: it is exempt from SCPs, so you can always detach-policy from there.
  • The safety switch matters. attach_to_sandbox_only defaults to true. Do not set it to false in a real organisation without a rollout plan.
  • Do not paste account IDs or organisation IDs from a real organisation into public repositories. The IDs in this lab are fictional.
  • Terraform state is sensitive. It contains your organisation structure. Keep it in a private backend, not in Git.
  • Never claim compliance from passing tests. The tests show that your intent is encoded; they do not show that the real organisation matches it or that a framework is satisfied.

Banking use case

Harbourline's platform team keeps org/ and policies/ in a repository that requires two approvals. Every pull request runs dotnet test and hl-org validate. When a security engineer proposes a new guardrail, reviewers read the tests first, because the tests say what the author believes the policy does. When an incident teaches the team something (for example an attacker used a Region nobody watched), the fix is a new test that fails, then a policy change that makes it pass. After merge, a pipeline role applies to Policy Staging, and promotion to Workloads follows the staged plan from the guardrails lesson.

Common mistakes

  • Testing only what should be denied. A guardrail that denies everything passes every "must be denied" test. Always add "must still work".
  • Letting the model replace AWS. The evaluator ignores IAM policies, RCPs and several operators. Confirm in a staging account.
  • Editing broken.json in place and forgetting to delete it. The validator reads only the files you name, but a stray file in org/ is copied to test output; keep the folder clean.
  • Attaching to Workloads and Security while the safety switch is on. Terraform will quietly attach only to Sandbox and Suspended; read the plan.
  • Forgetting existing_sandbox_ou_id. apply fails with a duplicate OU error. Pass the Module 0 OU ID.
  • Using a policy name with a space or capital in org/*.json. Names must match the file name exactly (case-sensitive).

Troubleshooting

SymptomLikely causeFix
dotnet test cannot find the solutionWrong folderRun from labs/m15-org-guardrails, with --solution OrgGuardrails.slnx
Test fails with DirectoryNotFoundException for policiesFixture copy item missing or filteredCheck the <None Include> items in the test csproj
Error: No account named 'payments-prod'The org file path or name is wrongAccount names are case-insensitive but must exist in the file
HL-ORG-009 for your new policyThe file is in policies/bad/ or its name differs from the referenceMove it to policies/ and match the file stem
NotSupportedException from checkThe policy uses an operator the model does not supportTest it in a staging account, or add support in ScpEvaluator
terraform apply: DuplicateOrganizationalUnitExceptionAn OU already existsUse -var existing_sandbox_ou_id=... or rename
terraform apply: PolicyTypeNotEnabledExceptionSCPs not enabled on the rootaws organizations enable-policy-type --root-id r-xxxx --policy-type SERVICE_CONTROL_POLICY
After apply, stop-logging still says TrailNotFoundExceptionThe sandbox account is not in the OU you attached to, or the attach was skippedCheck list-policies-for-target on the OU and list-parents on the account
You cannot sign in or run commands in the sandbox after applyA guardrail blocks your roleFrom the management account, detach-policy the newest policy, then investigate

Cost and cleanup

Cost: free. The tests run locally. Organizations, OUs and SCPs have no charge; the optional Terraform apply creates no billable resources.

# 1. Terraform (if you applied)
cd labs/m15-org-guardrails/infra/terraform
terraform destroy -var owner=<your-name> -var root_id=r-xxxx -var existing_sandbox_ou_id=ou-xxxx-xxxxxxxx

# 2. If an OU will not delete, it still has an account: move it out first
aws organizations list-accounts-for-parent --parent-id ou-xxxx-xxxxxxxx --profile learn-management

# 3. Local build output (the test runs create bin/ and obj/)
find labs/m15-org-guardrails -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} +

# 4. Confirm nothing tagged for the lab remains in the sandbox account
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --profile learn-sandbox --region us-east-1 --query "ResourceTagMappingList[].ResourceARN"

# 5. Confirm the policies are gone
aws organizations list-policies --filter SERVICE_CONTROL_POLICY --profile learn-management \
  --query "Policies[].Name"

You should see only FullAWSAccess and your Module 0 cea-region-guardrail.

Exercises

  • 🟢 Guided: Complete Parts A to D, including G10 and its three tests.
  • 🟡 Challenge: Add a Policy Staging OU with one test account to org/harbourline-org.json, attach only scp-baseline-protect to it, and extend OrgValidator with a rule HL-ORG-011: every custom SCP attached to Workloads must also be attached to the Policy Staging OU (a warning). Add two tests (one passing, one failing).
  • 🔴 Live problem: After your Part E apply, a teammate reports that their Lambda deployment in the sandbox now fails with an access denied error mentioning a service control policy. Using only the repository and CloudTrail, find which statement caused it (the lab's check command should reproduce it) and decide whether to change the policy, the deployment, or neither. Write your reasoning.

Assignment

Publish m15-org-guardrails in your portfolio repository, with: the tests passing in CI, your G10 policy and tests, a short DECISIONS.md (why each OU exists, which guardrails are attached where and why the root has none), and the output of hl-org validate. This is the first building block of Capstone 7: Secure multi-account landing zone (lite).

Solutions

Knowledge check

Interview questions

  • How do you test an SCP before it reaches production? Lint, unit-test intent (denied and still-allowed cases) with a model, validate with Access Analyzer, attach to a staging account, watch CloudTrail, promote OU by OU with a rehearsed rollback.
  • Why keep the organisation as code? Review, history, repeatability, and automated checks like the probe. It also makes recovery after a mistake much faster.
  • What does your offline evaluator not cover? RCPs, IAM and resource policies, boundaries, session policies, several condition operators and real service behaviour. So it supplements, not replaces, staging tests.
  • How would you stop someone accidentally detaching the guardrails? Only a pipeline role in the management account can edit policies, alerts fire on DetachPolicy, and the daily validator compares reality with the repository.

Certification practice

Completion checklist

  • I ran the 50 tests and read three of them
  • I ran hl-org validate, lint and check and predicted the results first
  • I broke the design five ways and understood each finding
  • I added G10 with a "must still work" test
  • (Optional) I saw a real explicit deny in the sandbox and rolled it back
  • I deleted bin/, obj/, broken.json and ran the cleanup checks

Key takeaways

  • Treat the organisation as code: file, lint, test, review, apply.
  • Test what must be denied and what must still work.
  • A probe that acts like an ordinary user finds guardrails that are attached but ineffective.
  • Models are fast and cheap; staging accounts are true. Use both.
  • Attach to the Sandbox first, keep the management account as your way back.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page