Back to Blog
CloudTrail for ML Audit Trails: Complete Compliance Setup
Technical Guide·10 min read·

CloudTrail for ML Audit Trails: Complete Compliance Setup

C

Claw GRC Team

Claw GRC Team

How to configure AWS CloudTrail for ML audit trails covering SageMaker and Bedrock API logging, KMS encryption, S3 log validation, and Athena queries mapped to SOC 2, NIST 800-53, and ISO 27001.

CloudTrail for ML Audit Trails: Complete Compliance Setup

Every compliance framework requires audit trails. SOC 2 CC5.1 requires monitoring of controls. NIST 800-53 AU-2 requires event logging. ISO 27001 A.8.15 requires activity monitoring. When your workloads include machine learning models and LLM applications, those audit requirements extend to every SageMaker training job, every Bedrock model invocation, every model deployment, and every data access operation.

AWS CloudTrail is the foundation of audit logging on AWS. It records API calls across your account, including who made the call, when, from where, and what parameters were passed. For ML workloads, CloudTrail captures the full lifecycle: data preparation, model training, model deployment, inference, monitoring, and decommissioning. The challenge is configuring it correctly, encrypting the logs, validating their integrity, and extracting the evidence your auditors need.

This guide walks through complete CloudTrail setup for ML compliance, from multi-region trail configuration to Athena-based evidence extraction.


Why CloudTrail Matters for ML Compliance

CloudTrail is not optional for ML governance. It is the only AWS service that provides a tamper-evident, chronological record of every API call made against your AI services. Without it, you cannot answer basic audit questions:

  • Who created the SageMaker training job that produced model version 3.1?
  • When was the Bedrock guardrail configuration last modified, and by whom?
  • Which IAM role deployed the model endpoint to production?
  • Did anyone access the training data S3 bucket outside of the ML pipeline?
  • Were there any unauthorized attempts to invoke the Bedrock model?

These questions map directly to compliance requirements. SOC 2 CC7.1 requires that you monitor your systems for anomalies. NIST 800-53 AU-3 requires that audit records contain sufficient information to establish what occurred, when, where, and who was responsible. ISO 27001 A.8.15 requires monitoring activities to detect unauthorized behavior.

For a broader view of how CloudTrail fits into the AWS AI governance landscape, see the Complete Guide to AWS AI/ML Governance. For detailed IAM and security controls, see AWS Cloud Security for AI Compliance.


Configuring a Multi-Region Trail for ML Workloads

A single-region trail leaves gaps. SageMaker training jobs can run in any region. Bedrock models are available in specific regions, and teams may use different regions for different models. A multi-region trail captures everything, regardless of where the API call originates.

# Create a KMS key for CloudTrail log encryption
aws kms create-key \
  --description "CloudTrail ML audit log encryption key" \
  --key-usage ENCRYPT_DECRYPT \
  --origin AWS_KMS \
  --tags '[
    {"TagKey": "compliance", "TagValue": "soc2-cc6.7"},
    {"TagKey": "purpose", "TagValue": "cloudtrail-ml-audit"}
  ]'

# Create the KMS alias for easier reference
aws kms create-alias \
  --alias-name alias/cloudtrail-ml-audit \
  --target-key-id <key-id-from-above>

# Create the multi-region trail
aws cloudtrail create-trail \
  --name ml-governance-audit-trail \
  --s3-bucket-name ml-audit-logs-123456789 \
  --s3-key-prefix cloudtrail/ml-governance \
  --is-multi-region-trail \
  --include-global-service-events \
  --enable-log-file-validation \
  --kms-key-id alias/cloudtrail-ml-audit \
  --tags-list '[
    {"Key": "compliance", "Value": "soc2-cc5.1,nist-au-2,iso27001-a.8.15"},
    {"Key": "data-classification", "Value": "audit-sensitive"}
  ]'

# Start logging
aws cloudtrail start-logging \
  --name ml-governance-audit-trail

Three configuration flags are non-negotiable for compliance:

  • --is-multi-region-trail: Captures API calls in all regions. Without this, a SageMaker training job launched in eu-west-1 while your trail only covers us-east-1 would be invisible to auditors.
  • --enable-log-file-validation: Creates a digest file every hour that allows you to verify log files have not been tampered with. NIST 800-53 AU-9 (protection of audit information) requires this.
  • --kms-key-id: Encrypts log files at rest with a customer-managed key. SOC 2 CC6.7 requires encryption of sensitive data, and audit logs are sensitive data.

Enabling Data Event Logging for SageMaker and Bedrock

By default, CloudTrail only captures management events (control plane operations like CreateModel, CreateEndpoint). For comprehensive ML audit trails, you also need data events -- the actual invocations of your models and access to your training data.

# Enable data events for SageMaker and Bedrock
aws cloudtrail put-event-selectors \
  --trail-name ml-governance-audit-trail \
  --advanced-event-selectors '[
    {
      "Name": "SageMaker-Management-Events",
      "FieldSelectors": [
        {"Field": "eventCategory", "Equals": ["Management"]},
        {"Field": "eventSource", "Equals": ["sagemaker.amazonaws.com"]}
      ]
    },
    {
      "Name": "Bedrock-Management-Events",
      "FieldSelectors": [
        {"Field": "eventCategory", "Equals": ["Management"]},
        {"Field": "eventSource", "Equals": ["bedrock.amazonaws.com"]}
      ]
    },
    {
      "Name": "Bedrock-Runtime-Data-Events",
      "FieldSelectors": [
        {"Field": "eventCategory", "Equals": ["Data"]},
        {"Field": "eventSource", "Equals": ["bedrock.amazonaws.com"]},
        {"Field": "readOnly", "Equals": ["true", "false"]}
      ]
    },
    {
      "Name": "SageMaker-Runtime-Data-Events",
      "FieldSelectors": [
        {"Field": "eventCategory", "Equals": ["Data"]},
        {"Field": "eventSource", "Equals": ["sagemaker.amazonaws.com"]},
        {"Field": "readOnly", "Equals": ["true", "false"]}
      ]
    },
    {
      "Name": "Training-Data-S3-Access",
      "FieldSelectors": [
        {"Field": "eventCategory", "Equals": ["Data"]},
        {"Field": "eventSource", "Equals": ["s3.amazonaws.com"]},
        {"Field": "resources.ARN", "StartsWith": [
          "arn:aws:s3:::ml-data/",
          "arn:aws:s3:::ml-artifacts/",
          "arn:aws:s3:::ml-governance/"
        ]}
      ]
    }
  ]'

This configuration captures five categories of events:

  1. SageMaker management events: CreateTrainingJob, CreateModel, CreateEndpoint, UpdateEndpoint, DeleteEndpoint, CreateModelCard, and all other control plane operations.
  2. Bedrock management events: CreateGuardrail, UpdateGuardrail, CreateModelCustomizationJob, and other configuration operations.
  3. Bedrock runtime data events: InvokeModel, InvokeModelWithResponseStream -- every call to a foundation model, with request metadata.
  4. SageMaker runtime data events: InvokeEndpoint calls to your deployed models.
  5. S3 data events: GetObject, PutObject on your ML data, artifact, and governance buckets -- tracking who accessed training data and model artifacts.

Cost Warning: Data events generate significantly more log volume than management events. Bedrock InvokeModel data events alone can produce thousands of log entries per hour for a production application. See the cost optimization section below for strategies to manage this.


S3 Log File Validation and Integrity

Log file validation is the feature that makes CloudTrail logs admissible as audit evidence. Without validation, an adversary (or a misconfigured automation) could modify or delete log files, and you would have no way to detect the tampering.

When --enable-log-file-validation is set, CloudTrail produces a digest file every hour. The digest contains a hash of each log file delivered during that period. To validate, use the AWS CLI.

# Validate log file integrity for the past 7 days
aws cloudtrail validate-logs \
  --trail-arn arn:aws:cloudtrail:us-east-1:123456789:trail/ml-governance-audit-trail \
  --start-time "2026-04-28T00:00:00Z" \
  --end-time "2026-05-05T00:00:00Z" \
  --verbose

# Expected output for a clean validation:
# Results requested for 2026-04-28T00:00:00Z to 2026-05-05T00:00:00Z
# Results found for 2026-04-28T00:00:00Z to 2026-05-05T00:00:00Z:
# 168/168 digest files valid
# 4,231/4,231 log files valid

Run this validation on a schedule (weekly is typical for compliance) and store the output as evidence. NIST 800-53 AU-9 requires protection of audit information against unauthorized modification. CloudTrail's digest-based validation is the mechanism that satisfies this requirement.

For additional protection, configure your S3 bucket with Object Lock in compliance mode:

# Enable Object Lock on the audit log bucket (must be set at bucket creation)
aws s3api put-object-lock-configuration \
  --bucket ml-audit-logs-123456789 \
  --object-lock-configuration '{
    "ObjectLockEnabled": "Enabled",
    "Rule": {
      "DefaultRetention": {
        "Mode": "COMPLIANCE",
        "Years": 3
      }
    }
  }'

Compliance mode Object Lock prevents anyone -- including the root account -- from deleting or modifying log files during the retention period. This is the strongest protection available for audit evidence on AWS.


Athena Queries for Audit Evidence Extraction

When an auditor requests evidence, you need to extract specific events from potentially millions of log entries. AWS Athena lets you run SQL queries against CloudTrail logs stored in S3 without any infrastructure to manage.

First, create an Athena table for your CloudTrail logs:

CREATE EXTERNAL TABLE cloudtrail_ml_audit (
    eventVersion STRING,
    userIdentity STRUCT<
        type: STRING,
        principalId: STRING,
        arn: STRING,
        accountId: STRING,
        invokedBy: STRING,
        accessKeyId: STRING,
        userName: STRING,
        sessionContext: STRUCT<
            attributes: STRUCT<
                mfaAuthenticated: STRING,
                creationDate: STRING>,
            sessionIssuer: STRUCT<
                type: STRING,
                principalId: STRING,
                arn: STRING,
                accountId: STRING,
                userName: STRING>>>,
    eventTime STRING,
    eventSource STRING,
    eventName STRING,
    awsRegion STRING,
    sourceIPAddress STRING,
    userAgent STRING,
    errorCode STRING,
    errorMessage STRING,
    requestParameters STRING,
    responseElements STRING,
    additionalEventData STRING,
    requestId STRING,
    eventId STRING,
    resources ARRAY<STRUCT<
        arn: STRING,
        accountId: STRING,
        type: STRING>>,
    eventType STRING,
    recipientAccountId STRING,
    readOnly STRING
)
PARTITIONED BY (region STRING, year STRING, month STRING, day STRING)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://ml-audit-logs-123456789/cloudtrail/ml-governance/AWSLogs/123456789/CloudTrail/'
TBLPROPERTIES ('classification'='cloudtrail');

Now run targeted queries for specific compliance evidence:

-- SOC 2 CC5.1 Evidence: All SageMaker model deployments in Q1 2026
SELECT
    eventTime,
    eventName,
    userIdentity.arn AS deployer,
    awsRegion,
    JSON_EXTRACT_SCALAR(requestParameters, '$.modelName') AS model_name,
    JSON_EXTRACT_SCALAR(requestParameters, '$.endpointName') AS endpoint_name,
    sourceIPAddress
FROM cloudtrail_ml_audit
WHERE eventSource = 'sagemaker.amazonaws.com'
    AND eventName IN ('CreateModel', 'CreateEndpoint', 'UpdateEndpoint', 'DeleteEndpoint')
    AND eventTime BETWEEN '2026-01-01T00:00:00Z' AND '2026-03-31T23:59:59Z'
ORDER BY eventTime DESC;

-- NIST AU-6 Evidence: All Bedrock guardrail modifications
SELECT
    eventTime,
    eventName,
    userIdentity.arn AS modifier,
    JSON_EXTRACT_SCALAR(requestParameters, '$.name') AS guardrail_name,
    errorCode,
    sourceIPAddress
FROM cloudtrail_ml_audit
WHERE eventSource = 'bedrock.amazonaws.com'
    AND eventName IN ('CreateGuardrail', 'UpdateGuardrail', 'DeleteGuardrail')
ORDER BY eventTime DESC;

-- ISO 27001 A.8.15 Evidence: Unauthorized or failed access attempts
SELECT
    eventTime,
    eventName,
    userIdentity.arn AS caller,
    eventSource,
    errorCode,
    errorMessage,
    sourceIPAddress
FROM cloudtrail_ml_audit
WHERE eventSource IN ('sagemaker.amazonaws.com', 'bedrock.amazonaws.com')
    AND errorCode IS NOT NULL
    AND errorCode IN ('AccessDenied', 'UnauthorizedAccess', 'Client.UnauthorizedAccess')
ORDER BY eventTime DESC
LIMIT 500;

Save these queries as named queries in Athena and schedule them monthly using Amazon EventBridge and a Lambda function. The query results become your monthly audit evidence package.


Cost Optimization for Data Events

Data event logging is essential for compliance but expensive at scale. SageMaker and Bedrock data events are charged at $0.10 per 100,000 events. A production Bedrock application handling 100,000 InvokeModel calls per day generates approximately $3,000 per month in CloudTrail data event charges alone.

Strategies to optimize costs without sacrificing compliance:

Use advanced event selectors to scope data events narrowly. Instead of logging all S3 data events, scope to specific bucket prefixes (as shown in the configuration above). Instead of logging all SageMaker data events, consider whether you truly need InvokeEndpoint logging for low-risk internal models.

Separate trails for different retention periods. Management events (CreateModel, CreateEndpoint) need long-term retention for compliance. Data events (InvokeModel) may only need 90-day retention for security monitoring. Use separate trails with different S3 lifecycle policies.

Use CloudTrail Lake for high-volume querying. If you query CloudTrail logs frequently, CloudTrail Lake's event data store is more cost-effective than Athena for repeated queries. The tradeoff is a per-GB ingestion charge versus per-query charges.

Sample Bedrock invocation logging for cost reduction. If your compliance framework does not require logging every individual model invocation, configure a sampling Lambda that logs every Nth invocation to a separate audit table. Keep full management event logging -- that is non-negotiable.

Compliance Tip: Document your cost optimization decisions and their compliance rationale. If an auditor asks why you are not logging every Bedrock invocation, you need a documented risk acceptance that explains the sampling strategy and confirms it meets your framework requirements. Never silently disable logging.


Compliance Mapping Table

The following table maps CloudTrail capabilities for ML workloads to specific compliance framework requirements.

CloudTrail Capability SOC 2 NIST 800-53 ISO 27001 Evidence Artifact
Multi-region trail CC5.1 (control monitoring) AU-2 (event logging) A.8.15 (logging) Trail configuration
SageMaker management events CC5.1, CC7.1 (monitoring) AU-2 (event logging), AU-3 (content of records) A.8.15 (logging) CloudTrail event history
Bedrock management events CC5.1, CC7.1 (monitoring) AU-2, AU-3 A.8.15 (logging) CloudTrail event history
SageMaker/Bedrock data events CC7.1 (monitoring) AU-2, AU-3, AU-12 (audit generation) A.8.15 (logging) CloudTrail data event logs
S3 data events (training data access) CC7.1, CC6.1 (access control) AU-2, AU-3, AU-12 A.8.15, A.8.3 (access restriction) S3 access logs via CloudTrail
KMS encryption of trail logs CC6.7 (encryption) AU-9 (protection of audit info) A.8.24 (use of cryptography) KMS key policy + trail encryption config
Log file validation (digest) CC7.1 (integrity monitoring) AU-9 (protection of audit info) A.8.15 (logging) Validation output reports
S3 Object Lock (WORM) CC7.1, CC6.7 AU-9 (protection of audit info) A.8.15 (logging) Object Lock configuration
Athena evidence extraction CC5.1 (evidence production) AU-6 (audit review/analysis) A.8.15 (logging) Named query results (CSV/JSON)

Key Takeaway: CloudTrail is the audit backbone. It does not govern your models -- it proves that you governed them. Every SageMaker Model Card creation, every Clarify bias analysis, every Model Monitor execution, every guardrail configuration change is captured in CloudTrail. Without it, your governance program has no evidentiary foundation.


How Claw GRC Auto-Collects CloudTrail Evidence

CloudTrail generates the raw events. Claw GRC transforms them into audit-ready evidence packages.

Automated event collection. Claw GRC continuously ingests CloudTrail events for SageMaker, Bedrock, and related services. Events are classified by type (model lifecycle, data access, configuration change, security event) and indexed for rapid retrieval.

Pre-built audit queries. Instead of writing Athena queries from scratch for each audit, Claw GRC provides pre-built evidence packages for SOC 2, NIST 800-53, and ISO 27001. Request evidence for "NIST AU-2" and Claw GRC produces every relevant CloudTrail event, formatted and filtered for the audit period.

Anomaly detection. Claw GRC applies behavioral analysis to CloudTrail events to detect unusual patterns: unexpected model deployments, off-hours data access, new IAM principals invoking ML services, and spikes in Bedrock invocation errors. Anomalies generate compliance findings that require investigation.

Gap identification. If CloudTrail logging is disabled in a region where SageMaker resources exist, Claw GRC flags the gap. If data event logging is not enabled for a critical model endpoint, Claw GRC creates a remediation finding. These gaps are invisible without automated monitoring.

Retention management. Claw GRC tracks your CloudTrail log retention settings against your compliance requirements. If SOC 2 requires three years of audit logs but your S3 lifecycle policy deletes them after one year, Claw GRC alerts you to the mismatch before an auditor finds it.


Next Steps

Audit trails are the foundation of ML compliance. To build out the full governance stack:

Each guide includes hands-on code examples, compliance mapping tables, and evidence collection strategies you can implement today.


Start your ML audit trail assessment with Claw GRC →

CG

Get started with Claw GRC

AI-native compliance automation. 1,026+ controls. MCP-native. Free workspace, no credit card.

Start Free →