@composurecdk/organizations
v0.17.0
Published
Composable AWS Organizations service control policy builders with synth-time guardrails
Downloads
945
Maintainers
Readme
@composurecdk/organizations
AWS Organizations builders for ComposureCDK.
This package provides a fluent builder for service control policies (SCPs). CDK ships no Organizations L2, so the builder wraps the CfnPolicy L1 construct, following the same pattern as @composurecdk/budgets: typed setters, synth-time validation, and builder tags.
Before you deploy
- Deploy from the management account, or from a member account that is a delegated administrator for policy management.
CreatePolicyandAttachPolicywork nowhere else. - Enable the SCP policy type on the root first. This is a one-time step, done in the console or with
aws organizations enable-policy-type --root-id r-xxxx --policy-type SERVICE_CONTROL_POLICY. CloudFormation has no resource for it, and the builder does not automate it:DisablePolicyTypedetaches every SCP in the organization, so no single stack should own it. - Turn on termination protection for the stack that holds your organization's guardrails. Deleting that stack detaches every SCP in it.
- Validate before deploying. IAM Access Analyzer's
ValidatePolicyacceptspolicyType: SERVICE_CONTROL_POLICY.cfn-policy-validatorruns it over a synthesised template. The builder doesn't call it, because synth stays offline.
How SCPs behave
SCPs grant nothing. They set the most an identity policy in a member account can allow. A Deny anywhere on the path from the root to the account wins, and an action must be allowed at every level.
- Start with deny lists. Leave the AWS-managed
FullAWSAccessSCP attached everywhere and addDenypolicies alongside it. That is AWS's recommended starting point. The builder never detachesFullAWSAccess. If you move to allow lists, managingFullAWSAccessis your job: removing it without anAllowreplacement blocks every action in the affected accounts. - SCPs do not apply to the management account, nor to service-linked roles. Attaching a policy to the root does not protect the management account.
- Test on a test OU first. Attach a new SCP to an OU holding a test account before attaching it to production OUs or the root.
Service Control Policy Builder
import { createStatementBuilder } from "@composurecdk/iam";
import { createServiceControlPolicyBuilder, target } from "@composurecdk/organizations";
const { policy, document } = createServiceControlPolicyBuilder()
.name("SandboxGuardrails")
.description("Guardrails for the sandbox OU")
.addStatements([
createStatementBuilder()
.sid("DenyLeaveOrg")
.deny()
.actions(["organizations:LeaveOrganization"])
.resources(["*"]),
createStatementBuilder()
.sid("DenyLargeInstances")
.deny()
.actions(["ec2:RunInstances"])
.resources(["arn:aws:ec2:*:*:instance/*"])
.conditions({ StringNotLike: { "ec2:InstanceType": ["t3.*", "t4g.*"] } }),
])
.exceptPrincipals(["arn:aws:iam::*:role/OrganizationAccountAccessRole"])
.attachTo([target.ou("ou-ab12-cdef3456")])
.tag("project", "sandbox")
.build(stack, "SandboxGuardrails");Type is always SERVICE_CONTROL_POLICY. The result exposes the CfnPolicy and the PolicyDocument that is its Content.
| Method | Purpose |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| name(string) | The policy's Name. Required; 1 to 128 characters. |
| description(string) | The policy's Description. Up to 512 characters. |
| addStatements([...]) | Statements, as @composurecdk/iam statement builders or CDK PolicyStatements. Repeated calls add to the list. |
| exceptPrincipals([...]) | Exempts principals, such as break-glass and pipeline roles, from every Deny statement. See Statements. |
| attachTo([...]) | The policy's TargetIds. See Targets. Calls add to the list. |
| detached() | Creates the policy without attaching it. See below. |
| tag(key, value) / tags({}) | Tags the policy. |
Statements
Statements are IAM statements: SCPs support the full IAM policy language. A statement builder's wildcard-resource guard still runs, which matters for allow-list SCPs: an Allow on "*" needs allowWildcardResources(true).
Principal and NotPrincipal are the one part of the IAM grammar SCPs do not support. Scope principals with an aws:PrincipalArn condition instead. exceptPrincipals writes one, ArnNotLike: { "aws:PrincipalArn": [...] }, on every Deny statement. It merges with any conditions a statement already has, and leaves the caller's PolicyStatement unchanged.
Targets
attachTo takes target.root(id), target.ou(id) and target.account(id), or a ref to a sibling that produces one. The three constructors check the ID's format where you call them, so a typo fails at synth with the expected format in the message, not at deploy. A value holding an unresolved token is passed through unchecked. The builder checks every target again at build, which also covers values from a ref.
Organizational units are not created by this package. Pass their IDs in, for example from configuration or the environment.
Synth-time checks
build() throws when:
nameis unset, or the name or description is too long;- the policy has no statements;
- a statement has a
PrincipalorNotPrincipal, or no action; - a target ID is malformed;
- the policy has no targets and
detached()wasn't called, or has targets anddetached()was called.
Synthesis fails when the document is longer than SERVICE_CONTROL_POLICY_QUOTAS.maxCharacters. That's 10,240 characters, measured as CloudFormation sends the document: resolved, so merged where @aws-cdk/aws-iam:minimizePolicies is on, and minified. AWS raised the limit from 5,120 in May 2026. The check runs at synthesis, so it also counts statements added to the returned document after build(). It is skipped when the document holds an unresolved token.
Why a policy with no targets throws. A detached SCP deploys and does nothing, and nothing reports that it does nothing. Call detached() when you mean it, for example to stage a policy before you attach it.
Attachment slots
Each root, OU and account can have at most 10 SCPs attached, and FullAWSAccess takes one of them. To save attachment slots, put several unrelated statements in one policy. The size check is what makes this safe.
Guardrails
guardrails.* are curated Deny statements for the common deny-list SCPs. Each call returns a fresh @composurecdk/iam statement builder, so a guardrail can be its own policy or share one with others:
import { createServiceControlPolicyBuilder, guardrails, target } from "@composurecdk/organizations";
// Org-wide baseline, in one policy (see Attachment slots).
createServiceControlPolicyBuilder()
.name("OrgBaseline")
.addStatements([
guardrails.denyLeaveOrganization(),
guardrails.denyIamUsers(),
guardrails.denyDisablingSecurityServices(),
])
.attachTo([target.root("r-ab12")]);
// Sandbox OU only.
createServiceControlPolicyBuilder()
.name("SandboxLimits")
.addStatements([
guardrails.restrictRegions(["eu-west-2"]),
guardrails.restrictInstanceTypes(["t3.*", "t4g.*"]),
])
.attachTo([target.ou("ou-ab12-cdef3456")]);| Guardrail | Denies |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| denyLeaveOrganization() | organizations:LeaveOrganization. |
| denyIamUsers() | Creating IAM users, access keys and console passwords, so access goes through IAM Identity Center and roles. Existing users are untouched. |
| denyDisablingSecurityServices() | Stopping, deleting or narrowing CloudTrail, AWS Config and GuardDuty. This includes cloudtrail:UpdateTrail and cloudtrail:PutEventSelectors, and both the current and deprecated GuardDuty disassociate actions. |
| restrictRegions(regions, opts?) | Every action requested outside regions, except the global services in guardrails.GLOBAL_SERVICE_ACTIONS. opts.exemptActions adds to that list. |
| restrictInstanceTypes(types) | ec2:RunInstances for instance types outside types. Entries can be wildcards ("t4g.*"), matched with StringNotLike. |
Each factory's JSDoc links the AWS example it follows. Extend one with the statement builder's setters, or write your own statements alongside them. The set is kept small on purpose, because each list needs maintaining as AWS adds actions and services.
guardrails.GLOBAL_SERVICE_ACTIONS includes budgets:*. Budgets is a global service served from us-east-1. Without the exemption, a region-pinned account could not deploy an AWS::Budgets::Budget, a cost kill-switch for example.
Constraints
constraints.validate exposes this package's validators: policyName, policyDescription, rootId, organizationalUnitId, accountId and policyTargetId. See ADR-0010.
