← Back to Tutorials
Tutorial 02 Beginner-Intermediate

Complete Guide: Setting Up CloudTrail Logging

AWS CloudTrail is your organization's flight recorder—it captures every action taken in your AWS account. Learn how to implement comprehensive audit logging in 20 minutes.

20 min implementation
12 min read
Logging & Compliance

Why CloudTrail Logging is Business-Critical

AWS CloudTrail records API calls made in your AWS account, creating an audit trail of who did what, when, and where. Without it, you're flying blind when security incidents occur—unable to determine breach scope, trace attacker activity, or prove containment to auditors.

What CloudTrail Records

  • Identity & Access Events: Login attempts, IAM changes, role assumptions
  • Resource Management: EC2 launches, S3 bucket creation, security group changes
  • Data Access Patterns: S3 object access, database connections (with data events enabled)
  • Security Configuration: Changes to encryption, NACLs, and security settings
  • Network Activity: VPC changes, route table updates, subnet modifications
  • Billing Events: Account-level and cost-related API calls
⚠️
Compliance Requirement: Most compliance frameworks explicitly require audit logging—SOC 2, PCI DSS, HIPAA, and GDPR all mandate detailed access logs. Without CloudTrail, you cannot pass these audits.

The Four Critical Risks of Missing CloudTrail

1

Compliance Violations & Regulatory Fines

SOC 2 requires detailed access logs. PCI DSS mandates monitoring of network resources. HIPAA requires PHI access logs. GDPR Article 25 requires logging for data protection. Violations can result in significant fines.

2

Incident Response Paralysis

Without CloudTrail, security incidents become investigations with no evidence. You cannot determine breach scope, identify compromised resources, trace attacker activity, or prove containment to auditors.

3

Insider Threat Blindness

43% of data breaches involve insiders. Without audit logs, you have no way to detect employees accessing data outside their role, unusual login patterns, bulk data downloads, or privilege escalation attempts.

4

Forensic Investigation Gaps

Law enforcement and cyber insurance require detailed forensic evidence. Without CloudTrail, you cannot provide timelines of attacker activities, proof of data access, or documentation for insurance claims.

💡
Cost Reality: For most SMBs, CloudTrail costs less than $25/month—significantly less than the potential cost of a single security incident or compliance violation.
1

Create a Multi-Region Trail

~8 minutes

Prerequisites

  • AWS account with administrative access
  • Basic understanding of S3 buckets
  • Decision on AWS region for log storage (recommend us-east-1 or your primary region)

Console Steps

1.1 Navigate to CloudTrail

  • Sign in to AWS Console with admin credentials
  • Search for CloudTrail in the services search bar
  • Click on CloudTrail to open the service console

1.2 Create Trail

  • Click the Create trail button
  • Trail name: company-security-audit-trail
  • Enable Enable for all accounts in my organization if using AWS Organizations
  • Check Apply trail to all regions (critical for comprehensive coverage)
⚠️
Critical: Always enable "Apply trail to all regions" to capture activity across your entire AWS footprint, even in regions you don't actively use. Attackers often target unused regions.

1.3 Configure S3 Storage Location

  • Choose Create new S3 bucket
  • S3 bucket name: company-cloudtrail-logs-[random-suffix]
  • Keep Log file SSE-S3 encryption enabled
  • Enable Log file validation (recommended)
AWS CLI Alternative
# Create trail via AWS CLI
aws cloudtrail create-trail \
    --name company-security-audit-trail \
    --s3-bucket-name company-cloudtrail-logs-unique-suffix \
    --include-global-service-events \
    --is-multi-region-trail \
    --enable-log-file-validation

# Start logging
aws cloudtrail start-logging \
    --name company-security-audit-trail

1.4 Advanced Settings

  • Log file validation: Enable (detects tampering)
  • SNS notification: Skip for now (can add later)
  • CloudWatch Logs: We'll configure this in Step 4
  • Tags: Add tags like Environment=Production, Purpose=Security

1.5 Review and Create

  • Review all settings carefully
  • Estimated cost should be shown (typically $2-5/month for small environments)
  • Click Create trail
Success! Your CloudTrail is now created and logging is automatically started. Events will begin appearing in your S3 bucket within 15 minutes.
2

Secure the S3 Bucket

~5 minutes

Securing your CloudTrail S3 bucket is crucial—these logs contain sensitive information about your AWS environment and could be targeted by attackers trying to cover their tracks.

Console Steps

2.1 Navigate to Your CloudTrail S3 Bucket

  • Go to S3 service in AWS Console
  • Find your CloudTrail bucket (company-cloudtrail-logs-xxx)
  • Click on the bucket name to enter it

2.2 Verify Public Access Settings

  • Click on the Permissions tab
  • Under Block public access, verify ALL options are enabled:
  • Block all public ACLs ✓
  • Ignore public ACLs ✓
  • Block public bucket policies ✓
  • Block public and cross-account access ✓
⚠️
Critical: CloudTrail logs should NEVER be publicly accessible. Verify all public access blocking is enabled to prevent accidental exposure.

2.3 Configure Bucket Policy

  • In the Permissions tab, scroll to Bucket policy
  • Click Edit and add a restrictive policy
  • Replace YOUR-BUCKET-NAME and YOUR-ACCOUNT-ID with your values
Secure Bucket Policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AWSCloudTrailAclCheck",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudtrail.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME"
        },
        {
            "Sid": "AWSCloudTrailWrite",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudtrail.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/AWSLogs/YOUR-ACCOUNT-ID/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        },
        {
            "Sid": "DenyUnSecureCommunications",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::YOUR-BUCKET-NAME",
                "arn:aws:s3:::YOUR-BUCKET-NAME/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "false"
                }
            }
        }
    ]
}

2.4 Enable Versioning

  • Go to Properties tab
  • Find Bucket Versioning and click Edit
  • Select Enable
  • For production environments, consider enabling MFA Delete via CLI

2.5 Set Up Lifecycle Management

  • In Management tab, click Create lifecycle rule
  • Rule name: cloudtrail-log-lifecycle
  • Apply to all objects in bucket
  • Configure transitions for cost optimization:
  • Move to Standard-IA after 30 days (40% cost reduction)
  • Move to Glacier after 90 days (80% cost reduction)
  • Delete after 7 years (adjust based on compliance needs)
Security Improved! Your CloudTrail bucket is now properly secured against unauthorized access and configured for cost-effective long-term storage.
3

Enable Log File Validation

~2 minutes

Log file validation creates digital signatures for your CloudTrail logs, allowing you to detect if logs have been tampered with—crucial for forensic investigations and compliance.

Console Steps

3.1 Verify Validation is Enabled

  • Return to CloudTrail service console
  • Click on your trail name (company-security-audit-trail)
  • In the General details section, verify Log file validation shows Enabled
  • If not enabled, click Edit and enable it

3.2 Understanding Log File Validation

  • CloudTrail creates a hash (digest) file every hour
  • Digest files contain hashes of all log files delivered in that hour
  • Digest files are stored in the same S3 bucket under /CloudTrail-Digest/
  • You can validate log integrity using AWS CLI tools
Validate Log Integrity
# Validate log file integrity using AWS CLI
aws cloudtrail validate-logs \
    --trail-arn arn:aws:cloudtrail:REGION:ACCOUNT-ID:trail/trail-name \
    --start-time 2026-01-01T00:00:00Z \
    --end-time 2026-01-02T00:00:00Z

# Example output shows validation results:
# Results for s3://bucket/AWSLogs/123456789012/CloudTrail/us-east-1/2026/01/01/
# 2026-01-01T00:05:00Z - 2026-01-01T01:00:00Z: VALID
# 2026-01-01T01:05:00Z - 2026-01-01T02:00:00Z: VALID
📋
Compliance Note: Many audit frameworks require tamper-evident logging. Log file validation provides cryptographic proof that your audit logs haven't been modified, which is essential for legal and compliance purposes.
Forensic Capability Added! Your CloudTrail logs now have cryptographic integrity verification, essential for incident response and compliance audits.
4

Set Up CloudWatch Integration

~5 minutes

Integrating CloudTrail with CloudWatch allows real-time monitoring and alerting on security events, transforming your audit logs from passive recordings into active security monitoring.

Console Steps

4.1 Create CloudWatch Log Group

  • Navigate to CloudWatch service in AWS Console
  • Click Log groups in the left sidebar
  • Click Create log group
  • Log group name: CloudTrail/SecurityAuditLogs
  • Retention setting: 30 days (adjust based on needs and budget)
  • Click Create

4.2 Create IAM Role for CloudTrail

  • Go to IAM service → Roles → Create role
  • Select AWS serviceCloudTrail
  • Attach policy: CloudWatchLogsDeliveryRolePolicy
  • Role name: CloudTrailLogsRole
  • Create the role

4.3 Configure CloudTrail to Send Logs

  • Return to CloudTrail service
  • Select your trail and click Edit
  • Scroll to CloudWatch Logs section
  • Check Enabled
  • Log group: Select the group you created
  • IAM role: Select CloudTrailLogsRole
  • Click Save changes

4.4 Create Security Alert Metric Filters

  • In CloudWatch, go to LogsLog groups
  • Select your CloudTrail log group
  • Click Create metric filter
  • Create filters for critical events (see patterns below)
Critical Security Metric Filters
# Root account usage filter
{ ($.userIdentity.type = "Root") && ($.userIdentity.invokedBy NOT EXISTS) && ($.eventType != "AwsServiceEvent") }

# Failed console logins filter
{ ($.eventName = ConsoleLogin) && ($.errorMessage EXISTS) }

# IAM policy changes filter
{ ($.eventSource = iam.amazonaws.com) && (($.eventName = DeleteUserPolicy) || ($.eventName = DeleteRolePolicy) || ($.eventName = DeleteGroupPolicy) || ($.eventName = CreatePolicy) || ($.eventName = CreateRole) || ($.eventName = CreateUser)) }

# Security group changes filter
{ ($.eventName = AuthorizeSecurityGroupIngress) || ($.eventName = AuthorizeSecurityGroupEgress) || ($.eventName = RevokeSecurityGroupIngress) || ($.eventName = RevokeSecurityGroupEgress) || ($.eventName = CreateSecurityGroup) || ($.eventName = DeleteSecurityGroup) }

# CloudTrail configuration changes
{ ($.eventSource = cloudtrail.amazonaws.com) && (($.eventName = StopLogging) || ($.eventName = DeleteTrail) || ($.eventName = UpdateTrail)) }

4.5 Set Up SNS Notifications

  • Go to SNS service → Topics → Create topic
  • Topic name: security-alerts
  • Add email subscription for your security team
  • Return to CloudWatch and create alarms for each metric filter
  • Set threshold to 1 occurrence and connect to SNS topic
Real-time Monitoring Active! You now have real-time alerting on critical security events. Your team will be notified within minutes of suspicious activity.

Validate Your Configuration

Complete these checks to ensure your CloudTrail is properly configured and functioning:

Validation Script

cloudtrail-validation.sh
#!/bin/bash
# CloudTrail Configuration Validation Script

echo "Validating CloudTrail configuration..."

# Check if trails exist
TRAILS=$(aws cloudtrail describe-trails --query 'trailList[*].Name' --output text)
if [ -z "$TRAILS" ]; then
    echo "✗ No CloudTrail found!"
    exit 1
else
    echo "✓ CloudTrail found: $TRAILS"
fi

# Check multi-region configuration
MULTIREGION=$(aws cloudtrail describe-trails --query 'trailList[*].IsMultiRegionTrail' --output text)
if [[ "$MULTIREGION" == *"True"* ]]; then
    echo "✓ Multi-region trail configured"
else
    echo "✗ WARNING: Trail not configured for all regions!"
fi

# Check logging status
for TRAIL in $TRAILS; do
    LOGGING=$(aws cloudtrail get-trail-status --name $TRAIL --query 'IsLogging' --output text)
    if [ "$LOGGING" = "True" ]; then
        echo "✓ CloudTrail logging is active for $TRAIL"
    else
        echo "✗ WARNING: CloudTrail logging is not active for $TRAIL!"
    fi
done

# Check log file validation
VALIDATION=$(aws cloudtrail describe-trails --query 'trailList[*].LogFileValidationEnabled' --output text)
if [[ "$VALIDATION" == *"True"* ]]; then
    echo "✓ Log file validation enabled"
else
    echo "! Log file validation not enabled"
fi

# Check recent log delivery
for TRAIL in $TRAILS; do
    RECENT_DELIVERY=$(aws cloudtrail get-trail-status --name $TRAIL --query 'LatestDeliveryTime' --output text)
    if [ "$RECENT_DELIVERY" != "None" ] && [ -n "$RECENT_DELIVERY" ]; then
        echo "✓ Recent log delivery confirmed: $RECENT_DELIVERY"
    else
        echo "! No recent log delivery detected for $TRAIL"
    fi
done

echo ""
echo "CloudTrail validation complete!"

Test Your Setup

Perform these activities to generate test events and verify detection:

Generate Test Events
# Generate test events to verify logging

# 1. Create and delete a test security group
aws ec2 create-security-group \
    --group-name test-cloudtrail-sg \
    --description "Test CloudTrail logging"

aws ec2 delete-security-group --group-name test-cloudtrail-sg

# 2. Check CloudTrail logs in S3 (wait 15 minutes)
aws s3 ls s3://your-cloudtrail-bucket/AWSLogs/ --recursive | head -20

# 3. Query CloudWatch Logs (wait 5 minutes)
aws logs describe-log-streams \
    --log-group-name CloudTrail/SecurityAuditLogs \
    --order-by LastEventTime \
    --descending \
    --limit 5

Common Mistakes to Avoid

Single-region trails only. Always enable multi-region trails to capture activity across your entire AWS footprint—attackers often target unused regions.

No log file validation. Without validation, you cannot prove logs haven't been tampered with during forensic investigations or compliance audits.

Overly permissive S3 bucket policies. CloudTrail logs contain sensitive information about your infrastructure and should never be publicly accessible.

No real-time monitoring. Logs sitting in S3 don't help during active incidents—set up CloudWatch integration for immediate alerts.

Inadequate retention policies. Compliance frameworks often require 3-7 years of log retention. Plan for long-term storage with lifecycle policies.

Not testing log delivery. Regularly verify that logs are being delivered and alerts are working—discover problems before you need the logs.

Don't Analyze CloudTrail Logs Manually

CloudTrail generates thousands of events daily. Manual log analysis is impractical and error-prone. AWSight automatically analyzes your CloudTrail logs against 500+ security best practices, providing actionable insights and automated alerting.

References