Study guide
Technical reference and lesson notes
Purpose of This Lesson
Amazon EventBridge can evaluate events and invoke targets such as AWS Lambda. This pattern is useful for automation, alerting, compliance workflows, and operational responses to EC2 activity.
A key distinction is important: an EC2 instance state-change notification is an EventBridge event generated when an instance changes state. A CloudTrail API event is generated when an API operation such as StopInstances is called. These are related but different event types and require different event patterns.
Key Concepts
EventBridge rules and event patterns
An EventBridge rule contains an event pattern that determines which events it matches. When an incoming event matches, EventBridge sends it to one or more targets.
A rule can use:
- The default event bus for AWS service events
- A custom event bus for application or organizational events
- Event patterns for filtering
- Scheduled expressions for time-based automation
- Targets such as Lambda, Step Functions, SNS, SQS, API destinations, and Systems Manager Automation
For EC2 state changes, the relevant event commonly looks like this:
{
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"],
"detail": {
"state": ["stopped"]
}
}
This pattern matches stopped instances regardless of instance ID. To target one instance, add an instance ID filter under detail.
EC2 state-change events versus CloudTrail API events
The demonstration uses the EC2 Instance State-change Notification event type. This is not the same as a CloudTrail API event. It indicates that the instance reached a new state, such as stopped, running, or terminated.
A CloudTrail API event records an API operation and its caller. A corresponding EventBridge pattern for an EC2 stop API call could be:
{
"source": ["aws.ec2"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["ec2.amazonaws.com"],
"eventName": ["StopInstances"]
}
}
Use the state-change event when the requirement is to react to the resulting state. Use the CloudTrail pattern when the requirement is to identify the API request, caller, request parameters, or authorization context.
Lambda as an EventBridge target
A Lambda function can receive the complete EventBridge event as a JSON object. The function can extract fields such as:
- Instance ID
- Account ID
- Region
- Event time
- Previous and new state, for state-change events
- API caller identity and request details, for CloudTrail events
EventBridge must be allowed to invoke the Lambda function. When Lambda is selected as a target through the console, the required resource-based permission is normally configured automatically. When creating rules with infrastructure as code, verify the function policy includes an aws lambda add-permission-equivalent statement for the EventBridge rule ARN.
Lambda execution output is written to Amazon CloudWatch Logs when the function’s execution role has the required log permissions, typically through the managed AWSLambdaBasicExecutionRole policy or an equivalent least-privilege policy.
CloudTrail management events
CloudTrail management events record control-plane operations such as starting, stopping, terminating, or modifying EC2 instances. If the design specifically depends on CloudTrail API events, verify that CloudTrail is enabled for the relevant account and Region and that management events are being logged.
CloudTrail and EventBridge have different roles:
- CloudTrail: Records API activity for auditing, investigation, and governance.
- EventBridge: Routes matching events to targets for near-real-time automation.
- CloudWatch Logs: Stores Lambda output and can support operational troubleshooting.
Exam-Relevant Takeaways
- EventBridge can invoke Lambda when an AWS service event matches a rule pattern.
EC2 Instance State-change Notificationdescribes a state transition, not necessarily the API call that caused it.AWS API Call via CloudTrailidentifies an API operation and can include caller and request information.- Filter broadly by state when all stopped instances must be processed; filter by instance ID, account, Region, tags, or other fields when the workflow is narrower.
- A CloudTrail trail is required when the solution depends on CloudTrail event delivery or long-term API auditing. It is not inherently required for every native EC2 state-change EventBridge rule.
- Lambda needs permission to write to CloudWatch Logs and EventBridge needs permission to invoke Lambda.
- EventBridge delivery is asynchronous. Design targets to tolerate retries and duplicate processing by making actions idempotent.
- For cross-account routing, use event bus resource policies and, where appropriate, forwarding rules or AWS Organizations-based governance.
Architecture Decision Guide
| Requirement | Recommended event or service | Reason |
|---|---|---|
| React when an EC2 instance becomes stopped | EC2 Instance State-change Notification | Represents the resulting instance state |
Identify who called StopInstances | CloudTrail event pattern with eventName: StopInstances | Includes API and caller context |
| Record all management activity for investigation | CloudTrail trail or CloudTrail Lake | Durable audit and query capabilities |
| Invoke code in response to a matching event | EventBridge to Lambda | Serverless event-driven automation |
| Buffer events during target outages or bursts | EventBridge to SQS, then Lambda | Durable queueing and controlled consumption |
| Notify operators without custom code | EventBridge to SNS | Fanout to email, HTTP subscribers, or other consumers |
| Perform multi-step remediation | EventBridge to Step Functions | State management, retries, and workflow orchestration |
Common Exam Traps
- Confusing an EC2 state event with a CloudTrail API event: A stopped-state notification does not prove which API call caused the transition or who initiated it.
- Assuming CloudTrail is always required: Native EventBridge service events can be available without configuring a CloudTrail trail. CloudTrail is required for CloudTrail-based matching and audit retention.
- Filtering on the wrong field:
detail-typemust match the event type exactly.StopInstancesbelongs in the CloudTrail event’sdetail.eventName, not in an EC2 state-change event’sdetail.state. - Assuming EventBridge guarantees exactly-once delivery: Targets should safely handle duplicate deliveries and retries.
- Forgetting Lambda permissions: A rule can exist and match events but still fail if EventBridge cannot invoke the function.
- Expecting the Lambda console to show invocation immediately: Check the function’s CloudWatch Logs log group and recent log streams, while accounting for normal propagation and delivery delay.
- Leaving lab resources active: EC2 instances, CloudTrail trails, Lambda functions, and other resources can generate ongoing costs or operational noise.
Real-World Engineer Notes
- Include the AWS account and Region in alerts. EventBridge rules are Region-specific unless events are explicitly forwarded.
- Use a dead-letter queue and retry policy for important targets. This prevents transient failures from silently losing operational actions.
- Restrict Lambda execution permissions to only the APIs required by the remediation logic.
- If the rule starts or stops resources, protect against loops. A Lambda action that changes instance state can generate another event and repeatedly invoke the workflow.
- For organization-wide controls, consider centralized CloudTrail, delegated administration, EventBridge cross-account event buses, and service control policies. These solve different problems and should not be treated as interchangeable.
- Use structured logging in Lambda and include the EventBridge event ID. This helps correlate retries and detect duplicate processing.
- For compliance, do not rely only on Lambda logs. Retain CloudTrail data according to governance requirements and protect the destination from unauthorized modification.
Quick Reference Summary
- EventBridge rule: Matches events and routes them to targets.
- EC2 state event:
source: aws.ec2,detail-type: EC2 Instance State-change Notification. - CloudTrail API event:
detail-type: AWS API Call via CloudTrailwith fields such aseventSourceandeventName. - Lambda target: Receives the matched event as JSON.
- CloudWatch Logs: Common destination for Lambda execution output.
- CloudTrail: Provides API auditing and caller context; configure management event logging when required.
- Production safeguards: Idempotency, retries, dead-letter queues, least privilege, loop prevention, and cost cleanup.
Flashcards
- Q: What does an EventBridge rule do?
A: It evaluates incoming events against an event pattern or schedule and sends matching events to configured targets.
- Q: Which EventBridge event type indicates that an EC2 instance reached the stopped state?
A: EC2 Instance State-change Notification with detail.state set to stopped.
- Q: Which event type identifies an EC2 API request made through CloudTrail?
A: AWS API Call via CloudTrail.
- Q: Where is the API operation name found in a CloudTrail EventBridge event?
A: In detail.eventName, such as StopInstances or TerminateInstances.
- Q: Does an EC2 state-change EventBridge rule always require a CloudTrail trail?
A: No. Native EC2 state-change events can be consumed directly. A CloudTrail trail is needed when the design specifically depends on CloudTrail API events or audit retention.
- Q: What permission allows EventBridge to invoke Lambda?
A: A Lambda resource-based policy statement allowing the EventBridge rule principal to invoke the function.
- Q: Where does Lambda normally write execution output?
A: Amazon CloudWatch Logs, provided the execution role has the necessary log permissions.
- Q: Why should an EventBridge target be idempotent?
A: Event delivery and target invocation can be retried, so duplicate processing is possible.
- Q: What field filters a state-change event to only stopped instances?
A: detail.state: ["stopped"].
- Q: What service provides durable records of AWS API activity?
A: AWS CloudTrail, optionally with CloudTrail Lake or an S3-based trail destination for longer-term analysis and retention.
Practice Questions
Question 1
A security team wants an automated Lambda function to record the identity of every principal that calls TerminateInstances in an AWS account. Which EventBridge event pattern is most appropriate?
A. Match source: aws.ec2 and detail-type: EC2 Instance State-change Notification with detail.state: terminated
B. Match source: aws.ec2 and detail-type: AWS API Call via CloudTrail with detail.eventName: TerminateInstances
C. Match all CloudWatch metric alarms for EC2
D. Match source: aws.lambda and detail-type: Lambda Function Invocation Result
Correct answer: B
Explanation: The requirement is to identify the API caller. CloudTrail API events contain the API operation and caller context. A terminated state-change event only indicates the resulting state and does not reliably identify the principal that initiated it.
Question 2
An operations team wants to invoke a Lambda function whenever any EC2 instance in a Region enters the stopped state. The team does not need the initiating user’s identity. Which solution is simplest?
A. Create an EventBridge rule matching EC2 Instance State-change Notification and detail.state: stopped
B. Query CloudTrail logs every minute with a Lambda function
C. Create a scheduled CloudWatch alarm for every EC2 instance
D. Enable VPC Flow Logs and invoke Lambda from the logs
Correct answer: A
Explanation: EC2 state-change notifications are designed for this event-driven use case. A direct EventBridge rule avoids polling and does not require CloudTrail when caller identity and API auditing are not part of the requirement.
Question 3
A Lambda function is configured as an EventBridge target, but matching events do not result in Lambda invocations. The function has an execution role with CloudWatch Logs permissions. What should be checked first?
A. Whether the Lambda function has a public IP address
B. Whether the EventBridge rule has permission to invoke the Lambda function
C. Whether the EC2 instances use an internet gateway
D. Whether the Lambda function is deployed in a public subnet
Correct answer: B
Explanation: Lambda execution-role permissions control what the function can do after invocation. EventBridge separately requires permission in the Lambda resource-based policy to invoke the function.
Question 4
A company wants to stop an EC2 instance automatically when it is detected as noncompliant. The EventBridge rule invokes Lambda, and Lambda calls StopInstances. The workflow sometimes invokes itself repeatedly. What is the best engineering improvement?
A. Disable CloudWatch Logs
B. Add loop prevention and make the remediation idempotent
C. Replace EventBridge with an internet-facing API Gateway
D. Remove the Lambda execution role
Correct answer: B
Explanation: Remediation actions can produce additional service events that match the same or another rule. Filtering events, recording remediation state, and making the operation safe to repeat prevents recursive or duplicate processing.
Question 5
A compliance solution must retain a tamper-resistant history of EC2 API activity for several years and also trigger near-real-time remediation. Which architecture best meets both requirements?
A. Use only Lambda logs
B. Use EventBridge state-change events without any audit service
C. Use CloudTrail for API recording and EventBridge rules for real-time routing to remediation targets
D. Use EC2 system logs and a scheduled script
Correct answer: C
Explanation: CloudTrail provides the durable API audit trail, while EventBridge provides event-driven routing for rapid response. Lambda can perform remediation, with appropriate retry, dead-letter, and least-privilege controls.