AWS Builder Center
Locking Down a Brand-New AWS Account in 60 Minutes (with Terraform)

Locking Down a Brand-New AWS Account in 60 Minutes (with Terraform)

You’ve just created a fresh AWS account. Before you launch your first EC2 instance or Lambda function, take an hour to put in the guardrails that protect you from the most common problems: leaked root credentials, surprise bills, public S3 buckets and attacks nobody notices.

Technical Consultant @Inivos and Computer Science Student at IIT
In this post I’ll walk through the exact baseline I apply to every new account. It has 4 manual steps (they can’t or shouldn’t be automated) and 7 controls deployed with Terraform.

All code is on GitHub:   bl4ckf0xk/aws-secure-baseline  .

What we’re building

MANUAL (console)
TERRAFORM
Root MFA
IAM password policy
Delete root access keys
Account-wide S3 Block Public Access
IAM access to Billing
EBS encryption by default
IAM Identity Center admin
Multi-region CloudTrail ──► S3 (versioned, encrypted, TLS-only, log file validation)

Monthly budget + email alerts

IAM Access Analyzer

GuardDuty


Threat
Control
Someone gets the root password
Root MFA, no root access keys
Unexpected or abusive spend- crypto-mining
AWS Budgets alerts, GuardDuty
"Who deleted that?" with no answer
CloudTrail in every region, tamper-evident
Accidentally public data
S3 Block Public Access, Access Analyzer
Unencrypted disks
EBS encryption by default
Day-to-day use of overly powerful creds
IAM Identity Center with short-lived credents

Part 1: Manual steps (about 20 min)

Step 1: Protect the root user with MFA

Sign in as root → top-right account menu → Security credentials→ Assign MFA device.
  • Use a passkey or FIDO2 security key if you have one. An authenticator app is the next best choice.
  • Register a second MFA device as a backup (AWS supports up to 8 MFA devices per user).
  • Store the root password in a password manager, then stop using root.
AWS now requires MFA for root users on most accounts, but check that it’s actually set up on yours.



Step 2: Make sure root has no access keys

On the same Security credentials page, check Access keys. If any exist, delete them. Root access keys can do anything, can’t be restricted by IAM policies, and are a common way accounts get compromised.

Step 3: Let IAM identities see billing

Still as root: Account → IAM user and role access to Billing information → Activate. Without this, even an admin role can’t see the Billing console, so you’d end up logging in as root to check costs.


Step 4: Enable IAM Identity Center and stop using root

  1. Open IAM Identity Center → Enable. Choose the option to enable it with AWS Organizations. This makes your account the management account of a new organization, which you need in order to assign AWS account access through permission sets.
  1. Users → create a user for yourself (your real email) → accept the invite and set up MFA.
  1. Permission sets → create one from the predefined  AdministratorAccess policy. Set the session duration to 1–4 hours.
  1. AWS accounts → select your account → Assign users → your user + the permission set.
  1. Configure the CLI with short-lived credentials:

aws configure sso
# SSO start URL: copy it from the Identity Center dashboard ("AWS access portal URL")
# SSO region: the region where you enabled Identity Center
aws sts get-caller-identity --profile <your-profile>

From now on you never need long-lived IAM user access keyson your laptop.
💡 Why Identity Center instead of an IAM user? Credentials expire automatically, MFA is enforced in one place, and it scales when you add more accounts later.

Part 2: Terraform baseline (about 20 min)

Run everything below using your Identity Center admin profile, not root.
terraform/
├── versions.tf
├── variables.tf
├── main.tf
├── outputs.tf
└── terraform.tfvars.example


Control 1: IAM password policy

Even though you’re using Identity Center, a password policy protects you if someone creates an IAM user later.
resource "aws_iam_account_password_policy" "strict" {
minimum_password_length = 14
require_lowercase_characters = true
require_uppercase_characters = true
require_numbers = true
require_symbols = true
allow_users_to_change_password = true
password_reuse_prevention = 24
max_password_age = 90
}

Control 2: Account-wide S3 Block Public Access

This is a single switch that overrides any bucket policy or ACL that would make data public, across every bucket in the account.
resource "aws_s3_account_public_access_block" "this" {
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
⚠️ If you later want to host a public static website from S3, don’t turn this off. Put CloudFront with Origin Access Control in front of a private bucket instead.

Control 3: EBS encryption by default

resource "aws_ebs_encryption_by_default" "this" {
enabled = true
}
⚠️ Gotcha: this setting is per region. If you work in more than one region, apply it in each one (for example with a provider alias per region).

Control 4: CloudTrail logs everything, in every region

This is the most important control. If something goes wrong, CloudTrail is how you find out who did what and when.
resource "aws_cloudtrail" "main" {
name = local.trail_name
s3_bucket_name = aws_s3_bucket.cloudtrail.id
is_multi_region_trail = true # covers regions you "don't use" too
include_global_service_events = true # IAM, STS, CloudFront
enable_log_file_validation = true # tamper-evident digest files
depends_on = [aws_s3_bucket_policy.cloudtrail]
}
The log bucket is hardened as well: versioning, SSE encryption,  BucketOwnerEnforced , a lifecycle expiry, and a bucket policy that:
  • only lets this specific trail write to it ( aws:SourceArn  condition, which prevents the confused-deputy problem)
  • denies any non-TLS request ( aws:SecureTransport = false )
condition {
test = "StringEquals"
variable = "aws:SourceArn"
values = [local.trail_arn]
}

Control 5: Budget alerts

resource "aws_budgets_budget" "monthly" {
name = "${var.name_prefix}-monthly-cost"
budget_type = "COST"
limit_amount = tostring(var.budget_limit_usd)
limit_unit = "USD"
time_unit = "MONTHLY"

notification {
comparison_operator = "GREATER_THAN"
threshold = 80
threshold_type = "PERCENTAGE"
notification_type = "ACTUAL"
subscriber_email_addresses = [var.alert_email]
}
notification {
comparison_operator = "GREATER_THAN"
threshold = 100
threshold_type = "PERCENTAGE"
notification_type = "FORECASTED"
subscriber_email_addresses = [var.alert_email]
}
}
The forecasted alert is the useful one: it warns you before you go over budget. A sudden cost spike is often the first sign that leaked credentials are being used for crypto-mining.

Control 6: IAM Access Analyzer

resource "aws_accessanalyzer_analyzer" "account" {
analyzer_name = "${var.name_prefix}-account-analyzer"
type = "ACCOUNT"
}
It continuously checks resource policies (S3, KMS, IAM roles, Lambda, SQS, Secrets Manager…) and reports anything shared outside your account. The external access analyzer has no extra charge.

Control 7: GuardDuty

resource "aws_guardduty_detector" "this" {
count = var.enable_guardduty ? 1 : 0
enable = true
}
GuardDuty analyses CloudTrail, VPC Flow Logs and DNS logs for threats such as credential exfiltration, connections to crypto-mining pools, or API calls from unusual locations. It’s regional and comes with a 30-day free trial. Check the estimated cost in the GuardDuty console under Usage before the trial ends.

Deploy

cd terraform
cp terraform.tfvars.example terraform.tfvars # edit alert_email and region
terraform init
terraform plan
terraform apply

Part 3: Verify it worked (about 10 min)

Don’t just trust  apply . Check each control:
# CloudTrail is logging, multi-region, with validation
aws cloudtrail get-trail-status --name baseline-account-trail --query IsLogging
aws cloudtrail describe-trails --query "trailList[].{multi:IsMultiRegionTrail,validation:LogFileValidationEnabled}"

# Account-level S3 Block Public Access is on
aws s3control get-public-access-block --account-id <ACCOUNT_ID>

# EBS default encryption is on (in this region)
aws ec2 get-ebs-encryption-by-default

# GuardDuty is enabled
aws guardduty list-detectors

# Generate sample GuardDuty findings to see what alerts look like
aws guardduty create-sample-findings --detector-id <DETECTOR_ID>
Test the S3 guardrail by trying to make a test bucket public. It should be denied:
aws s3api create-bucket --bucket bpa-test-<random> --region <region> \
--create-bucket-configuration LocationConstraint=<region>
aws s3api put-bucket-policy --bucket bpa-test-<random> --policy '{
"Version":"2012-10-17",
"Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::bpa-test-<random>/*"}]
}'
# Expected: AccessDenied ... because public policies are blocked by the BlockPublicPolicy block public access setting
aws s3api delete-bucket --bucket bpa-test-<random>
In  us-east-1 , leave out  --create-bucket-configuration .
Validate CloudTrail log integrity:
aws cloudtrail validate-logs \
--trail-arn <TRAIL_ARN> \
--start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ) # macOS; on Linux use: date -u -d '1 hour ago' ...
Digest files are delivered roughly every hour, so this may only return results after about an hour.

Cleanup (lab accounts only)

terraform destroy
Set  force_destroy_log_bucket = true  first if the log bucket has objects. In a real account, keep all of this running. That's the whole point.

What’s next

This baseline covers a single account. In upcoming posts I’ll build on it:
  1. Getting rid of SSH: EC2 access with SSM Session Manager
  1. Finding unused permissions with IAM Access Analyzer
  1. Auto-remediating GuardDuty findings with EventBridge + Lambda
  1. Moving to a multi-account setup with SCPs, RCPs and an organization trail

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article