Homeβ€Ί Blogβ€Ί Week 6 - Building an Account Vending Machine with …
AWS Weekly Lab AWS Terraform

Building an Account Vending Machine with AWS Organizations, SCPs & Step Functions (No Control Tower)

A ServiceNow ticket creates a real AWS account, drops it into the right Organizational Unit, and inherits its guardrails automatically β€” no Control Tower required

AWS Platform Engineering Lab Β· Week 06

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.

Who Benefits

Cloud Services and Concepts

ServicePurpose hereWhat it is
AWS OrganizationsOwns the OU tree and creates the accountsGroups AWS accounts under one management account, so policy and billing apply across all of them rather than account by account.
Service control policyThe guardrail attached to the Sandbox OUAn 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 FunctionsOrchestrates vending, including the failure pathRuns 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 LambdaReceives the webhook and calls CreateAccountRuns a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs.
Amazon API GatewayThe HMAC-signed webhook endpointA managed front door that accepts HTTP requests and forwards them to a backend.
Amazon CloudWatchWhere the real error was foundAWS's metrics and logs service. Most services publish into it automatically, without being asked to.
HCP TerraformProvisioning, with no static keysHashiCorp'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

aws AWS Cloud ServiceNow catalog request 1 Management account API Gateway signed POST 2 webhook receiver validates 3 Step Functions 4 states 4 Organizations CreateAccount SCPs on the OU guardrails CreateAccount is asynchronous, so the workflow polls its status before moving the account -- a create that returned is not an account that exists yet. 5 Workloads OU Sandbox / Prod

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

RequirementWhyHow to check
An AWS Organization with all features enabledService control policies do not exist in consolidated-billing modeaws organizations describe-organization reports FeatureSet: ALL
The SCP policy type enabled on the rootA one-time manual switch. Terraform can create a policy while the type is disabled, and attaching it then failsaws organizations list-roots shows SERVICE_CONTROL_POLICY as ENABLED
Headroom in the organization's account quotaThis 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 TerraformOrganizations console β†’ Settings, or raise the quota before running
An HCP Terraform workspace with OIDC into the AWS roleKeeps credentials out of the repo and out of CIThe workspace is VCS-connected, so apply and destroy are both driven from the HCP UI
A shared secret for the webhookThe endpoint accepts only HMAC-signed requests; scripts/test_webhook.sh signs with the same secretStored 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:

HCL β€” Nesting Under an Existing OU
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

Prerequisite β€” Enable the SCP Policy Type First

Enable the policy type on the root once before applying anything below (see Prerequisites):

AWS CLI β€” One-Time Root Setup
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:

HCL β€” Sandbox Guardrail SCP
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.

HCP Terraform apply run for week-06-dev showing resources created
HCP Terraform β€” week-06-dev apply run, confirmed via the HCP UI run page (VCS-connected workspace, no local CLI apply)

The OUs now exist, nested under the existing structure rather than sitting at root:

Sandbox OU nested under Workloads-OU in AWS Organizations console
The Sandbox OU, reached via Root β†’ Workloads-OU β†’ Sandbox β€” nested inside 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:

sandbox-guardrail-scp attached directly to the Sandbox OU
Sandbox OU β€” Policies tab showing sandbox-guardrail-scp "Attached directly", alongside the inherited FullAWSAccess defaults

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.

API Gateway /webhook POST method execution diagram showing Lambda integration
API Gateway /webhook POST method β€” Client β†’ Method request β†’ Integration request β†’ webhook_receiver Lambda

No ServiceNow instance is needed; a script sends the same signed payload:

Terminal output showing a simulated ServiceNow webhook call returning 200 OK with an execution ARN
Simulated ServiceNow webhook via scripts/test_webhook.sh β€” HMAC-signed POST returns 200 OK with the Step Functions execution ARN, confirming the pipeline started

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.

TestExpectedActualStatus
The OU tree is createdSandbox and Production nested under the existing Workloads OUSandbox present at Root β†’ Workloads-OU β†’ Sandbox, inside the existing structure rather than beside itPass
The guardrail is attachedsandbox-guardrail-scp attached to the Sandbox OUShown as "Attached directly" on the OU's Policies tab, alongside the inherited FullAWSAccessPass
The webhook authenticates and starts the workflowAn HMAC-signed POST returns 200 and a Step Functions execution ARN200 OK with the execution ARN returnedPass
An account is vendedA new account appears in the Sandbox OUNo account was created. CreateAccount returned ConstraintViolationException β€” the organization was at its account quotaFail β€” quota, not code
The failure path reports the failureCreateAccount's Catch routes to VendingFailed, which closes the ticket with the reasonVendingFailed itself errored with States.Runtime, so the real error never reached the ticket and was only visible in CloudWatch LogsFail β€” see Troubleshooting
Teardown removes everythingA clean destroy39 resources destroyed, 0 added, 0 changedPass

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.

What's Missing for Production
  • The shared hcp-terraform-role currently has AdministratorAccess β€” broader than this pipeline actually needs; a production setup should scope it down
  • No SCP yet on the Production OU β€” only Sandbox has 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.

ResourceUsageCost
AWS Organizations, OUs, SCPsn/aFree
Step Functions~10 state transitions per vend<$0.001
Lambda (4 functions)~6 invocations per vend<$0.001
API Gateway1 request per vend<$0.001
Vended AWS accountsn/a directlyNo charge to create, but each is a real, persistent account β€” not destroyed by terraform destroy
Pipeline infrastructure destroyed: $0. Vended accounts are a separate, manual cleanup β€” they were never written into Terraform state, since they're created dynamically by Lambda at runtime, not declared statically.

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.

ResourceDestroyed by Terraform?Manual step needed?
Sandbox / Production OUsYes β€” if emptyMove any vended accounts out first; AWS refuses to delete a non-empty OU
Sandbox guardrail SCPYesNone
Lambda functions (4)YesNone
Step Functions state machineYesNone
API GatewayYesNone
IAM roles + policiesYesNone
Vended AWS accountsNo β€” never in stateClose manually via Organizations console; closed accounts suspend for ~90 days, not deleted instantly
A vended account is forever-ish
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.
HCP Terraform destroy run for week-06-dev, triggered via UI, 39 resources destroyed
HCP Terraform β€” week-06-dev destroy run, triggered via UI and confirmed (39 resources destroyed, 0 added/changed)

References

Takeaways β€” What I'd Do Differently

  1. Read live state first. Assuming a lab account is a clean slate nearly scattered new OUs beside an existing populated tree.
  2. 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.
  3. Catch blocks need their own test. The happy path reviewed clean while the failure path dropped the notification entirely.
  4. 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

How was your experience?
Your feedback helps improve this site.
PoorExcellent