Explain it simply
Install the safety kit before anyone moves in
Before staff move into a new office, you install CCTV, a smoke alarm, a monthly spending limit, locks on the internal corridors, and a rule about which keys new staff may cut for themselves. An account baseline is exactly that safety kit.
In AWS, the CCTV is CloudTrail, the alarm is GuardDuty, the spending limit is AWS Budgets, the locked corridors are private subnets with VPC endpoints, and the key-cutting rule is a permission boundary. Because the kit is written as code (CDK), every new account gets the identical kit in minutes.
Problem → Why → Solution
When an account starts life with its first workload
Most teams deploy their app the day they receive a new account. Security and cost controls are left for 'later', and later usually arrives as an incident. The commands below use the CLI you learned in AWS Fundamentals to inspect an account three months after its first deploy.
With no trail, nobody can answer 'who deleted that table?'. With no GuardDuty, crypto-mining instances launched with a leaked access key run unnoticed. With no budget, the first cost signal is the monthly invoice. And all S3 traffic leaves through NAT Gateways that bill per GB processed.
# A "fresh" workload account, three months after the first deploy.
aws cloudtrail describe-trails --query 'trailList[].Name'
# [] <- nobody can answer "who deleted that table?"
aws guardduty list-detectors
# {"DetectorIds": []} <- crypto-mining on a leaked key goes unnoticed
aws budgets describe-budgets --account-id 111122223333
# {} <- the first cost signal is the invoice
aws ec2 describe-nat-gateways --query 'NatGateways[].State'
# ["available", "available", "available"] <- S3 traffic billed per GBWhy this keeps happening
A baseline appears in no feature ticket, so it ends up being nobody's job. Manual console setup also drifts: past about three accounts, no two are configured the same. The fix is to write the baseline as code and deploy it before any workload lands.
Five questions a baseline must answer
A baseline is a small set of controls deployed identically to every workload account. It must answer five questions: who did what (audit), is something bad happening right now (detection), are we spending what we expect (cost), can a network mistake leak out (containment), and can a role a developer creates exceed that developer's own permissions (guardrail).
This project splits them into three CDK stacks because their lifecycles and blast radius differ. The audit bucket and key must live for years, so they are retained. The network rarely changes. Guardrails change often as teams need new services. With separate stacks, running 'cdk deploy Baseline-Guardrails' can never accidentally replace the trail bucket.
BASELINE: THREE STACKS, ONE WORKLOAD ACCOUNT
--------------------------------------------
+-------------------- Baseline-Audit (RETAIN) ---------------------+
| CloudTrail (all regions) --> S3 bucket: versioned, BPA, TLS-only |
| | encrypted with |
| v |
| KMS key (rotation on) |
| GuardDuty detector Budget: 80% actual / 100% forecast email |
+-------------------------------------------------------------------+
+---------------- Baseline-Network --------------------------------+
| VPC 10.20.0.0/16 public /24 x2 private-isolated /20 x2 |
| no NAT gateway S3 + DynamoDB gateway endpoints (free) |
| flow logs: REJECTed traffic |
+------------------------------------------------------------------+
+---------------- Baseline-Guardrails -----------------------------+
| managed policy 'workload-developer-boundary' |
| allow app services | deny audit tampering | deny boundary escape |
+------------------------------------------------------------------+- Permission boundary
- A managed policy that sets the ceiling for an IAM role or user: whatever its identity policies say, it can never do more than the boundary allows. Effective permissions are the intersection of the identity policies and the boundary. The boundary itself grants nothing.
| Control | Decision | Why |
|---|---|---|
| Trail bucket | SSE-KMS + versioning + BPA + TLS-only | The key policy is a second lock: bucket read alone cannot decrypt logs |
| Trail | Multi-region + file validation | See attacker activity in regions you never use, and detect edited logs |
| Budget | ACTUAL 80% + FORECASTED 100% | The forecast alert fires days before the month ends |
| VPC | No NAT, isolated subnets + gateway endpoints | S3/DynamoDB traffic uses free endpoints; internet egress must be added on purpose |
This baseline is per account. At organization level, AWS Control Tower and SCPs can protect every account at once, which the deeper section covers. The point of building it by hand is to understand each building block, so you can see what those managed services automate for you.
Notice also what the baseline deliberately leaves out: no NAT Gateway, no internet-facing load balancer, no application roles. Each of those is a decision the workload team makes explicitly, on top of a floor that is known to be safe.
- Record: CloudTrail -> KMS S3
- Detect: GuardDuty findings
- Budget: alert before invoice
- Contain: private VPC + endpoints
- Limit: boundary on new roles
The first three tell you what happened; the last two stop things from happening. A good baseline needs both kinds.
The deploy loop for a multi-stack CDK app
# once per account + region: the roles and bucket CDK deploys with
cdk bootstrap aws://111122223333/us-east-1
cdk synth # templates only, nothing touches AWS
cdk diff --all # what would change, stack by stack
cdk deploy --all --require-approval broadeningBootstrap once per account and region. 'cdk diff --all' shows what changes per stack, and '--require-approval broadening' stops to ask whenever a change widens IAM permissions, which matters for a security stack like this one.
The complete baseline CDK app
The app below lives in one file but produces three stacks. The S3 bucket, VPC and IAM policy you created one by one in the console during AWS Fundamentals are now code, with each decision written next to it. The comments explain the why.
import { App, Duration, RemovalPolicy, Stack, StackProps, Tags } from "aws-cdk-lib";
import * as budgets from "aws-cdk-lib/aws-budgets";
import * as cloudtrail from "aws-cdk-lib/aws-cloudtrail";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as guardduty from "aws-cdk-lib/aws-guardduty";
import * as iam from "aws-cdk-lib/aws-iam";
import * as kms from "aws-cdk-lib/aws-kms";
import * as s3 from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";
// 1) Audit: who did what, stored where nobody can quietly change it.
class AuditStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const key = new kms.Key(this, "AuditKey", {
alias: "alias/audit-logs",
enableKeyRotation: true,
removalPolicy: RemovalPolicy.RETAIN,
});
// CloudTrail must be allowed to encrypt with this key, or delivery fails.
const trailArns = `arn:${this.partition}:cloudtrail:*:${this.account}:trail/*`;
key.addToResourcePolicy(
new iam.PolicyStatement({
principals: [new iam.ServicePrincipal("cloudtrail.amazonaws.com")],
actions: ["kms:GenerateDataKey*", "kms:DescribeKey"],
resources: ["*"],
conditions: {
StringLike: { "kms:EncryptionContext:aws:cloudtrail:arn": trailArns },
},
}),
);
const bucket = new s3.Bucket(this, "TrailBucket", {
encryption: s3.BucketEncryption.KMS,
encryptionKey: key,
bucketKeyEnabled: true,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
versioned: true,
objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_ENFORCED,
lifecycleRules: [
{
transitions: [
{ storageClass: s3.StorageClass.GLACIER, transitionAfter: Duration.days(90) },
],
noncurrentVersionExpiration: Duration.days(365),
},
],
removalPolicy: RemovalPolicy.RETAIN,
});
new cloudtrail.Trail(this, "Trail", {
bucket,
encryptionKey: key,
isMultiRegionTrail: true,
includeGlobalServiceEvents: true,
enableFileValidation: true,
sendToCloudWatchLogs: false,
});
new guardduty.CfnDetector(this, "GuardDuty", {
enable: true,
findingPublishingFrequency: "FIFTEEN_MINUTES",
});
new budgets.CfnBudget(this, "MonthlyBudget", {
budget: {
budgetName: "workload-monthly",
budgetType: "COST",
timeUnit: "MONTHLY",
budgetLimit: { amount: 200, unit: "USD" },
},
notificationsWithSubscribers: [
{
notification: {
notificationType: "ACTUAL",
comparisonOperator: "GREATER_THAN",
threshold: 80,
thresholdType: "PERCENTAGE",
},
subscribers: [{ subscriptionType: "EMAIL", address: "cloud-team@example.com" }],
},
{
notification: {
notificationType: "FORECASTED",
comparisonOperator: "GREATER_THAN",
threshold: 100,
thresholdType: "PERCENTAGE",
},
subscribers: [{ subscriptionType: "EMAIL", address: "cloud-team@example.com" }],
},
],
});
}
}
// 2) Network: private by default, S3/DynamoDB traffic never touches NAT.
class NetworkStack extends Stack {
readonly vpc: ec2.Vpc;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.vpc = new ec2.Vpc(this, "Vpc", {
ipAddresses: ec2.IpAddresses.cidr("10.20.0.0/16"),
maxAzs: 2,
natGateways: 0,
subnetConfiguration: [
{ name: "public", subnetType: ec2.SubnetType.PUBLIC, cidrMask: 24 },
{ name: "app", subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 20 },
],
gatewayEndpoints: {
S3: { service: ec2.GatewayVpcEndpointAwsService.S3 },
DynamoDB: { service: ec2.GatewayVpcEndpointAwsService.DYNAMODB },
},
});
this.vpc.addFlowLog("FlowLogs", {
trafficType: ec2.FlowLogTrafficType.REJECT,
});
}
}
// 3) Guardrails: the ceiling every role created by app teams must live under.
class GuardrailStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
new iam.ManagedPolicy(this, "DeveloperBoundary", {
managedPolicyName: "workload-developer-boundary",
statements: [
new iam.PolicyStatement({
sid: "AllowAppServices",
actions: ["s3:*", "dynamodb:*", "sqs:*", "lambda:*", "logs:*", "cloudwatch:*"],
resources: ["*"],
}),
new iam.PolicyStatement({
sid: "DenyAuditTampering",
effect: iam.Effect.DENY,
actions: [
"cloudtrail:StopLogging",
"cloudtrail:DeleteTrail",
"guardduty:DeleteDetector",
"kms:ScheduleKeyDeletion",
],
resources: ["*"],
}),
new iam.PolicyStatement({
sid: "DenyBoundaryEscape",
effect: iam.Effect.DENY,
actions: [
"iam:DeleteRolePermissionsBoundary",
"iam:CreatePolicyVersion",
"iam:DeletePolicy",
"iam:SetDefaultPolicyVersion",
],
resources: ["*"],
}),
],
});
}
}
const app = new App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: "us-east-1" };
new AuditStack(app, "Baseline-Audit", { env });
new NetworkStack(app, "Baseline-Network", { env });
new GuardrailStack(app, "Baseline-Guardrails", { env });
Tags.of(app).add("baseline", "v1");
app.synth();Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- KMS key + key policy
key.addToResourcePolicy(...cloudtrail.amazonaws.com...)Rotation is on and the key is retained. The statement letting the CloudTrail service encrypt with this key is mandatory; without it trail creation or log delivery fails. The condition limits it to this account's trails.
- Trail bucket
blockPublicAccess: BLOCK_ALL, enforceSSL: true, versioned: truePublic access fully blocked, non-TLS requests denied by bucket policy, and versioning so overwrites and deletes are recoverable. BUCKET_OWNER_ENFORCED disables ACLs. The lifecycle rule moves logs older than 90 days to Glacier to cut storage cost.
- Trail
isMultiRegionTrail: true, enableFileValidation: trueCaptures management events from every region, and digest files let you prove nobody edited the logs. CDK adds the bucket-policy statements CloudTrail needs to write automatically.
- GuardDuty + Budget
new guardduty.CfnDetector(...); new budgets.CfnBudget(...)No L2 constructs exist for these, so the L1 (Cfn) constructs are used. The budget has two notifications: actual spend at 80% and forecasted spend above 100%, both by email.
- NetworkStack
natGateways: 0, PRIVATE_ISOLATED, gatewayEndpoints: { S3, DynamoDB }Private subnets have no internet route. S3 and DynamoDB are reached through free gateway endpoints. Flow logs record only REJECTed traffic: cheap, yet enough to debug security group problems.
- GuardrailStack
sid: "DenyAuditTampering" / "DenyBoundaryEscape"The boundary allows the app services and explicitly denies stopping the trail, deleting the detector, scheduling key deletion, and removing or editing the boundary. An explicit deny beats any allow.
Sample output (IDs vary):
✅ Baseline-Audit
✅ Baseline-Network
✅ Baseline-Guardrails
'cdk synth' produces three templates and 'cdk deploy --all' prints a check mark per stack. Budget email subscribers get no confirmation email; alerts are sent directly.- Role calls ec2:RunInstances
- Boundary + policies evaluated
- CloudTrail records the call
- Log encrypted (KMS) into S3
- GuardDuty analyses the events
Normal activity
Logged, no finding
Unusual pattern
GuardDuty finding -> alert
Delegating role creation without losing control
Creating the boundary is not enough: you must force developers to attach it to every role they create. The iam:PermissionsBoundary condition key does that. Attached to the developer role, the policy below lets them create only roles named 'app-*', and only with the boundary attached.
Without this pattern, a developer who has iam:CreateRole can create a new role with AdministratorAccess and make themselves an admin (privilege escalation).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CreateRolesOnlyWithTheBoundary",
"Effect": "Allow",
"Action": ["iam:CreateRole", "iam:PutRolePolicy", "iam:AttachRolePolicy"],
"Resource": "arn:aws:iam::111122223333:role/app-*",
"Condition": {
"StringEquals": {
"iam:PermissionsBoundary":
"arn:aws:iam::111122223333:policy/workload-developer-boundary"
}
}
},
{
"Sid": "PassOnlyAppRoles",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::111122223333:role/app-*"
}
]
}Applying the boundary automatically in CDK
In app teams' CDK apps, 'iam.PermissionsBoundary.of(stack).apply(policy)' attaches the boundary to every role in that stack. You can also customise the CDK bootstrap template to put a boundary on the CloudFormation execution role.
Verifying the baseline
A successful deploy does not mean a working baseline. With a wrong key policy, the trail can exist yet fail to deliver a single log file. So check each control.
Trail delivery
IsLogging must be true and LatestDeliveryError null. If there is an error, check the KMS key policy and the bucket policy first.
Bucket protection
All four public access block flags true, versioning Enabled, encryption aws:kms.
GuardDuty alert path
Generate sample findings and confirm they actually reach your alert path (EventBridge rule, Slack, email). A detector whose findings nobody sees is useless.
Endpoints and budget
Two gateway endpoints (s3, dynamodb) must exist and the budget name must appear in the list.
# 1. CloudTrail is logging and its last delivery succeeded
TRAIL=$(aws cloudtrail describe-trails --query 'trailList[0].TrailARN' --output text)
aws cloudtrail get-trail-status --name "$TRAIL" \
--query '{logging:IsLogging,lastError:LatestDeliveryError}'
# 2. The log bucket is private, versioned and KMS-encrypted
BUCKET=$(aws cloudtrail describe-trails --query 'trailList[0].S3BucketName' \
--output text)
aws s3api get-public-access-block --bucket "$BUCKET"
aws s3api get-bucket-versioning --bucket "$BUCKET"
aws s3api get-bucket-encryption --bucket "$BUCKET"
# 3. GuardDuty is on; generate sample findings to test your alert path
DETECTOR=$(aws guardduty list-detectors --query 'DetectorIds[0]' --output text)
aws guardduty create-sample-findings --detector-id "$DETECTOR"
# 4. Gateway endpoints exist for S3 and DynamoDB
aws ec2 describe-vpc-endpoints \
--filters Name=vpc-endpoint-type,Values=Gateway \
--query 'VpcEndpoints[].ServiceName'
# 5. Budget exists
aws budgets describe-budgets --account-id 111122223333 \
--query 'Budgets[].BudgetName'From one account to an organization
Once you have twenty accounts, org-level features beat deploying this app account by account. The table maps each piece of this project to how Organizations and Control Tower usually handle it.
| This project | At org level |
|---|---|
| Per-account trail | An organization trail created from the management account or by Control Tower, logging into a separate Log Archive account |
| Per-account GuardDuty detector | A delegated administrator account auto-enables GuardDuty in new member accounts |
| Permission boundary (ceiling per role) | SCP (ceiling for the whole account, including its root user) |
| Per-account VPC | A shared VPC from a network account via AWS RAM, or Transit Gateway |
| Account budget | Consolidated billing, budgets per team, and Cost Anomaly Detection |
Do not duplicate org-level controls
Adding this trail to an account already covered by an organization trail means paying for a second copy of management events (only the first copy is free). If a delegated admin already enabled GuardDuty, CfnDetector fails with 'detector already exists'. Check what the org already provides, then deploy only the stacks you still need.
In production
How production teams run this
In production the baseline runs as part of account vending. As soon as a new account is created through Control Tower Account Factory or the Organizations API, a pipeline deploys the baseline stacks automatically with a CDK pipeline or CloudFormation StackSets. By the time an app team receives the account, the baseline is already there.
The baseline carries a version tag (for example baseline=v1), so 'which accounts are still on v1?' is a Tag Editor or Config query. GuardDuty findings are routed by an EventBridge rule to Security Hub, Slack or the on-call tool. Log archive buckets usually add S3 Object Lock so that not even an admin can delete logs within the retention period.
Budgets are split not only per account but per cost allocation tag (team, service), so when an alert arrives you know immediately which team to call.
Common mistakes
Common mistakes
Forgetting CloudTrail in the KMS key policy
If the bucket and trail use a KMS key whose policy does not give cloudtrail.amazonaws.com kms:GenerateDataKey*, trail creation or log delivery fails. Worse, if nobody watches that error, everyone believes 'we have a trail' while not a single log exists. Run the get-trail-status check from the verify step in your pipeline.
Using RemovalPolicy.DESTROY on audit resources
Carrying the lab habit of DESTROY into a baseline means one 'cdk destroy' or one stack rename can wipe two years of audit logs. Keep the audit bucket and key on RETAIN and delete them by hand, deliberately, if you must.
A boundary that does not protect itself
If the boundary does not deny iam:DeleteRolePermissionsBoundary and creating new policy versions, a role under it can remove or rewrite the boundary and escape. A ceiling must never grant the right to move the ceiling.
Best practices
Best practices
- Deploy the baseline before any workload, from a pipeline separate from app stacks
- Split audit, network and guardrails into stacks by lifecycle
- Run the verify script automatically after every deploy
- Do not duplicate controls the org already provides (org trail, GuardDuty delegated admin)
💰 Cost & Cleanup
The first copy of CloudTrail management events is free, but you pay for S3 storage of the logs and for KMS requests. Each customer managed KMS key has a monthly fee. GuardDuty has a 30-day free trial per region, then bills by the volume of events and data analysed. This VPC has no NAT Gateway, so no hourly charge, and gateway endpoints are free; flow logs incur CloudWatch Logs ingestion. Check the AWS Budgets pricing page for budget costs. Delete everything after the lab with the commands below: the retained bucket and key must be removed by hand.
Clean up when you are done
# Note the retained bucket's name BEFORE the trail disappears
BUCKET=$(aws cloudtrail describe-trails --query 'trailList[0].S3BucketName' \
--output text)
cdk destroy --all
# RETAIN resources survive the destroy on purpose. In a lab, remove them.
# A versioned bucket: delete every object version and delete marker first
# (repeat while there are more than 1,000, or use the console "Empty").
aws s3api delete-objects --bucket "$BUCKET" --delete "$(aws s3api \
list-object-versions --bucket "$BUCKET" --output json \
--query '{Objects: Versions[].{Key: Key, VersionId: VersionId}}')"
aws s3api delete-objects --bucket "$BUCKET" --delete "$(aws s3api \
list-object-versions --bucket "$BUCKET" --output json \
--query '{Objects: DeleteMarkers[].{Key: Key, VersionId: VersionId}}')"
aws s3api delete-bucket --bucket "$BUCKET"
KEY_ID=$(aws kms describe-key --key-id alias/audit-logs \
--query 'KeyMetadata.KeyId' --output text)
aws kms delete-alias --alias-name alias/audit-logs
aws kms schedule-key-deletion --key-id "$KEY_ID" --pending-window-in-days 7Mini challenge
Alert whenever the root user is used
The root user should essentially never be used. Add a stack to the baseline that emails the security team whenever it is.
- The trail must also deliver to a CloudWatch Logs log group
- A metric filter counts events where userIdentity.type = Root
- An alarm on that metric (>= 1) emails through an SNS topic
Expected: Within minutes of a root console sign-in, the alarm goes to ALARM and security@example.com receives an email (after confirming the SNS subscription).
Show hint
Use sendToCloudWatchLogs and cloudWatchLogGroup on cloudtrail.Trail. The filter is a JSON pattern; exclude events AWS itself generates (eventType AwsServiceEvent).
Show solution
import { App, Duration, Stack, StackProps } from "aws-cdk-lib";
import * as cloudtrail from "aws-cdk-lib/aws-cloudtrail";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as actions from "aws-cdk-lib/aws-cloudwatch-actions";
import * as logs from "aws-cdk-lib/aws-logs";
import * as sns from "aws-cdk-lib/aws-sns";
import * as subs from "aws-cdk-lib/aws-sns-subscriptions";
import { Construct } from "constructs";
class RootUsageAlarmStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const group = new logs.LogGroup(this, "TrailLogs", {
retention: logs.RetentionDays.ONE_YEAR,
});
// The trail also streams to CloudWatch Logs so we can alarm on events.
new cloudtrail.Trail(this, "Trail", {
sendToCloudWatchLogs: true,
cloudWatchLogGroup: group,
isMultiRegionTrail: true,
});
const filter = new logs.MetricFilter(this, "RootUse", {
logGroup: group,
metricNamespace: "Baseline",
metricName: "RootAccountUsage",
filterPattern: logs.FilterPattern.literal(
'{ $.userIdentity.type = "Root" && $.eventType != "AwsServiceEvent" }',
),
metricValue: "1",
});
const topic = new sns.Topic(this, "SecurityAlerts");
topic.addSubscription(new subs.EmailSubscription("security@example.com"));
const alarm = new cloudwatch.Alarm(this, "RootUsageAlarm", {
metric: filter.metric({ period: Duration.minutes(5), statistic: "Sum" }),
threshold: 1,
evaluationPeriods: 1,
comparisonOperator:
cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});
alarm.addAlarmAction(new actions.SnsAction(topic));
}
}
const app = new App();
new RootUsageAlarmStack(app, "Baseline-RootAlarm");
app.synth();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A baseline gives every account the same audit, detection, cost, containment and guardrail controls
- Split stacks by lifecycle and keep audit resources on RETAIN
- The KMS key policy must allow CloudTrail; verify delivery after every deploy
- A permission boundary is only a guardrail once the iam:PermissionsBoundary condition forces it
- Do not duplicate org trails, delegated admin or SCPs with account-level copies
AWS CloudTrail User Guide — AWS Documentation
IAM: Permissions boundaries for IAM entities — AWS Documentation
What is AWS Control Tower? — AWS Documentation