Sub topic 15
Automating account provisioning and baselines
This chapter assumes you know the basics of AWS Organizations (management account, OUs, member accounts), can read IAM policy JSON, and have used the AWS CLI. Terraform knowledge helps but is not required. By the end you should be able to describe how a new account goes from a request to a usable, governed environment without anyone clicking through the console.
Why automate account creation
Creating one account by hand is easy. Creating the fiftieth is where mistakes appear. A person forgets to enable a log setting, picks a different alias, or leaves the account in the wrong OU. Each mistake becomes a small difference between accounts, and those differences are hard to find later.
Automation gives you three things:
- Repeatability. Every account gets the same structure and settings.
- Reviewability. Changes go through pull requests, so a second person sees them before they take effect.
- Auditability. Version history shows who changed what, and when.
Two separate jobs need automation, and it helps to keep them apart:
- Provisioning creates the account and places it in an OU.
- Baselining configures what every account needs from its first day: roles, logging, security settings, budgets and network pieces.
The provisioning pipeline
The diagram below shows a typical flow. A request enters as a code change. A pipeline running in the management account (or a dedicated automation account) creates the account. A second stage then applies the baseline inside the new account by assuming the role that Organizations created.
Declaring the structure in Terraform
Terraform lets you describe the organization, OUs and accounts as code. The configuration below declares the organization with all features, enables trusted access for two services, enables SCPs, creates a Workloads OU and one member account in it.
resource "aws_organizations_organization" "org" {
feature_set = "ALL"
aws_service_access_principals = [
"cloudtrail.amazonaws.com",
"sso.amazonaws.com",
]
enabled_policy_types = ["SERVICE_CONTROL_POLICY"]
}
resource "aws_organizations_organizational_unit" "workloads" {
name = "Workloads"
parent_id = aws_organizations_organization.org.roots[0].id
}
resource "aws_organizations_account" "prod_app1" {
name = "prod-app1"
email = "[email protected]"
parent_id = aws_organizations_organizational_unit.workloads.id
role_name = "OrganizationAccountAccessRole"
}Several details matter here.
aws_service_access_principalsturns on trusted access, which lets those services work across the organization. Without it, features such as an organization-wide trail cannot be set up.enabled_policy_typesmust include a policy type before you can attach policies of that type.role_namesets the name of the administrative role created in the new account. The default isOrganizationAccountAccessRole.- The
emailmust be unique across all AWS accounts. Plan an address scheme, such as a shared mailbox with plus-addressing or one alias per account, before you create many accounts.
Gotchas with account resources
Accounts behave differently from most resources, and these points cause the most surprises.
- Deleting the Terraform resource does not close the account. By default, removing the resource only removes it from state. Closing an account is a separate, deliberate step covered in the lifecycle chapter. Set
close_on_deletion = trueonly if you really want a destroy to close accounts. - Closed accounts keep their email address and count against quotas for a period, so a create, destroy, create cycle in a test environment can fail.
- Changing
role_nameoremailafter creation is not applied to the existing account. Treat these as fixed at creation time. - Account creation is asynchronous. The API call returns quickly, but the account takes a few minutes to become active. Tools handle this by polling; custom scripts must do the same.
Doing it with the CLI
A CLI script is useful for understanding what Terraform does underneath, and for small pipelines. The sequence is the same as the console: create, wait, move.
aws organizations create-account \
--email [email protected] \
--account-name prod-app1
aws organizations list-create-account-status \
--states IN_PROGRESS SUCCEEDED FAILEDNew accounts land directly under the root. Moving the account into its OU uses the command from earlier chapters:
aws organizations move-account \
--account-id 111122223333 \
--source-parent-id r-examplerootid111 \
--destination-parent-id ou-examplerootid111-exampleouid111Move the account as early as possible. Until it is in the OU, it inherits only the policies attached to the root, and it will not receive the guardrails you designed for that OU.
Reaching into the new account
The pipeline needs credentials inside the new account to apply a baseline. Organizations creates the administrative role for this purpose. The management account assumes it and receives temporary credentials:
aws sts assume-role \
--role-arn arn:aws:iam::111122223333:role/OrganizationAccountAccessRole \
--role-session-name admin-sessionThis role trusts the management account and has full administrator permissions. That is convenient for bootstrapping, but it is a powerful door. Good practice is to:
- Use it only to deploy the baseline, and let the baseline create narrower roles for day-to-day deployment.
- Restrict who in the management account can assume it.
- Consider an SCP or monitoring rule that alerts on its use outside the pipeline.
What belongs in a baseline
A baseline is the set of resources every account gets. Keep it small and focused on things that must exist for governance, not application resources.
| Baseline item | Purpose |
|---|---|
| Deployment role | Lets the pipeline deploy workloads with least privilege |
| Account alias and contact details | Makes the account identifiable and reachable |
| Security services enabled | Detection tools turned on in the account |
| Log delivery settings | Sends logs to the central logging account |
| Default encryption and public access blocks | Safe defaults for storage |
| Budget and alert | Early warning on unexpected spend |
| Network attachments | Connects to shared networking where needed |
Different OUs usually need different baselines. A sandbox account might get a low budget cap and no network attachment. A production account gets stricter logging and a connection to the shared network. Drive this from an input such as the OU name or an account tag.
Applying baselines at scale
You have three common options for pushing a baseline into many accounts.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Terraform with provider aliases | One configuration assumes a role per account | Single tool for everything | Provider blocks must be known up front, so adding accounts means editing code |
| CloudFormation StackSets | Service-managed StackSets deploy a template to every account in chosen OUs | Deploys automatically to new accounts in the OU | Template language is CloudFormation only |
| Pipeline per account | A pipeline runs a baseline module with account-specific variables | Flexible and easy to retry | More moving parts to maintain |
Service-managed StackSets are worth knowing well. You enable trusted access for StackSets, target an OU, and AWS deploys the stack to every current account in it. When a new account joins the OU, the stack deploys automatically. That removes the gap between creating an account and baselining it.
Handling drift
Drift is any difference between what the code says and what exists. In a multi-account setup, drift usually comes from console changes made during an incident.
- Run a scheduled plan or drift detection and alert on differences.
- Limit who can change baseline resources by denying changes to them in an SCP, with an exception for the pipeline role.
- Prefer fixing the code and redeploying over editing the resource, so the next run does not undo your fix.
Choosing between custom automation and Control Tower
Building your own pipeline gives you full control and fits teams already fluent in Terraform. The cost is that you maintain it. AWS Control Tower, covered in the next chapter, packages many of these steps into a managed service. A reasonable rule: if you have a handful of accounts and strong infrastructure-as-code skills, custom automation is manageable. As the fleet grows, or when you need a managed set of guardrails, weigh Control Tower's ready-made landing zone against its constraints.
Common errors
EmailAlreadyExistsException: the address is already tied to another AWS account. Use a unique address.ConstraintViolationExceptionon account count: you reached the account quota. Request an increase before running bulk creation.AccessDeniedExceptiononassume-role: the caller is not in the management account, or the role was removed from the new account.- Baseline fails because a service is not enabled: trusted access or the policy type was not turned on in the organization. Enable it first.
- A new account is missing guardrails: it was left at the root. Place it in the OU as part of the same pipeline run.
Exercise
A pipeline creates an account, then immediately runs aws sts assume-role against the new account and fails. Give two likely causes and one fix for each.
Show answer
First, account creation is asynchronous, so the account may still be INPROGRESS. Fix: poll list-create-account-status until the state is SUCCEEDED before assuming the role. Second, the caller may not be the management account, which the default role trusts, or the role name may differ from the one set at creation. Fix: run the pipeline from the management account (or adjust the trust policy) and use the exact `rolename` you configured.
Exercise
Your team wants every account in the Workloads OU to get the same logging baseline automatically, including accounts created next month. Which approach from this chapter fits best, and why?
Show answer
A service-managed CloudFormation StackSet targeted at the Workloads OU. It deploys to existing accounts and automatically to any account that later joins the OU, so there is no gap between account creation and baselining.