TExcelTAD
Home › AWS Cloud › CloudTrail and AWS Config

CloudTrail and AWS Config

CloudWatch answers "how is my system performing?". Two other services answer governance questions:

  • AWS CloudTrail: who did what, when, from where? It records API calls made in your account.
  • AWS Config: what does my infrastructure look like, how did it change, and is it compliant? It records resource configurations over time and evaluates rules.

AWS CloudTrail

Every action in AWS, whether from the console, the CLI, an SDK or another AWS service, is an API call. CloudTrail records it as an event: the caller's identity, the time, the source IP, the request parameters and the response.

  • Event history: the last 90 days of management events, free and on by default.
  • Trails: deliver events continuously to an S3 bucket (and optionally CloudWatch Logs) for long-term storage and analysis. Create an organization trail covering all accounts and Regions.
  • Management events (create/delete/modify resources) vs data events (high-volume object-level operations like s3:GetObject and Lambda invokes, opt-in and paid).
  • CloudTrail Lake: store and query events with SQL.
bash
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=DeleteBucket \
    --max-results 1 --query "Events[0].CloudTrailEvent" --output text

Sample output (one event, shortened):

text
{"eventVersion":"1.10","userIdentity":{"type":"IAMUser","arn":"arn:aws:iam::123456789012:user/linus","userName":"linus"},
 "eventTime":"2026-03-02T09:41:17Z","eventSource":"s3.amazonaws.com","eventName":"DeleteBucket",
 "awsRegion":"eu-west-1","sourceIPAddress":"198.51.100.23","requestParameters":{"bucketName":"tad-old-exports"}}

Model: investigating with CloudTrail events

A security review often starts with questions like "who deleted things?" and "were there failed console logins?". With events as JSON, the answers are a few lines of code:

python · try it yourself
import json
from collections import Counter

raw = """
{"eventTime":"2026-03-02T09:12:03Z","eventName":"ConsoleLogin","userIdentity":{"userName":"grace"},"sourceIPAddress":"198.51.100.10","errorMessage":null}
{"eventTime":"2026-03-02T09:30:44Z","eventName":"ConsoleLogin","userIdentity":{"userName":"admin"},"sourceIPAddress":"203.0.113.66","errorMessage":"Failed authentication"}
{"eventTime":"2026-03-02T09:30:51Z","eventName":"ConsoleLogin","userIdentity":{"userName":"admin"},"sourceIPAddress":"203.0.113.66","errorMessage":"Failed authentication"}
{"eventTime":"2026-03-02T09:41:17Z","eventName":"DeleteBucket","userIdentity":{"userName":"linus"},"sourceIPAddress":"198.51.100.23","errorMessage":null}
{"eventTime":"2026-03-02T10:02:09Z","eventName":"TerminateInstances","userIdentity":{"userName":"linus"},"sourceIPAddress":"198.51.100.23","errorMessage":null}
{"eventTime":"2026-03-02T10:05:30Z","eventName":"PutBucketPolicy","userIdentity":{"userName":"grace"},"sourceIPAddress":"198.51.100.10","errorMessage":null}
"""
events = [json.loads(line) for line in raw.strip().splitlines()]

destructive = [e for e in events if e["eventName"].startswith(("Delete", "Terminate"))]
print("destructive actions:")
for e in destructive:
    print(f"  {e['eventTime']} {e['userIdentity']['userName']:<6} {e['eventName']}")

failed = Counter(e["sourceIPAddress"] for e in events
                 if e["eventName"] == "ConsoleLogin" and e["errorMessage"])
print("failed console logins per IP:", dict(failed))
print("actions per user:", dict(Counter(e["userIdentity"]["userName"] for e in events)))
destructive actions:
  2026-03-02T09:41:17Z linus  DeleteBucket
  2026-03-02T10:02:09Z linus  TerminateInstances
failed console logins per IP: {'203.0.113.66': 2}
actions per user: {'grace': 2, 'admin': 2, 'linus': 2}

Tip: Protect the trail itself: store logs in a separate, locked-down logging account, enable log file integrity validation, and alert on StopLogging and DeleteTrail events.

AWS Config

AWS Config keeps a configuration history of supported resources (security groups, buckets, instances, IAM roles...) and evaluates Config rules against them. Rules can be AWS managed (e.g. s3-bucket-public-read-prohibited, encrypted-volumes, restricted-ssh) or custom (a Lambda function or Guard policy). Non-compliant resources can be fixed automatically with remediation actions (Systems Manager documents). Conformance packs bundle rules for standards like CIS or PCI.

bash
aws configservice describe-compliance-by-config-rule --config-rule-names restricted-ssh encrypted-volumes

Sample output (shortened):

text
{
    "ComplianceByConfigRules": [
        {"ConfigRuleName": "restricted-ssh", "Compliance": {"ComplianceType": "NON_COMPLIANT"}},
        {"ConfigRuleName": "encrypted-volumes", "Compliance": {"ComplianceType": "COMPLIANT"}}
    ]
}

Model: Config rules over a resource inventory

python · try it yourself
resources = [
    {"id": "sg-0web", "type": "SecurityGroup", "ingress": [(443, "0.0.0.0/0")]},
    {"id": "sg-0bastion", "type": "SecurityGroup", "ingress": [(22, "0.0.0.0/0")]},
    {"id": "vol-01", "type": "Volume", "encrypted": True},
    {"id": "vol-02", "type": "Volume", "encrypted": False},
    {"id": "tad-media", "type": "Bucket", "public_read": False, "versioning": True},
    {"id": "tad-tmp", "type": "Bucket", "public_read": True, "versioning": False},
]

RULES = {
    "restricted-ssh": ("SecurityGroup", lambda r: not any(p == 22 and c == "0.0.0.0/0" for p, c in r["ingress"])),
    "encrypted-volumes": ("Volume", lambda r: r["encrypted"]),
    "s3-bucket-public-read-prohibited": ("Bucket", lambda r: not r["public_read"]),
    "s3-bucket-versioning-enabled": ("Bucket", lambda r: r["versioning"]),
}

total = compliant = 0
for rule, (rtype, check) in RULES.items():
    for r in (x for x in resources if x["type"] == rtype):
        ok = check(r)
        total += 1
        compliant += ok
        if not ok:
            print(f"NON_COMPLIANT  {rule:<34} {r['id']}")
print(f"compliance: {compliant}/{total} evaluations ({compliant / total:.0%})")
NON_COMPLIANT  restricted-ssh                     sg-0bastion
NON_COMPLIANT  encrypted-volumes                  vol-02
NON_COMPLIANT  s3-bucket-public-read-prohibited   tad-tmp
NON_COMPLIANT  s3-bucket-versioning-enabled       tad-tmp
compliance: 4/8 evaluations (50%)

Model: configuration timeline

Config answers "what did this security group look like last Tuesday?". It stores a configuration item each time a resource changes:

python · try it yourself
timeline = [   # (time, configuration of sg-0bastion)
    ("2026-02-20T08:00Z", {"ingress": ["22 from 198.51.100.0/24"]}),
    ("2026-03-01T17:45Z", {"ingress": ["22 from 198.51.100.0/24", "22 from 0.0.0.0/0"]}),
    ("2026-03-02T09:10Z", {"ingress": ["22 from 198.51.100.0/24"]}),
]

def config_at(when):
    current = None
    for t, cfg in timeline:
        if t <= when:
            current = cfg
    return current

for when in ["2026-02-25T12:00Z", "2026-03-01T23:00Z", "2026-03-02T12:00Z"]:
    print(when, config_at(when))
2026-02-25T12:00Z {'ingress': ['22 from 198.51.100.0/24']}
2026-03-01T23:00Z {'ingress': ['22 from 198.51.100.0/24', '22 from 0.0.0.0/0']}
2026-03-02T12:00Z {'ingress': ['22 from 198.51.100.0/24']}

Combined with CloudTrail you can see who opened SSH to the world on the evening of 1 March (CloudTrail's AuthorizeSecurityGroupIngress event) and what the rule looked like (Config).

CloudWatch vs CloudTrail vs Config

Question Service
Is CPU high? Are there errors in my logs? CloudWatch
Who deleted this bucket? CloudTrail
Is every volume encrypted? What did this resource look like last week? AWS Config

Go further: Cloud Audit Logs compares CloudTrail with Azure and GCP audit logs, and Cloud Detections writes rules on them.

Test yourself

Which service tells you which IAM user terminated an EC2 instance?

  1. CloudWatch metrics
  2. AWS CloudTrail
  3. AWS Config
  4. Amazon Inspector

Which service checks continuously whether all EBS volumes are encrypted?

  1. AWS Config with the encrypted-volumes rule
  2. CloudTrail event history
  3. CloudFront
  4. AWS Budgets

How long does CloudTrail event history keep management events by default?

  1. 24 hours
  2. 7 days
  3. 90 days
  4. Forever