AWS Systems Architect Professional

Resize an EC2 Instance with AWS Lambda – SAP-C02 Study Guide

Learn how to use AWS Lambda, IAM, CloudWatch, and EC2 APIs to safely automate instance resizing for SAP-C02 scenario questions.

AWS Systems Architect ProfessionalAWS Systems Architect ProfessionalUpdated Sep 1, 2026
Study options
WatchComing later
ListenComing later
ReadAvailable
ReviewComing later

Study guide

Technical reference and lesson notes

Purpose of This Lesson

This hands-on exercise demonstrates how to use an AWS Lambda function to automate an EC2 instance type change. The workflow highlights several exam-relevant design concerns:

  • Granting Lambda permission to call other AWS services
  • Using an execution role rather than embedding credentials
  • Monitoring Lambda invocations with Amazon CloudWatch Logs
  • Handling long-running AWS API operations with an appropriate timeout
  • Stopping an EC2 instance before changing its instance type, then starting it again

The example changes an EBS-backed EC2 instance from t2.micro to t2.medium.

Key Concepts

Lambda execution roles control AWS API access

A Lambda function executes using an IAM execution role. The role determines which AWS APIs the function can call.

A newly created function commonly receives a basic policy that permits writing invocation output to CloudWatch Logs. That policy does not automatically allow the function to manage EC2 instances.

For an EC2 resize workflow, the role may need permissions such as:

  • ec2:DescribeInstances
  • ec2:StopInstances
  • ec2:ModifyInstanceAttribute or the relevant EC2 modification API
  • ec2:StartInstances
  • Potentially ec2:DescribeInstanceStatus
  • CloudWatch Logs permissions such as logs:CreateLogGroup, logs:CreateLogStream, and logs:PutLogEvents

The exact actions depend on the implementation. Avoid granting AmazonEC2FullAccess in production when a smaller resource-scoped policy can perform the task.

EC2 instance type changes generally require a stopped instance

For a typical EBS-backed EC2 instance, changing the instance type requires this sequence:

  1. Stop the instance.
  2. Modify the instance type.
  3. Start the instance.
  4. Verify that the instance is running with the expected type.

Stopping and starting affects availability. It can also change the instance’s underlying host and, depending on the addressing configuration, may affect public IPv4 addressing. Elastic IP addresses remain associated when configured appropriately.

Lambda timeout must accommodate asynchronous infrastructure operations

Lambda’s default timeout is short. In the demonstration, the function timed out while waiting for the EC2 instance to stop because the default timeout was three seconds.

Lambda supports a maximum timeout of 15 minutes. Increasing the timeout can make a small workflow succeed, but it is not always the best architecture. A function that waits synchronously for EC2 state transitions consumes Lambda execution time and may still fail if the operation is slow.

For production automation, consider a state-machine approach with AWS Step Functions, or an event-driven design that reacts to EC2 state changes rather than continuously polling.

CloudWatch Logs are essential for troubleshooting

Lambda automatically creates a log group using the function name, typically following this pattern:

/aws/lambda/<function-name>

Each invocation is written to a log stream. Logs can reveal:

  • Whether the invocation started and completed
  • API errors and authorization failures
  • Timeout events
  • Application output and exception details
  • Duration and memory usage

A successful Lambda test response may show a status result, duration, initialization time, and maximum memory used. These metrics help distinguish code failures, permission failures, and resource sizing problems.

Test events provide input such as the instance ID

A Lambda test event can provide the target instance identifier in JSON. A simplified event might look like this:

{
  "instance_id": "i-0123456789abcdef0"
}

The function should validate the input rather than blindly trusting the event. In a production implementation, also consider validating the target instance through tags, account, Region, and expected current state.

Exam-Relevant Takeaways

  • Lambda requires an IAM execution role to access AWS services.
  • The basic Lambda role normally provides CloudWatch Logs access, not EC2 management access.
  • Use least-privilege permissions instead of broad policies such as full EC2 access.
  • A Lambda timeout is different from an EC2 API timeout. The function can time out while an EC2 operation continues or changes state.
  • Lambda’s maximum execution timeout is 15 minutes.
  • Stopping and starting an EC2 instance causes downtime and may affect ephemeral public addressing.
  • CloudWatch Logs is the first place to investigate Lambda timeouts, exceptions, and permission errors.
  • A successful Lambda invocation does not necessarily prove that the intended infrastructure state was reached; the function should verify the final state.
  • For multi-step operations with waits, retries, branching, and error handling, Step Functions is often more suitable than a single long-running Lambda invocation.

Architecture Decision Guide

RequirementAppropriate approachImportant considerations
Run a one-off resize manuallyLambda test event or an operator-triggered invocationValidate the instance ID and execution Region
Resize instances on a scheduleAmazon EventBridge schedule invoking LambdaAdd idempotency, concurrency controls, and tagging filters
Resize based on a business eventEventBridge event rule or another service invoking LambdaEnsure the event contains enough context to identify the target
Stop, wait, resize, start, and verifyStep Functions with Lambda or AWS SDK integrationsBetter visibility, retries, wait states, and failure handling
Apply the same change to many instancesSystems Manager Automation or a controlled orchestration workflowSafer fleet targeting and concurrency management
Permit only selected instancesIAM conditions and application-side tag validationResource-level support varies by EC2 action; test the policy carefully
Preserve a stable public addressAssociate an Elastic IP or use a load balancerA normal public IPv4 address can change after stop/start

Common Exam Traps

Confusing the Lambda role with the caller’s permissions

The IAM identity that creates or invokes a function is not the identity used by the function to call EC2. The function uses its execution role. Both identities may require permissions for their respective operations.

Assuming basic Lambda permissions include EC2 access

Basic Lambda permissions generally support CloudWatch logging only. EC2 API calls fail with an authorization error unless the execution role has the required EC2 actions.

Leaving the default timeout unchanged

A short default timeout may be insufficient for a workflow that waits for an instance to stop and restart. Increasing the timeout may solve a small lab problem, but a production design should evaluate whether synchronous waiting is appropriate.

Granting full EC2 access for convenience

AmazonEC2FullAccess is excessive for a function that only needs to manage one class of operation. Prefer a customer-managed policy with only the required actions and suitable resource or condition restrictions.

Ignoring downtime and address changes

Changing an instance type usually requires a stop/start cycle. This is not a zero-downtime scaling method. If availability is important, use an Auto Scaling group, load balancer, or replacement-instance strategy instead.

Treating a test invocation as production automation

The Lambda console test event is useful for validation, but production workflows need authentication, input validation, retries, observability, concurrency controls, and safe targeting.

Real-World Engineer Notes

  • Use a current, supported Lambda runtime. Older runtimes shown in training labs may be deprecated and unavailable for new functions.
  • Design the function to be idempotent. If the instance is already stopped, already the desired type, or in a transitional state, the function should handle that condition safely.
  • Do not hard-code credentials. Attach an IAM role to the function.
  • Restrict the function’s network configuration only when it needs VPC resources. A Lambda function that calls public AWS endpoints may need NAT gateway access if placed in private subnets, unless it uses appropriate VPC endpoints. Avoid placing Lambda in a VPC unnecessarily.
  • Add structured logging, a correlation identifier, and the target instance ID to make operations traceable.
  • Configure CloudWatch alarms for errors, throttles, and unusual duration. Consider an alert for failed state verification.
  • Use reserved concurrency or another control when concurrent invocations could attempt conflicting changes to the same instance.
  • For fleet operations, target instances through tags and use Systems Manager or Step Functions to control concurrency and retries.
  • Consider whether resizing is the right solution. Auto Scaling groups and horizontal scaling often provide better availability than stopping and resizing a single instance.
  • Clean up lab resources. EC2 charges can continue while an instance is running; Lambda charges are based primarily on requests and execution duration, subject to the applicable free tier.

Quick Reference Summary

  • Compute automation: Lambda can call EC2 APIs using its execution role.
  • Required access: Add only the EC2 actions the function actually uses.
  • Resize sequence: Stop → modify instance type → start → verify.
  • Timeout: Default Lambda timeouts may be too short; maximum is 15 minutes.
  • Logging: Review /aws/lambda/<function-name> in CloudWatch Logs.
  • Availability: A stop/start resize causes downtime.
  • Addressing: A non-Elastic public IPv4 address may change after stop/start.
  • Better orchestration: Use Step Functions or Systems Manager for complex or fleet-wide workflows.

Flashcards

1. What IAM identity does a Lambda function use when calling EC2?

Its attached IAM execution role.

2. What do basic Lambda permissions normally allow?

Writing invocation logs to Amazon CloudWatch Logs.

3. Why might an EC2 resize Lambda function time out?

It may synchronously wait for the instance to stop before modifying and restarting it, exceeding the function’s configured timeout.

4. What is the maximum Lambda execution timeout?

15 minutes.

5. What is the usual sequence for changing an EBS-backed EC2 instance type?

Stop the instance, modify its instance type, start it, and verify the resulting state.

6. Where are Lambda execution logs normally stored?

In a CloudWatch Logs group named /aws/lambda/<function-name>.

7. Why is AmazonEC2FullAccess a poor production choice for this function?

It grants substantially more access than required and violates least-privilege principles.

8. What can happen to a regular public IPv4 address after an EC2 stop/start?

It can change. An Elastic IP or load balancer should be used when a stable endpoint is required.

9. When is Step Functions preferable to one long-running Lambda function?

When the workflow has multiple steps, wait states, retries, branching, or detailed failure handling.

10. What should a resize function do if the instance is already the desired type?

Treat the request as idempotently complete or return a clear no-op result rather than performing unnecessary actions.

Practice Questions

Question 1

A Lambda function successfully writes to CloudWatch Logs but receives UnauthorizedOperation when it attempts to stop an EC2 instance. What is the most likely cause?

A. The Lambda function is configured with an x86_64 architecture.

B. The function’s execution role lacks the required EC2 permissions.

C. The Lambda function has no test event configured.

D. The EC2 instance does not have a public IPv4 address.

Correct answer: B

The function uses its execution role when calling EC2. Basic logging permissions do not grant EC2 management access.

Question 2

A company needs to stop an EC2 instance, wait until it is stopped, change its instance type, start it, and retry failed steps with visibility into each state transition. Which solution is most appropriate?

A. A single Lambda function with a 15-minute timeout and a polling loop

B. An EventBridge rule that repeatedly invokes the same Lambda function without state

C. AWS Step Functions orchestrating the workflow with wait states and retries

D. An EC2 user data script that changes the instance type from inside the instance

Correct answer: C

Step Functions is designed for multi-step orchestration, wait states, retries, and execution history. A polling Lambda can work for a small task but is less efficient and less observable.

Question 3

An operations team uses a Lambda function to resize a production EC2 instance. The resize causes several minutes of downtime and the instance’s public IPv4 address changes. Which redesign best improves availability and endpoint stability?

A. Increase the Lambda memory allocation.

B. Assign an Elastic IP and continue resizing the same instance during business hours.

C. Place instances behind an Application Load Balancer and use an Auto Scaling group to replace or scale capacity.

D. Grant the Lambda function full administrator permissions.

Correct answer: C

Horizontal scaling behind a load balancer avoids depending on a single instance and supports replacement or capacity changes with less service disruption. An Elastic IP can stabilize an address but does not eliminate downtime during resizing.

Question 4

A Lambda function is invoked concurrently by two automation events for the same instance. One invocation stops the instance while the other attempts to change its type. What is the best control to prevent conflicting operations?

A. Disable CloudWatch Logs.

B. Add concurrency control and make the workflow idempotent.

C. Change the function architecture from x86_64 to ARM64.

D. Remove the Lambda timeout.

Correct answer: B

Concurrency controls, state checks, and idempotent behavior help prevent simultaneous operations from producing race conditions or inconsistent instance state.

Question 5

A developer places a Lambda function in private VPC subnets to resize an EC2 instance. The function times out when calling the EC2 API, even though its IAM role is correct. What should be investigated first?

A. Whether the private subnets have a route to the required AWS API endpoint through NAT or an appropriate VPC endpoint.

B. Whether the EC2 instance has an SSH key pair.

C. Whether the Lambda test event contains a Hello from Lambda response.

D. Whether the instance type supports CloudWatch Logs.

Correct answer: A

A VPC-attached Lambda function requires suitable network connectivity to reach AWS service endpoints. Correct IAM permissions alone do not provide network access.