Skip to content
Visual explainer 3h to learn 4 steps

CloudWatch, CloudTrail & AWS Config

Set up metrics, alarms, audit trails and compliance rules.

By Invicly Tech, , in AWS Solutions Architect – Associate. About 12 minutes to read.

Topic 27 of 34

In short

CloudWatch collects metrics and logs and raises alarms that trigger actions. CloudTrail records who called which AWS API and when. AWS Config records resource configuration over time and checks it against compliance rules.

Explained simply

Monitoring answers three different questions, and AWS has a service for each. Is my system healthy right now? That is CloudWatch, with metrics, logs and alarms. Who did what in my account? That is CloudTrail, a record of API calls. Is my setup still the way it should be? That is AWS Config.

A metric is a number measured over time, like CPU use every minute or the count of 5xx errors. An alarm watches one metric and changes state when it crosses a line for long enough. Alarms can send a message, scale a group of servers, or reboot or recover an instance.

Logs are the detailed story behind the numbers. CloudWatch Logs collects log lines from Lambda, containers, servers and many AWS services in one place. Logs Insights lets you search them with a short query language, for example to count errors per minute or find the slowest requests.

CloudTrail is the security camera of your account. Every console click and API call becomes an event: who, from where, when, and what. AWS Config takes snapshots of each resource's settings over time and checks them against rules, like every EBS volume must be encrypted.

Press Play on a diagram to walk through it one step at a time.

CompareWhich monitoring service
CloudWatch
  • Performance metrics
  • Logs and Logs Insights
  • Alarms and dashboards
  • What is happening now
CloudTrail
  • API call history
  • Who did what, when
  • 90-day event history free
  • Trails to S3 for longer
AWS Config
  • Resource config history
  • Compliance rules
  • Auto remediation
  • What changed and is it allowed
CycleAlarm-driven operations
  1. 1
    Publish metric

    Service or agent sends data points.

  2. 2
    Evaluate alarm

    Threshold breached for N periods.

  3. 3
    Take action

    Notify SNS, scale ASG or recover EC2.

  4. 4
    Return to OK

    Metric recovers and alarm state resets.

  5. Back to step 1
SequenceDetect and fix a public security group rule
Engineer
AWS Config
SSM Automation
Security group
  1. 1Opens port 22 to 0.0.0.0/0
    Engineer to Security group: Opens port 22 to 0.0.0.0/0
  2. 2Configuration change recorded
    Security group to AWS Config: Configuration change recorded
  3. 3Rule restricted-ssh: NON_COMPLIANT
    AWS Config to AWS Config: Rule restricted-ssh: NON_COMPLIANT
  4. 4Run remediation document
    AWS Config to SSM Automation: Run remediation document
  5. 5Remove the open SSH rule
    SSM Automation to Security group: Remove the open SSH rule
  6. 6Re-evaluate: COMPLIANT
    AWS Config to AWS Config: Re-evaluate: COMPLIANT
MapWhich tool answers which question?
Question
  • Is it healthy now?
    • CloudWatch metrics and alarms
  • What went wrong inside the app?
    • CloudWatch Logs and Logs Insights
    • X-Ray traces for request paths
  • Who made this change?
    • CloudTrail event history or trail
  • What did this resource look like before?
    • AWS Config timeline
  • Are we following our rules?
    • Config rules and conformance packs
  • React to an API call right away
    • EventBridge rule on CloudTrail events

In depth

Metrics: resolution, retention and the agent

AWS services publish metrics to CloudWatch automatically. EC2 sends them every 5 minutes for free (basic monitoring) or every minute with detailed monitoring for a fee. Custom metrics can be standard resolution (1 minute) or high resolution (down to 1 second). CloudWatch keeps data for 15 months but rolls it up as it ages: 1-second points for 3 hours, 1-minute points for 15 days, 5-minute points for 63 days and 1-hour points for 455 days.

The hypervisor cannot see inside your instance, so memory use, disk space used and process counts are not default EC2 metrics. Install the CloudWatch agent, usually configured from an SSM Parameter Store parameter, to collect them along with log files. Metrics are grouped by namespace (like AWS/EC2) and dimensions (like InstanceId), and the same metric name with different dimensions is a different metric.

  • Basic EC2 monitoring: 5 minutes. Detailed: 1 minute
  • High-resolution custom metrics: down to 1 second
  • Memory and disk space need the CloudWatch agent
  • Retention: 15 months, with coarser points as data ages

Alarms that don't cry wolf

An alarm checks a statistic (Average, Sum, Maximum, or a percentile like p99) over a period, and goes to ALARM when M out of N recent data points breach the threshold. For example, 3 out of 5 one-minute periods above 80 percent ignores a single spike but still catches sustained trouble. States are OK, ALARM and INSUFFICIENT_DATA, and you choose how missing data counts: missing, notBreaching, breaching or ignore.

Alarm on symptoms users feel, such as error rate and p99 latency, rather than only on causes such as CPU. Composite alarms combine several alarms with AND or OR, which cuts noise: page someone only when errors are high and latency is high. Anomaly detection alarms learn a metric's normal daily shape and fire when it leaves that band, which works well for traffic that changes by hour.

FlowFrom data point to action
  1. 1
    Data points

    One per period, e.g. every 60 s

  2. 2
    Statistic

    Average, Sum, Max or p99

  3. 3
    M of N check

    e.g. 3 of the last 5 breach

  4. 4
    State change

    OK to ALARM

  5. 5
    Actions

    SNS, Auto Scaling, EC2 recover

CloudWatch Logs in practice

Logs are stored in log groups (one per app or function) made of log streams (one per instance or container). By default log groups never expire, which quietly grows your bill, so set a retention such as 30 or 90 days. Metric filters turn log patterns into metrics, for example counting lines containing ERROR, so you can alarm on them. Subscription filters stream log events in near real time to Lambda, Kinesis, Firehose or OpenSearch, which is how you centralise logs from many accounts.

Logs Insights queries look like this: fields @timestamp, @message | filter @message like /ERROR/ | stats count() by bin(5m). You pay per GB scanned, so narrow the time range. For long-term, cheap storage, export logs to S3 or deliver them there with Firehose. Lambda writes to CloudWatch Logs automatically; EC2 needs the agent.

CloudTrail: the audit record

Event history shows the last 90 days of management events (actions that create, change or delete resources, and many reads) in each Region for free, with no setup. For longer retention and analysis, create a trail that delivers log files to an S3 bucket, usually within about 5 minutes of the call, and optionally to CloudWatch Logs for alarms. An organization trail created in the management account records every account.

Data events are off by default because they are high volume and cost extra: S3 object reads and writes, Lambda invocations, DynamoDB item actions. Turn them on for sensitive buckets. CloudTrail Insights detects unusual API activity, such as a sudden burst of TerminateInstances calls. Log file integrity validation adds signed digest files, so you can prove logs were not altered. Protect the trail bucket with a strict bucket policy, ideally in a separate logging account.

SequenceTracing who deleted a bucket
User
Amazon S3
CloudTrail
Security team
  1. 1DeleteBucket logs-old
    User to Amazon S3: DeleteBucket logs-old
  2. 2Management event recorded
    Amazon S3 to CloudTrail: Management event recorded
  3. 3Delivered to trail bucket, about 5 min
    CloudTrail to CloudTrail: Delivered to trail bucket, about 5 min
  4. 4lookup-events EventName=DeleteBucket
    Security team to CloudTrail: lookup-events EventName=DeleteBucket
  5. 5userIdentity, sourceIPAddress, eventTime
    CloudTrail to Security team: userIdentity, sourceIPAddress, eventTime

AWS Config: drift and compliance

Once the configuration recorder is on, Config records a configuration item every time a supported resource changes, building a timeline: what this security group looked like last Tuesday, and which resources it was attached to. Config rules evaluate resources against a desired state, either when a resource changes or on a schedule. AWS provides hundreds of managed rules, such as encrypted-volumes, restricted-ssh and s3-bucket-public-read-prohibited, and you can write custom rules with Lambda or Guard.

Config detects; it does not block. To fix things automatically, attach a remediation action, an SSM Automation document that, for example, turns on bucket encryption. Conformance packs bundle rules for a standard, and an aggregator shows compliance across accounts and Regions. To prevent bad changes in the first place, use SCPs or IAM. Config is Regional and charges per configuration item recorded and per rule evaluation.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Create CloudWatch metrics and alarms~45m
  2. 2
    Centralise logs with CloudWatch Logs~45m
  3. 3
    Audit API calls with CloudTrail~45m
  4. 4
    Track compliance with AWS Config rules~45m

Key points

  • EC2 memory and disk usage need the CloudWatch agent; they are not default metrics.
  • Create an organization trail to log all accounts into one S3 bucket.
  • Use Config rules to detect, for example, unencrypted EBS volumes.
  • EventBridge can react to CloudTrail API events in near real time.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
aws cloudwatch put-metric-alarm \
  --alarm-name web-high-cpu \
  --namespace AWS/EC2 --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-0abc123 \
  --statistic Average --period 300 \
  --evaluation-periods 2 --threshold 80 \
  --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:us-east-1:123456789012:ops

Alarm when average CPU stays above 80 percent for 10 minutes.

Alarm on application errors found in logs

An app writes lines like level=ERROR to the log group /app/web, and the team wants a page when errors pass 10 per minute for 3 minutes. Step 1: create a metric filter that counts matching lines into a custom metric. Step 2: create an alarm on that metric with Sum over 60-second periods, 3 of 3 data points, treating missing data as not breaching because no errors means no data. Step 3: send the alarm to an SNS topic that pages the on-call engineer.

bash
aws logs put-metric-filter --log-group-name /app/web --filter-name errors \
  --filter-pattern '"level=ERROR"' \
  --metric-transformations metricName=AppErrors,metricNamespace=MyApp,metricValue=1

aws cloudwatch put-metric-alarm --alarm-name web-errors-high \
  --namespace MyApp --metric-name AppErrors --statistic Sum --period 60 \
  --evaluation-periods 3 --datapoints-to-alarm 3 --threshold 10 \
  --comparison-operator GreaterThanThreshold --treat-missing-data notBreaching \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:oncall

Find who opened SSH to the world

A Config rule flagged a security group with port 22 open to 0.0.0.0/0. Step 1: ask CloudTrail for recent AuthorizeSecurityGroupIngress calls to see who made the change, when and from which IP. Step 2: open the Config timeline for the security group to see the exact rule added and every resource attached to it. Step 3: remove the rule, then add automatic remediation to the Config rule so it is fixed within minutes next time.

bash
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress \
  --max-results 5 --query 'Events[].[EventTime,Username,CloudTrailEvent]'

aws configservice get-resource-config-history \
  --resource-type AWS::EC2::SecurityGroup --resource-id sg-0abc1234 --limit 3

Quick reference

  • CloudWatch = performance now. CloudTrail = who called which API. Config = settings history and rules
  • EC2 basic metrics every 5 min; detailed every 1 min; memory and disk need the agent
  • Alarm states: OK, ALARM, INSUFFICIENT_DATA; use M of N data points to avoid noise
  • Log groups never expire by default; set retention: aws logs put-retention-policy
  • CloudTrail event history: 90 days of management events, free, per Region
  • S3 object and Lambda invoke activity are data events: off by default, extra cost
  • Config detects drift; remediate with SSM Automation; prevent with SCPs or IAM
  • React to an API call in near real time: EventBridge rule on CloudTrail events

Common mistakes

  • Using CloudTrail to monitor CPU, or CloudWatch to find who deleted a bucket.
  • Expecting memory metrics from EC2 without installing the agent.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You need to know how much memory EC2 instances use. What do you do?

Question 2

2An alarm fires on single short CPU spikes and wakes people up for nothing. What is the best change?

Question 3

3Security wants a record of every GetObject call on one sensitive bucket. What must be enabled?

Question 4

4Which service shows how a security group's rules looked last week?

Question 5

5CloudWatch Logs costs keep growing although traffic is flat. What is the most likely cause?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Set a 30-day retention on every log group in a Region that currently has none.

  2. Exercise 2medium

    Write a Logs Insights query that shows the 10 slowest requests in the last hour from a JSON log with fields path and latency_ms, and the error count per 5 minutes.

  3. Exercise 3hard

    Create a multi-Region trail with log file validation to a dedicated bucket, then add an EventBridge rule that notifies you whenever someone calls StopLogging.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between CloudWatch and CloudTrail?
CloudWatch measures how resources and apps perform and holds their logs. CloudTrail records API calls, so it tells you who did something, not how fast the system is.
Is CloudTrail on by default?
Yes, event history keeps 90 days of management events for free in each Region. For longer storage, data events or delivery to S3, you create a trail.
Does AWS Config stop non-compliant changes?
No. Config detects and records them, and can trigger automatic remediation afterwards. To block changes up front, use SCPs, IAM policies or CloudFormation Guard checks in your pipeline.
How long does CloudWatch keep metrics?
Up to 15 months, but older data is stored at coarser resolution: 1-minute points for 15 days, 5-minute points for 63 days, and 1-hour points after that.

Go deeper

ShareXLinkedInWhatsApp