π In This Post
Lab Overview
A new team needs an AWS account. How do they get one, safely, without an engineer in the loop?
The problem. Done by hand it is three separate acts of remembering: create the account, attach the right guardrails, put it in the right place in the tree. Miss the second and the account is live with no ceiling on it.
Why not Control Tower. It automates exactly this, and enabling it is a heavy, largely irreversible step that provisions its own Log Archive and Audit accounts. This build is the same pattern without the permanent Landing Zone.
The objective. A ServiceNow ticket in, an account in the right OU with its guardrail already attached out, and the ticket closed with the new account id.
The outcome. Every step worked except the one that needed capacity: the organization was at its account limit, and the workflow's own failure path crashed before it could say so.
Cloud Services and Concepts
| Service | Purpose here | What it is |
|---|---|---|
| AWS Organizations | Owns the OU tree and creates the accounts | Groups AWS accounts under one management account, so policy and billing apply across all of them rather than account by account. |
| Service control policy | The guardrail attached to the Sandbox OU | An organization policy that sets the ceiling on what any principal in an account may do. It grants nothing on its own; it only takes permissions away. |
| AWS Step Functions | Orchestrates vending, including the failure path | Runs a workflow as an explicit state machine, so each step, its retry behaviour and its failure path are declared rather than buried in code. |
| AWS Lambda | Receives the webhook and calls CreateAccount | Runs a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs. |
| Amazon API Gateway | The HMAC-signed webhook endpoint | A managed front door that accepts HTTP requests and forwards them to a backend. |
| Amazon CloudWatch | Where the real error was found | AWS's metrics and logs service. Most services publish into it automatically, without being asked to. |
| HCP Terraform | Provisioning, with no static keys | HashiCorp's hosted Terraform. It runs plans and applies on its own machines and keeps the state file, and it assumes an AWS role by OIDC so no static keys exist anywhere. |
What You Need to Know β Skills & Tools
Two ideas carry the build. An OU is where policy attaches, and a service control policy sets a ceiling rather than granting anything. An account inherits that ceiling the moment it lands in the OU.
Architecture and Workflow
Why Nest Under an Existing OU Instead of the Root?
This Organization already had real, active accounts and Control-Tower-style OUs (Core-OU, Archived-Accounts, Workloads-OU) sitting at the root β leftovers from a Landing Zone that had been enabled and later decommissioned. Rather than scatter new Sandbox/Production OUs alongside that existing structure, this project nests them inside the existing Workloads-OU, as siblings of the existing Dev OU. Always read the current state of a shared resource like an Organization before assuming it's a blank slate.
Why a Separate Lambda per Pipeline Step?
Following the same action-dispatch pattern as Week 4's glue_trigger, account_creator handles both create_account and get_account_status via an action key, since they share the same boto3 client and IAM role. account_mover and status_notifier are separate because they need genuinely different IAM permissions β least privilege is easier to enforce when a Lambda's role only ever needs to do one category of thing.
Prerequisites
| Requirement | Why | How to check |
|---|---|---|
| An AWS Organization with all features enabled | Service control policies do not exist in consolidated-billing mode | aws organizations describe-organization reports FeatureSet: ALL |
| The SCP policy type enabled on the root | A one-time manual switch. Terraform can create a policy while the type is disabled, and attaching it then fails | aws organizations list-roots shows SERVICE_CONTROL_POLICY as ENABLED |
| Headroom in the organization's account quota | This is what stopped the lab. CreateAccount returns ConstraintViolationException when the organization is at its limit, and the quota is raised by a support request, not by Terraform | Organizations console β Settings, or raise the quota before running |
| An HCP Terraform workspace with OIDC into the AWS role | Keeps credentials out of the repo and out of CI | The workspace is VCS-connected, so apply and destroy are both driven from the HCP UI |
| A shared secret for the webhook | The endpoint accepts only HMAC-signed requests; scripts/test_webhook.sh signs with the same secret | Stored as a sensitive workspace variable, never in the repo |
Implementation
Step 1: Terraform Modules
Six Terraform modules: organizations, scp, iam, lambda, step-functions, and api-gateway. The dev environment wires them together, with the Organizations OU lookup done via a real data source rather than assumed:
data "aws_organizations_organizational_units" "root_children" {
parent_id = data.aws_organizations_organization.current.roots[0].id
}
locals {
workloads_ou_id = [
for ou in data.aws_organizations_organizational_units.root_children.children :
ou.id if ou.name == var.parent_ou_name
][0]
}
module "organizations" {
source = "../../modules/organizations"
parent_id = local.workloads_ou_id
ou_names = var.ou_names # ["Sandbox", "Production"]
}
Step 2: Service Control Policy
Enable the policy type on the root once before applying anything below (see Prerequisites):
aws organizations enable-policy-type \ --root-id <root-id> \ --policy-type SERVICE_CONTROL_POLICY # verify it took effect aws organizations list-roots
The guardrail denies expensive instance types and restricts regions. Attached once to the OU, inherited by every account that lands there:
resource "aws_organizations_policy" "sandbox_guardrail" {
name = "sandbox-guardrail-scp"
type = "SERVICE_CONTROL_POLICY"
content = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "DenyLargeInstanceTypes"
Effect = "Deny"
Action = ["ec2:RunInstances"]
Resource = "arn:aws:ec2:*:*:instance/*"
Condition = {
StringLike = { "ec2:InstanceType" = var.denied_instance_types }
}
}]
})
}
resource "aws_organizations_policy_attachment" "sandbox_guardrail" {
policy_id = aws_organizations_policy.sandbox_guardrail.id
target_id = var.sandbox_ou_id
}
Step 3: Deploying via HCP Terraform (VCS-Driven)
State lives in HCP Terraform. The workspace has to be VCS-connected rather than CLI-driven, for a reason covered in Troubleshooting.
The OUs now exist, nested under the existing structure rather than sitting at root:
With the apply complete, the SCP is live and inherited by anything that lands in the Sandbox OU:
Step 4: The Vending Pipeline (Lambda + Step Functions)
Account creation is asynchronous: CreateAccount returns a request id, the account takes 1β3 minutes, and Step Functions polls every 30s before moving it into the OU.
No ServiceNow instance is needed; a script sends the same signed payload:
Validation and Evidence
Each row traces to a figure in this post. The lab was destroyed in June 2026, so these are the results recorded then, not a fresh run.
| Test | Expected | Actual | Status |
|---|---|---|---|
| The OU tree is created | Sandbox and Production nested under the existing Workloads OU | Sandbox present at Root β Workloads-OU β Sandbox, inside the existing structure rather than beside it | Pass |
| The guardrail is attached | sandbox-guardrail-scp attached to the Sandbox OU | Shown as "Attached directly" on the OU's Policies tab, alongside the inherited FullAWSAccess | Pass |
| The webhook authenticates and starts the workflow | An HMAC-signed POST returns 200 and a Step Functions execution ARN | 200 OK with the execution ARN returned | Pass |
| An account is vended | A new account appears in the Sandbox OU | No account was created. CreateAccount returned ConstraintViolationException β the organization was at its account quota | Fail β quota, not code |
| The failure path reports the failure | CreateAccount's Catch routes to VendingFailed, which closes the ticket with the reason | VendingFailed itself errored with States.Runtime, so the real error never reached the ticket and was only visible in CloudWatch Logs | Fail β see Troubleshooting |
| Teardown removes everything | A clean destroy | 39 resources destroyed, 0 added, 0 changed | Pass |
The quota failure is the useful result: the pipeline did all it could, and the organization simply could not hold another account.
Security and Cost
Security β Controls at Every Layer
π SCPs as a Hard Ceiling
The Sandbox guardrail SCP can't be bypassed by IAM inside the vended account β not even by that account's root user. It's enforced at the Organizations level, above any policy the account itself could ever grant.
π Per-Lambda Least Privilege
account_creator can only call CreateAccount/DescribeCreateAccountStatus. account_mover can only call MoveAccount/TagResource. Neither can do what the other does.
π Webhook Authentication
Same HMAC-SHA256 validation pattern as every prior week β hmac.compare_digest(), not ==, to avoid timing attacks. Unsigned requests are rejected before Step Functions ever starts.
πΎ Secrets in SSM, Not Code
ServiceNow credentials and the webhook secret live in SSM Parameter Store as SecureString, read at runtime β nothing in environment variables or source.
- The shared
hcp-terraform-rolecurrently hasAdministratorAccessβ broader than this pipeline actually needs; a production setup should scope it down - No SCP yet on the
ProductionOU β onlySandboxhas a guardrail attached - No automated account-quota monitoring/alerting before hitting the org account limit
- No automated cleanup path for accounts that fail mid-vend and never get tagged
Cost
The vending pipeline itself is essentially free to run β the real cost consideration is what happens after an account is vended.
| Resource | Usage | Cost |
|---|---|---|
| AWS Organizations, OUs, SCPs | n/a | Free |
| Step Functions | ~10 state transitions per vend | <$0.001 |
| Lambda (4 functions) | ~6 invocations per vend | <$0.001 |
| API Gateway | 1 request per vend | <$0.001 |
| Vended AWS accounts | n/a directly | No charge to create, but each is a real, persistent account β not destroyed by terraform destroy |
Troubleshooting and Lessons
Problem. The organization was not the blank slate the module
assumed.
Root cause. It already held Control-Tower-style OUs and three
SUSPENDED accounts, residue of a decommissioned Landing
Zone.
Resolution. Nested the new OUs inside the existing
Workloads-OU, found by data source rather than assumed.
Lesson. Read the organization before writing to it. A vending machine
that only works on an empty org works nowhere real.
Problem. The workspace failed with
lstat ../../modules: no such file or directory.
Root cause. A CLI-driven HCP workspace uploads only the directory
Terraform runs from, so a module source above it can never resolve.
Resolution. Connected the workspace to the repository instead, with
working-directory set to the environment path.
Lesson. Module layout decides which execution mode is available to
you.
Problem. Attaching the SCP failed with
PolicyTypeNotEnabledException.
Root cause. SERVICE_CONTROL_POLICY had
never been enabled on the root, and Terraform creates the policy quite happily while
the type is off.
Resolution. enable-policy-type, once. The
provider has no equivalent resource.
Lesson. Creating a policy and being allowed to attach it are different
questions, and only one of them appears in the plan.
Problem. When account creation failed, the execution reported
FAILED and the ticket was never told.
Root cause. VendingFailed read
$.status_result.failure_reason, which only the polling branch
sets. With CreateAccount itself failing, the field did not
exist and the handler died on States.Runtime.
Resolution. A NormalizeFailure pass state
that both Catch blocks route through, mapping
$.error.Cause into the expected field.
Lesson. The failure path needs its own test. This one had never run
until the day it was needed.
Problem. The first end-to-end test returned
ConstraintViolationException: You have exceeded the allowed number
of AWS accounts.
Root cause. Ten accounts against the default limit β seven active,
three suspended, and suspended ones still count.
Resolution. None on the day. Closing an account does not free the slot: it stays suspended for about 90 days before deletion, and counts throughout. The limit moves only by support request.
Lesson. Quota is a capacity question with a lead time in days. Ask for
the headroom before the first ticket arrives, not after.
Cleanup and Key Takeaways
Cleanup β Tearing It Down
The workspace is VCS-connected, so destroy is confirmed from the HCP UI rather than the local CLI.
| Resource | Destroyed by Terraform? | Manual step needed? |
|---|---|---|
| Sandbox / Production OUs | Yes β if empty | Move any vended accounts out first; AWS refuses to delete a non-empty OU |
| Sandbox guardrail SCP | Yes | None |
| Lambda functions (4) | Yes | None |
| Step Functions state machine | Yes | None |
| API Gateway | Yes | None |
| IAM roles + policies | Yes | None |
| Vended AWS accounts | No β never in state | Close manually via Organizations console; closed accounts suspend for ~90 days, not deleted instantly |
Triggering the webhook in a real environment creates a real AWS account with no fast undo. Test deliberately, with a throwaway alias email, and only when you actually intend to exercise the full pipeline.
References
- Full lab guide on GitHub β prerequisites, Terraform, commands, validation and cleanup.
- AWS Organizations β Service Control Policies β how SCPs set a permission ceiling, not a grant.
- Enabling and disabling policy types on a root β the one-time root-level step this build hit (Challenge 3).
- aws_organizations_organizational_unit β Terraform resource for OUs.
- aws_organizations_policy / aws_organizations_policy_attachment β SCP creation and attachment.
- HCP Terraform CLI-driven run workflow β documents the working-directory upload limitation behind Challenge 2.
- Full source code β week-06-account-vending-machine
Takeaways β What I'd Do Differently
- Read live state first. Assuming a lab account is a clean slate nearly scattered new OUs beside an existing populated tree.
- Execution mode matters as much as the code. CLI-driven and VCS-driven workspaces differ in what they can even upload, which decides whether a module layout works at all.
- Catch blocks need their own test. The happy path reviewed clean while the failure path dropped the notification entirely.
- Quotas are infrastructure too. A vending system is only as good as the account quota behind it, and that quota moves on a support ticket, not an apply.
Comments