All practice questions

1542 questions

Question 21Question

A developer is troubleshooting an authorization issue with a REST API in Amazon API Gateway. The API uses a custom Lambda authorizer with caching enabled, and the cache key is set to the Authorization header. When a client sends a request to GET /orders/101 with a valid token, the request succeeds. However, when the same client immediately sends a request to GET /orders/202 using the same token, the client receives a 403 Forbidden error with the message 'User is not authorized to access this resource'. The developer verifies that the client has valid permissions for both order resources. What is the root cause of this authorization failure, and how should it be resolved?

Show answer & explanation

Answer: The Lambda authorizer returned a resource ARN specific to the first request's path, which was cached. Subsequent requests for different paths with the same token reuse the cached policy and are denied. To resolve this, configure the Lambda authorizer to return a wildcard resource ARN covering all paths, or disable caching.

Answer

The Lambda authorizer returned a resource ARN specific to the first request's path, which was cached. Subsequent requests for different paths with the same token reuse the cached policy and are denied. To resolve this, configure the Lambda authorizer to return a wildcard resource ARN covering all paths, or disable caching.
When caching is enabled, API Gateway caches the policy returned by the Lambda authorizer using the cache key (the token). If the policy specifies a resource-specific ARN (like the path of the first request), any subsequent requests to a different path with the same token will use the cached policy and fail with a 403 Forbidden error because that path is not allowed in the policy. Returning a wildcard ARN or disabling caching resolves this issue.

Step-by-Step Solution

1
Analyze the symptoms of the authorization failure where the first request succeeds but the subsequent request with the same token to a different path fails with a 403 Forbidden error.
Identify that the Lambda authorizer has caching enabled with the Authorization header as the cache key.
This helps narrow down the problem to how API Gateway caches and evaluates the IAM policy returned by the Lambda authorizer.
2
Examine how API Gateway caches policies based on the custom Lambda authorizer configuration.
The authorizer returns a policy containing the resource ARN for the specific path of the first request (/orders/101), which is then cached by API Gateway for that authorization token.
API Gateway uses the cached policy for all subsequent requests containing the same token during the TTL period, without invoking the Lambda function again.
3
Determine how the cached policy affects the second request (GET /orders/202).
Because the cached policy only allows access to the resource ARN for /orders/101, API Gateway denies access to /orders/202 and returns a 403 Forbidden error.
This confirms that the narrow resource scope in the cached policy is the root cause of the authorization failure.
4
Formulate the resolution to fix the authorization issue.
Modify the Lambda authorizer code to return a wildcard resource ARN (e.g., /orders/*) so that the cached policy permits access to all relevant paths, or disable caching if granular per-path verification is required on every request.
This ensures that either the cached policy is broad enough to cover all client requests or that the authorizer runs on every request to generate a precise policy.

Key Concept

API Gateway custom Lambda authorizer policy caching and resource ARN validation.
Question 22Question

A developer is troubleshooting an application named PixelStream that uploads high-resolution images. The application stores metadata in an Amazon DynamoDB table where the partition key is set to the upload date (formatted as YYYY-MM-DD). During peak hours, the application frequently encounters ProvisionedThroughputExceededException errors even though the table's overall consumed throughput is well below the provisioned write capacity limit. What is the most effective way to resolve this throughput issue?

Show answer & explanation

Answer: Redesign the partition key schema to use a more granular attribute, such as a unique Image ID, to distribute write requests evenly across partitions.

Answer

Redesign the partition key schema to use a more granular attribute, such as a unique Image ID, to distribute write requests evenly across partitions.
Redesigning the partition key schema to use a high-cardinality attribute, such as a unique Image ID, spreads write operations across multiple physical partitions, preventing any single partition from exceeding its individual throughput limits.

Step-by-Step Solution

1
Analyze the table schema and error behavior.
Identify that the partition key is the upload date, which has very low cardinality and results in all writes for a given day hitting the same partition.
This confirms that the ProvisionedThroughputExceededException is caused by a hot partition key rather than exceeding the table's total capacity.
2
Determine the solution for even data distribution.
Select a partition key with high cardinality, such as a unique Image ID.
High-cardinality keys distribute write requests evenly across physical partitions, resolving partition-level write limits.

Key Concept

Selecting a partition key with high cardinality to distribute write requests evenly and avoid hot partition bottlenecks.
Estimated Time:1m 0s
Question 23Question

A developer is troubleshooting a CI/CD pipeline in AWS CodePipeline that deploys infrastructure using AWS CloudFormation. During the initial deployment of a new stack, the deployment stage failed due to an invalid parameter value, leaving the CloudFormation stack in the ROLLBACK_COMPLETE state. After correcting the parameter value in the template and pushing the fix to the source repository, the pipeline runs again but the CloudFormation deploy stage fails immediately, indicating that the stack cannot be updated. Which action must the developer perform to successfully deploy the stack through the pipeline?

Show answer & explanation

Answer: Delete the existing CloudFormation stack manually or via the AWS CLI, and then trigger the pipeline again.

Answer

Delete the existing CloudFormation stack manually or via the AWS CLI, and then trigger the pipeline again.
The correct answer is to delete the existing CloudFormation stack manually or via the AWS CLI, and then trigger the pipeline again. When a CloudFormation stack fails during its initial creation, it goes into the ROLLBACK_COMPLETE state. CloudFormation does not allow updates to a stack that has never been successfully created. Therefore, to proceed, the developer must delete the failed stack, which removes it, allowing the pipeline's subsequent run to perform a successful create operation.

Step-by-Step Solution

1
Identify the current status of the CloudFormation stack from the AWS CloudFormation console or CLI.
The stack is found to be in the ROLLBACK_COMPLETE state due to a failed initial creation.
Understanding the exact failure state is necessary because different rollback states (e.g., ROLLBACK_COMPLETE vs UPDATE_ROLLBACK_COMPLETE) have different recovery paths.
2
Determine the supported actions for a stack in the ROLLBACK_COMPLETE state.
A stack in ROLLBACK_COMPLETE cannot be updated; it can only be deleted.
This determines that attempting to push template updates through the pipeline directly will continue to fail, as the pipeline will attempt to perform a stack update action.
3
Delete the failed stack and re-run the pipeline.
The pipeline runs successfully and creates the stack from scratch with the corrected template.
Deleting the stack removes the blocked state, allowing the pipeline's CloudFormation action to execute a clean stack creation.

Key Concept

Handling CloudFormation initial creation failures and the ROLLBACK_COMPLETE state in CI/CD pipelines.
Question 24Question

A company is migrating a containerized web application to run on Amazon ECS using the Amazon EC2 launch type. Multiple instances of the application task must run on each container instance, and the tasks are configured to use the bridge network mode. The application code requires access to a database password stored in AWS Secrets Manager and must perform read operations on an Amazon DynamoDB table. Which two configurations are required to support this deployment?

Select all that apply

Show answer & explanation

Answer: Set the container port to 80 and the host port to 0 (or leave it blank) in the task definition port mapping.; Configure the task definition's Task Role (taskRoleArn) with the IAM policies required to access the Amazon DynamoDB table and AWS Secrets Manager.

Answer

Configure dynamic port mapping by setting the host port to 0 or leaving it blank, and assign the required IAM policies to the ECS Task Role (taskRoleArn) with a trust policy for ecs-tasks.amazonaws.com.
To support running multiple instances of the container on a single EC2 host using the bridge network mode, dynamic host port mapping is required. This is achieved by setting the host port to 0 or leaving it blank in the task definition port mapping, which allows the ECS agent to automatically map the container port to a random ephemeral port on the host. Furthermore, the application container requires AWS credentials at runtime to query the DynamoDB table and fetch secrets from Secrets Manager. These application-level permissions must be defined in an IAM role assigned to the taskRoleArn (Task Role) parameter of the task definition.

Step-by-Step Solution

1
Configure the port mapping in the task definition for bridge network mode with the host port set to 0 or left blank.
Enables dynamic port mapping, letting the ECS agent bind the container's port to a random host port.
Allows multiple task instances to run on the same EC2 instance without port conflicts.
2
Create an IAM role that trusts the ecs-tasks.amazonaws.com service principal and attach permission policies for DynamoDB and Secrets Manager.
Creates a role that ECS tasks can assume to perform API operations on AWS services.
Secures application credentials by avoiding hardcoded values and granting access via temporary credentials.
3
Assign this role to the taskRoleArn parameter in the ECS task definition.
Ensures the containerized application executes with the permissions defined in the IAM role.
Maintains the separation of concerns by assigning application access to the Task Role rather than the Task Execution Role.

Key Concept

ECS Task Role vs Task Execution Role and Bridge Network Mode Port Mapping
Estimated Time:2m 0s
Question 25Question

A developer is setting up an AWS CodeBuild project to build a containerized application. The build process needs to retrieve a database password securely from AWS Secrets Manager. The developer has stored a custom build specification file at the path `build/pipelines/buildspec-dev.yml` in the source repository. During the initial build run, CodeBuild fails immediately because it cannot locate the build specification, and the database credentials are not resolved. Which two actions should the developer take to configure the project correctly? (Choose two.)

Select all that apply

Show answer & explanation

Answer: Update the CodeBuild project configuration to set the buildspec file path to build/pipelines/buildspec-dev.yml; In the buildspec-dev.yml file, retrieve the database password by defining it under the secrets-manager key in the env section

Answer

To configure the project correctly, the developer must update the CodeBuild project settings to set the buildspec path to the custom subdirectory path, and update the buildspec-dev.yml file to declare the secret under the secrets-manager key in the env section.
To resolve the buildspec locator issue, the developer must explicitly configure the custom file path in the CodeBuild project configuration since it is not named buildspec.yml at the root. To retrieve the secret correctly, the developer must define it under the secrets-manager key in the env block, which instructs CodeBuild to retrieve the value from Secrets Manager natively.

Step-by-Step Solution

1
Configure the CodeBuild project settings to point to the correct buildspec location.
CodeBuild is successfully able to locate and parse the buildspec file from build/pipelines/buildspec-dev.yml instead of failing at the start of the build.
By default, CodeBuild only searches for buildspec.yml at the root directory of the source provider. Any other name or path must be configured in the project settings.
2
Configure the env section of the buildspec-dev.yml file to pull the database password from Secrets Manager.
The database password is dynamically retrieved and exposed as an environment variable in the build environment.
Using the native secrets-manager key in the env block tells CodeBuild to fetch the secret from AWS Secrets Manager using the service role's permissions.

Key Concept

AWS CodeBuild buildspec configuration and Secrets Manager integration
Question 26Question

A developer is troubleshooting an AWS Lambda function that processes customer orders. The Lambda function is configured to run inside a custom VPC in two private subnets to access an Amazon RDS database securely. During testing, the function times out when attempting to connect to an external payment processor's HTTP endpoint over the internet. Additionally, under load, the Lambda function frequently times out because it establishes a new database connection during each invocation, quickly exhausting database resources.

Which combination of actions will resolve these issues? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Configuring a NAT gateway in a public subnet, and updating the route tables of the private subnets to route outbound internet traffic (0.0.0.0/0) through the NAT gateway.; Declaring the database connection client outside of the Lambda handler function to enable execution context reuse across warm starts.

Answer

The correct options are configuring a NAT gateway in a public subnet and routing the private subnet's traffic through it, and declaring the database connection client outside of the handler function to reuse the execution context.
The correct options resolve both issues. Routing internet-bound traffic from private subnets through a NAT gateway in a public subnet allows the Lambda function to communicate with the external payment API. Declaring the database client outside the handler code ensures that the database connection is reused across invocations, mitigating connection overhead and latency.

Step-by-Step Solution

1
Address the external payment processor connection timeouts.
Determine that Lambda functions in private subnets require a NAT gateway or VPC endpoint to access the public internet.
Since the external API is on the internet, a NAT gateway must be set up in a public subnet, and the private subnet route tables must be updated to route outbound traffic through it.
2
Address the database resource exhaustion and execution timeouts under load.
Move the database connection initialization code out of the Lambda handler block to global scope.
This allows subsequent warm executions of the function to reuse the existing database connection pool instead of repeatedly opening and closing sockets, resolving execution timeouts and database overload.

Key Concept

VPC networking configuration for outbound Lambda internet access and database connection optimization using execution context reuse.
Question 27Question

An application running inside an Amazon ECS task on AWS Fargate in Account A (111111111111111111111111) needs to write objects to an Amazon S3 bucket located in Account B (222222222222222222222222). The developer wants the application to temporarily assume an IAM role named CrossAccountS3Writer in Account B. The ECS task definition is configured with an ECS Task Role named ECSTaskRole.

The trust policy of the CrossAccountS3Writer role in Account B contains the following statement:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111111111111:role/ECSTaskRole"
},
"Action": "sts:AssumeRole"
}
]
}

When the application execution code attempts to call the sts:AssumeRole API, it fails with an AccessDenied error. How should the developer resolve this authorization failure?

Show answer & explanation

Answer: Attach an identity-based policy to ECSTaskRole in Account A that grants the sts:AssumeRole permission targeting the Amazon Resource Name (ARN) of the CrossAccountS3Writer role in Account B.

Answer

Attach an identity-based policy to ECSTaskRole in Account A that grants the sts:AssumeRole permission targeting the Amazon Resource Name (ARN) of the CrossAccountS3Writer role in Account B.
For cross-account role assumption, AWS IAM requires a bilateral handshake: the trusting role (in Account B) must specify the external principal in its trust policy, and the trusted principal (in Account A) must have an identity-based policy that grants permission to call 'sts:AssumeRole' on the target role's ARN. Since the trust policy in Account B is already correctly configured, adding the 'sts:AssumeRole' permission to the ECSTaskRole in Account A completes this handshake and resolves the AccessDenied error.

Step-by-Step Solution

1
Analyze the error context and the resource policy configuration.
The application inside the ECS task is trying to assume the CrossAccountS3Writer role in Account B, but the AssumeRole request is denied.
Establishing cross-account delegation requires explicit authorization in both accounts: a trust relationship in the receiving account (Account B) and an identity-based grant in the initiating account (Account A).
2
Examine the trust policy of the target role (CrossAccountS3Writer) in Account B.
The trust policy correctly allows the identity 'arn:aws:iam::111111111111:role/ECSTaskRole' to call 'sts:AssumeRole'.
This confirms that Account B is configured properly to trust the ECS Task Role from Account A.
3
Determine the missing permission in the initiating account (Account A).
The ECS Task Role (ECSTaskRole) itself does not have a policy permitting it to invoke 'sts:AssumeRole' on the destination role.
IAM identities require explicit permission to call 'sts:AssumeRole' on a resource in another account, even if that resource trusts them.
4
Select the correct action to resolve the authorization failure.
Add an identity-based policy to 'ECSTaskRole' with an 'Allow' effect on the 'sts:AssumeRole' action, specifying the ARN of the target role in Account B as the resource.
This satisfies the cross-account delegation requirements by authorizing the ECS Task Role to perform the assume-role request.

Key Concept

Cross-Account IAM Delegation and ECS Task Roles
Question 28Question

A developer has configured an AWS Lambda function written in Python to process events from an Amazon SQS queue and write the results to an Amazon DynamoDB table. Active tracing is enabled on both the SQS queue and the Lambda function. When reviewing the AWS X-Ray console, the developer observes that the service map shows the SQS queue and the Lambda function, but the downstream calls to DynamoDB are missing from the trace. Which action should the developer take to trace the downstream DynamoDB calls in AWS X-Ray?

Show answer & explanation

Answer: Import the AWS X-Ray SDK in the Lambda function code and invoke the patch_all() function before initializing the Boto3 client.

Answer

Import the AWS X-Ray SDK in the Lambda function code and invoke the patch_all() function before initializing the Boto3 client.
The correct answer is to import the AWS X-Ray SDK and run the patch_all() function. When running a Python Lambda function with active tracing enabled, downstream SDK calls are not traced by default unless the Boto3 library is instrumented. Patching the library automatically wraps Boto3 clients so that downstream calls (like DynamoDB operations) are recorded as subsegments in the X-Ray trace.

Step-by-Step Solution

1
Identify that the Lambda function has active tracing enabled but downstream calls to DynamoDB are not being recorded.
The Lambda function segment is present, but DynamoDB subsegments are missing.
Active tracing on Lambda only traces the Lambda execution itself, not downstream SDK calls by default.
2
Instrument the Boto3 library using the AWS X-Ray SDK for Python.
The Boto3 clients will automatically generate and propagate subsegment details for downstream API calls.
Patching is the standard method in the Python AWS X-Ray SDK to instrument supported libraries like Boto3 without modifying client invocation syntax.

Key Concept

AWS SDK client instrumentation using the X-Ray SDK to trace downstream AWS service calls.
Question 29Question

A developer is troubleshooting a web dashboard hosted on `https://monitor.server-analytics.io` that queries a backend using an Amazon API Gateway REST API. The API is configured with a Lambda Proxy integration. When the client makes a request to the API, the browser blocks the response and displays the following error:

`Access to XMLHttpRequest at 'https://api.server-analytics.io/v1/logs' from origin 'https://monitor.server-analytics.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.`

Which TWO steps should the developer take to resolve these errors?

Select all that apply

Show answer & explanation

Answer: Configure the `OPTIONS` method on the API Gateway resource to return the required CORS headers for preflight requests.; Modify the Lambda function's response payload to include the `Access-Control-Allow-Origin` header in the `headers` object.

Answer

Configure the `OPTIONS` method on the API Gateway resource to return the required CORS headers for preflight requests, and modify the Lambda function's response payload to include the `Access-Control-Allow-Origin` header in the `headers` object.
The correct options are configuring the `OPTIONS` method on the API Gateway resource and modifying the Lambda function's response payload. Under a Lambda Proxy integration, resolving CORS requires a two-fold approach: first, the preflight `OPTIONS` request must be handled by API Gateway (or a mock integration) to return the allowed origin; second, the backend Lambda function must return the `Access-Control-Allow-Origin` header in its execution response.

Step-by-Step Solution

1
Enable CORS preflight by configuring the `OPTIONS` method on the API resource.
The browser's initial preflight request is successfully answered with `Access-Control-Allow-Origin` and other CORS headers.
Browsers send an HTTP `OPTIONS` preflight request before cross-origin non-simple requests to verify if the server permits the cross-origin call.
2
Add the `Access-Control-Allow-Origin` header to the backend response returned by the Lambda function.
The actual HTTP request succeeds because the response payload contains the required header.
Under Lambda Proxy integration, API Gateway does not automatically inject CORS headers into the backend response. The backend Lambda function must explicitly return these headers in its payload.

Key Concept

CORS handling in API Gateway Lambda Proxy integrations requires CORS configuration for both the preflight `OPTIONS` method on API Gateway and the actual method response from the backend Lambda function.
Estimated Time:1m 30s
Question 30Question

A developer is troubleshooting an AWS Lambda function with a configured timeout of 10 seconds. The function is occasionally failing to process incoming payloads. The developer wants to configure an Amazon CloudWatch Logs metric filter to count how many times the function executions are terminated due to timeouts, and to trigger an alarm. The application code is designed to log custom execution details in JSON format, including `{ "execution_time_ms": 10500, "status": "success" }`, at the end of the handler execution. Which configuration should the developer implement to reliably monitor these execution timeouts?

Show answer & explanation

Answer: Create a metric filter on the log group with the pattern "Task timed out" and create a CloudWatch alarm based on this metric.

Answer

Create a metric filter on the log group with the pattern "Task timed out" and create a CloudWatch alarm based on this metric.
When a Lambda function times out, the Lambda service halts execution immediately. This prevents the custom application code from completing and writing any custom JSON log events. Instead, the service writes a message containing 'Task timed out' to the log stream. Therefore, a metric filter targeting this literal string is the only reliable way to count timeouts.

Step-by-Step Solution

1
Analyze Lambda execution behavior during a timeout
When a Lambda function reaches its configured timeout limit (10 seconds in this scenario), the AWS Lambda service terminates the execution container immediately.
This shows that any application-level code designed to run at the end of the handler (such as writing a custom JSON log with execution metrics) is never executed.
2
Identify the log event recorded during a timeout
The AWS Lambda service runtime writes a platform-generated log line to the log stream, containing the phrase: 'Task timed out after 10.00 seconds'.
To reliably track timeouts, the metric filter must search for this platform-generated text rather than custom JSON properties that are only written upon successful handler execution.
3
Select the correct CloudWatch Logs Metric Filter syntax
The literal pattern "Task timed out" is used to match the platform log event. An alarm is then associated with this metric to trigger notifications or scaling actions.
This correctly targets the service-level error message and tracks execution failures accurately.

Key Concept

AWS Lambda platform logging on execution timeouts vs application-level logs, and correct CloudWatch metric filter string matching.
Estimated Time:1m 30s
Question 31Question

A developer is configuring an AWS Lambda function in Account A (111122223333111122223333) to write data to an Amazon DynamoDB table in Account B (444455556666444455556666) by assuming an IAM role named `CrossAccountDynamoDBRole` in Account B. The Lambda function's execution role in Account A is named `LambdaExecutionRole`.

When the Lambda function invokes the `AssumeRole` API call using the AWS SDK, the execution fails with the following error:
`User: arn:aws:sts::111122223333:assumed-role/LambdaExecutionRole/my-function is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::444455556666:role/CrossAccountDynamoDBRole`

Which TWO configurations must the developer implement to resolve this error?

Select all that apply

Show answer & explanation

Answer: Add a permission policy to the LambdaExecutionRole in Account A that allows the sts:AssumeRole action on arn:aws:iam::444455556666:role/CrossAccountDynamoDBRole.; Configure the trust policy of CrossAccountDynamoDBRole in Account B to allow the sts:AssumeRole action for the principal arn:aws:iam::111122223333:role/LambdaExecutionRole.

Answer

To allow the Lambda function to perform cross-account access, the developer must grant the sts:AssumeRole permission to the Lambda execution role in Account A and configure the target role in Account B to trust the Lambda execution role in Account A.
The correct configurations involve setting up both sides of the trust boundary. First, the calling role in Account A must be granted permission to perform the sts:AssumeRole action. Second, the trust policy of the target role in Account B must be updated to trust the calling role in Account A as the principal.

Step-by-Step Solution

1
Analyze the error message and the configuration requirements.
The error indicates that the Lambda execution role in Account A is not authorized to perform sts:AssumeRole on the cross-account role in Account B.
For cross-account role assumption to succeed, two permissions must match: the caller role must have a permission policy allowing sts:AssumeRole, and the destination role must have a trust policy allowing the caller role to assume it.
2
Configure the calling side (Account A).
Attach an IAM policy to the LambdaExecutionRole allowing the action sts:AssumeRole on the resource arn:aws:iam::444455556666:role/CrossAccountDynamoDBRole.
This grants the source role the necessary authorization to call the STS AssumeRole API.
3
Configure the receiving side (Account B).
Update the trust policy of CrossAccountDynamoDBRole to specify the ARN of the LambdaExecutionRole (arn:aws:iam::111122223333:role/LambdaExecutionRole) as the principal and allow sts:AssumeRole.
This establishes the trust relationship, allowing the principal from Account A to assume the role in Account B.

Key Concept

Cross-account IAM role assumption requires configuration on both the source account (identity policy permitting sts:AssumeRole) and the destination account (trust policy permitting the source identity).
Question 32Question

A developer is setting up an AWS CodeDeploy deployment group for an in-place deployment of a web application to a fleet of Amazon EC2 instances. The deployment fails during the DownloadBundle phase because the CodeDeploy agent on the EC2 instances cannot access the deployment bundle in the Amazon S3 bucket. Additionally, the developer needs to store database credentials securely and retrieve them during the deployment process rather than packaging them in the deployment bundle.

Which two actions should the developer take to resolve these issues? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Attach an IAM policy to the EC2 instance profile role that allows the s3:GetObject action on the S3 bucket containing the deployment bundle.; Store the database credentials as SecureString parameters in AWS Systems Manager Parameter Store, and write a script in the AppSpec BeforeInstall hook to retrieve them.

Answer

Attach an IAM policy to the EC2 instance profile role that allows the s3:GetObject action on the S3 bucket containing the deployment bundle, and store the database credentials as SecureString parameters in AWS Systems Manager Parameter Store, retrieving them in the AppSpec BeforeInstall hook.
The correct options involve configuring the EC2 instance profile role with the appropriate S3 read permissions so the CodeDeploy agent can download the bundle, and securely storing credentials in Systems Manager Parameter Store as SecureString parameters, retrieving them during a valid EC2 lifecycle hook like BeforeInstall.

Step-by-Step Solution

1
Analyze the cause of the CodeDeploy agent S3 access failure.
The agent runs on the EC2 instances and uses the instance profile role to download the deployment bundle. S3 permissions must be granted to the instance profile role, not the CodeDeploy service role.
Permissions must align with the identity executing the action, which is the CodeDeploy agent on EC2.
2
Determine the secure method and correct lifecycle hook for credential retrieval on EC2.
Store credentials as SecureString parameters in AWS Systems Manager Parameter Store and retrieve them using a lifecycle hook valid for EC2, such as BeforeInstall.
This avoids plaintext storage and uses a hook that is compatible with EC2 in-place deployments.

Key Concept

AWS CodeDeploy permissions and AppSpec configuration on EC2
Question 33Question

A developer is designing a web application dashboard for a smart home IoT system. The application needs to allow users to sign in using their email and password or their social identity provider. Once authenticated, the web application must securely download and upload user-specific configuration files directly from an Amazon S3 bucket. Additionally, the application must invoke backend REST API endpoints hosted on Amazon API Gateway, which should only be accessible to authenticated users.

Which Cognito configuration should the developer choose to satisfy these requirements with the least operational overhead?

Show answer & explanation

Answer: Configure a Cognito User Pool to handle registration, login, and social identity provider federation. Secure the API Gateway REST API with a Cognito Authorizer using the User Pool ID token. Configure a Cognito Identity Pool with the User Pool as an identity provider to obtain temporary AWS credentials for S3 access.

Answer

Configure a Cognito User Pool to handle registration, login, and social identity provider federation. Secure the API Gateway REST API with a Cognito Authorizer using the User Pool ID token. Configure a Cognito Identity Pool with the User Pool as an identity provider to obtain temporary AWS credentials for S3 access.
The correct approach uses an Amazon Cognito User Pool to manage authentication (handling registration, local credentials, and social provider federation) and uses the resulting JSON Web Token (JWT) ID token to authorize API requests via the built-in API Gateway Cognito Authorizer. To access AWS resources like Amazon S3, a Cognito Identity Pool is required to exchange the User Pool tokens for temporary AWS IAM credentials.

Step-by-Step Solution

1
Select Cognito User Pools for user sign-in and management.
Users can register, sign in, and federate through social identity providers to receive JWT tokens.
Cognito User Pools serve as the user directory and handle the authentication flow.
2
Integrate API Gateway with the Cognito User Pool.
API Gateway uses a native Cognito Authorizer to validate incoming ID tokens directly.
This secures the REST API without requiring custom Lambda code or credentials exchange for API calls.
3
Configure a Cognito Identity Pool with the User Pool as a provider.
The client application exchanges the User Pool token for temporary AWS IAM credentials.
These temporary credentials allow the client application to directly and securely upload files to Amazon S3.

Key Concept

Distinction between Cognito User Pools (authentication and user directory) and Cognito Identity Pools (authorization and temporary AWS credentials exchange), as well as integrating User Pools with API Gateway Cognito Authorizers.
Estimated Time:1m 30s
Question 34Question

A developer is deploying an application on an Amazon EC2 instance. The application is configured to read configuration templates from an Amazon S3 bucket. The developer creates an IAM role named `AppConfigReadRole` with an attached policy that allows `s3:GetObject` on the target bucket. However, the application fails to retrieve the templates and receives an 'Access Denied' error. The developer inspects the trust policy of `AppConfigReadRole` and finds the following document:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

Which of the following modifications to the trust policy will resolve the Access Denied error and allow the EC2 instance to assume the role?

Show answer & explanation

Answer: Change the principal service in the trust policy from `lambda.amazonaws.com` to `ec2.amazonaws.com`.

Answer

Changing the service principal in the trust policy from `lambda.amazonaws.com` to `ec2.amazonaws.com`.
The trust policy of an IAM role determines which principals are allowed to assume it. For an application running on an Amazon EC2 instance to assume a role via an instance profile, the role's trust policy must specify the EC2 service principal (`ec2.amazonaws.com`) under the `Principal.Service` key, along with the `sts:AssumeRole` action. The original policy mistakenly trusted the Lambda service principal (`lambda.amazonaws.com`), which prevented the EC2 instance from assuming the role.

Step-by-Step Solution

1
Identify the compute environment where the application is running.
The application is running on an Amazon EC2 instance.
Understanding the host environment determines which AWS service principal needs permission to assume the IAM role.
2
Examine the trust policy of the `AppConfigReadRole` IAM role.
The principal is currently set to `lambda.amazonaws.com`.
An incorrect principal in a trust policy prevents the target service (EC2) from obtaining temporary credentials to assume the role.
3
Update the trust policy principal to match the hosting service.
Replace `lambda.amazonaws.com` with `ec2.amazonaws.com` in the trust policy.
This configures the role to trust the EC2 service, allowing the EC2 instance profile to successfully assume the role and access the S3 bucket.

Key Concept

IAM Role Trust Policies vs Permission Policies for EC2 Instances
Question 35Question

A logistics tracking application named LogiRoute writes real-time status updates for packages to an Amazon DynamoDB table. During peak delivery hours, the application occasionally encounters ProvisionedThroughputExceededException errors when writing updates, causing the tracking requests to fail immediately. Monitoring metrics show that the table's total consumed write capacity remains well below its provisioned write capacity limit. Investigations reveal that the application's HTTP library is configured to disable automatic retries for all backend calls. How should the developer resolve these transient errors while minimizing cost?

Show answer & explanation

Answer: Configure the AWS SDK client to use exponential backoff and jitter for handling transient write errors.

Answer

Configure the AWS SDK client to use exponential backoff and jitter for handling transient write errors.
Configuring the AWS SDK client to use exponential backoff and jitter is the standard best practice for resolving transient ProvisionedThroughputExceededException errors when the overall capacity is sufficient. This allows the application to retry requests after a progressively longer, randomized delay, smoothing out traffic spikes and avoiding errors for the end user without increasing provisioned throughput costs.

Step-by-Step Solution

1
Analyze the error message and CloudWatch metrics.
Identify that the ProvisionedThroughputExceededException errors are transient and occurring even though the total consumed capacity is below provisioned limits.
This indicates that overall capacity is sufficient, but temporary bursts or micro-bursts are causing brief throttling.
2
Identify the application-side behavior.
Determine that automatic retries are disabled, causing the application to fail immediately upon receiving the exception.
AWS SDKs by default implement retry logic, but disabling or misconfiguring it causes immediate failures on transient errors.
3
Implement retry logic with backoff and jitter.
Configure the AWS SDK client to retry throttled requests using exponential backoff and randomized jitter delays.
This spreads out the retry attempts, preventing them from hitting the database simultaneously and successfully completing the writes once the transient spike subsides.

Key Concept

Handling DynamoDB transient throttling errors using SDK retries with exponential backoff and jitter.
Estimated Time:1m 30s
Question 36Question

A developer is deploying a critical update to a serverless API backend running on AWS Lambda. The application handles high-velocity flash sales where traffic spikes instantly. To eliminate cold start latencies, the developer configures Provisioned Concurrency for the Lambda function. The API backend is integrated with an Amazon API Gateway HTTP API.

During deployment, the developer uploads the new function code, publishes Version 22 of the function, and associates Provisioned Concurrency with Version 22. However, when testing the API Gateway endpoint that routes traffic to the function using the LATEST\text{LATEST} identifier, clients still experience significant cold start latencies, and CloudWatch metrics show that the provisioned concurrency is not being utilized.

What should the developer do to ensure that the API Gateway endpoint utilizes the provisioned concurrency?

Show answer & explanation

Answer: Update the API Gateway integration to target a specific Lambda alias or a published function version that has Provisioned Concurrency configured, rather than targeting the LATEST\text{LATEST} identifier.

Answer

Update the API Gateway integration to target a specific Lambda alias or a published function version that has Provisioned Concurrency configured, rather than targeting the LATEST\text{LATEST} identifier.
Provisioned Concurrency initializes a specified number of execution environments so that they are prepared to respond immediately to your function's invocations. However, AWS Lambda does not allow you to configure Provisioned Concurrency on the LATEST\text{LATEST} version of a function, and any invocations that target the LATEST\text{LATEST} identifier directly or through an alias pointing to LATEST\text{LATEST} will not utilize provisioned concurrency. Therefore, the API Gateway integration must be updated to target a published version or an alias pointing to a published version (such as Version 22) that has Provisioned Concurrency configured.

Step-by-Step Solution

1
Analyze the invocation path of the AWS Lambda function from API Gateway.
Identify that the API Gateway endpoint targets the LATEST\text{LATEST} identifier of the Lambda function.
To determine why the configured Provisioned Concurrency is not being utilized during invocation.
2
Review the AWS Lambda Provisioned Concurrency specifications and restrictions.
Understand that Provisioned Concurrency cannot be associated with or invoked through the LATEST\text{LATEST} identifier; it must be mapped to a specific published version or alias.
To identify the root cause of the cold start latency despite configuration.
3
Modify the routing configuration of the API Gateway and the Lambda function targeting.
Update the API Gateway integration target to point to a Lambda alias (e.g., pointing to Version 22) or directly to Version 22, which has Provisioned Concurrency active.
To route incoming API Gateway traffic to the pre-warmed execution environments.

Key Concept

AWS Lambda Provisioned Concurrency Routing and Versioning Rules
Estimated Time:2m 0s
Question 37Question

A team of developers is deploying a backend processing application. An AWS Lambda function is configured to run inside a private VPC subnet to securely query an Amazon RDS PostgreSQL database located in another private subnet. The function must also download configuration files from Amazon S3 and make HTTP POST requests to an external, third-party payment processing API on the public internet. Which network configuration should the developer implement to enable these connections while minimizing data transfer costs and maintaining a secure architecture?

Show answer & explanation

Answer: Deploy the Lambda function in the private subnets. Create a Gateway VPC Endpoint for Amazon S3, and configure a NAT Gateway in a public subnet to route outbound traffic to the public internet.

Answer

Deploy the Lambda function in the private subnets, configure a Gateway VPC Endpoint for Amazon S3, and deploy a NAT Gateway in a public subnet to route outbound public internet traffic.
Deploying the Lambda function in private subnets allows it to access the private RDS database securely. Using a Gateway VPC Endpoint for S3 is a cost-effective choice since Gateway Endpoints do not incur hourly or data processing charges, unlike Interface Endpoints. A NAT Gateway deployed in a public subnet is required to route outbound public internet traffic for the Lambda function in the private subnet.

Step-by-Step Solution

1
Analyze the destination targets and security requirements.
The RDS database is private (requires private subnet association), S3 is an AWS service (can use a VPC endpoint), and the payment API is on the public internet (requires a NAT Gateway or NAT instance for private resources).
To determine the networking components needed for the VPC.
2
Determine the most cost-effective and secure way to access Amazon S3.
A Gateway VPC Endpoint is free and routes traffic directly to S3 without going through the NAT Gateway, saving data processing fees.
To minimize data transfer costs as requested.
3
Configure the route table for the private subnets where the Lambda function resides.
Add a route directing 0.0.0.0/00.0.0.0/0 traffic to the NAT Gateway in the public subnet.
To enable outbound internet access to the payment gateway API.

Key Concept

VPC networking for AWS Lambda, including NAT Gateway and VPC Endpoints.
Estimated Time:1m 30s
Question 38Question

An image processing application uses an Amazon SQS queue to trigger an AWS Lambda function that processes batch metadata and fetches external assets via HTTPS. The Lambda function is placed in a private VPC subnet to securely query an Amazon RDS PostgreSQL DB instance in the same VPC. During testing, the developer observes two issues: the Lambda function fails to connect to the external assets API, and several messages from the SQS queue are being processed multiple times, causing duplicate entries in the database. The Lambda function's timeout is set to 55 minutes. Which two actions should the developer take to resolve these issues? (Select two.)

Select all that apply

Show answer & explanation

Answer: Configure a NAT Gateway in a public subnet of the VPC, and add a route in the private subnet's route table pointing 0.0.0.0/00.0.0.0/0 traffic to the NAT Gateway.; Increase the visibility timeout of the Amazon SQS queue to at least 3030 minutes, matching the recommended ratio of 66 times the Lambda function's timeout.

Answer

Configure a NAT Gateway in a public subnet of the VPC with a route for 0.0.0.0/00.0.0.0/0 in the private subnet's route table, and increase the SQS queue's visibility timeout to at least 3030 minutes.
Configuring a NAT Gateway in a public subnet and updating the private subnet's route table ensures that the Lambda function can route outbound HTTPS requests to the internet. Concurrently, increasing the SQS visibility timeout to at least 66 times the Lambda timeout (3030 minutes for a 55-minute Lambda timeout) prevents SQS from releasing messages back to the queue while the Lambda function is still processing them, thereby preventing duplicate processing.

Step-by-Step Solution

1
Analyze the network failure of the Lambda function when accessing the external HTTP API.
Identify that because the Lambda function is placed in a private subnet, it lacks internet access without an outbound gateway.
Lambda functions in private subnets require a NAT Gateway or NAT instance in a public subnet to route outbound internet traffic.
2
Resolve the VPC internet connectivity issue.
Create a NAT Gateway in a public subnet, and configure a route for 0.0.0.0/00.0.0.0/0 pointing to this NAT Gateway in the private subnet's route table.
This establishes internet egress for resources in the private subnet while keeping them protected from inbound public traffic.
3
Analyze the duplicate SQS message processing issue.
Identify that the Lambda function's timeout of 55 minutes is causing messages to exceed the default SQS visibility timeout (which defaults to 3030 seconds) before completion.
When a message processing time exceeds the visibility timeout, the message becomes visible to other consumers, causing duplicates.
4
Adjust the SQS visibility timeout to align with AWS Lambda integration best practices.
Increase the visibility timeout of the SQS queue to 3030 minutes, which is 66 times the Lambda function's timeout.
AWS recommends setting the SQS visibility timeout to at least 66 times the Lambda function's timeout to prevent duplicate deliveries and handle retries.

Key Concept

Configuring private subnet internet access for AWS Lambda and aligning SQS visibility timeouts with Lambda function execution limits.
Estimated Time:2m 0s
Question 39Question

A developer is creating an AWS Lambda function that fetches metadata from an external third-party API and saves the results to an Amazon DynamoDB table. The external API requires an API key for authentication. The developer needs to optimize the function's performance by minimizing connection latency and ensuring the API key is secured according to AWS best practices.

Which two actions should the developer take to meet these requirements? (Select two.)

Select all that apply

Show answer & explanation

Answer: Initialize the DynamoDB client and the HTTP client outside of the Lambda handler method.; Store the API key in AWS Secrets Manager, retrieve it using the AWS SDK inside the Lambda function, and cache the retrieved key in a global variable outside the handler.

Answer

Initialize the DynamoDB client and the HTTP client outside of the Lambda handler method, and store the API key in AWS Secrets Manager, retrieving and caching it in a global variable outside the handler.
Initializing database clients and HTTP clients outside the handler allows AWS Lambda to reuse these connections across warm invocations, significantly optimizing execution latency. Additionally, retrieving sensitive keys from AWS Secrets Manager programmatically and caching them in global variables ensures credentials are kept secure while preventing API call overhead on subsequent executions.

Step-by-Step Solution

1
Analyze performance optimization for database and external connections in Lambda.
Determine that SDK and HTTP clients should be initialized outside of the handler function.
This allows the function to reuse the execution context, including established TCP connections, across warm invocations, reducing latency.
2
Evaluate secure credential management options for the external API key.
Identify AWS Secrets Manager as the secure repository for the API key instead of hardcoding it in the source code.
Hardcoding credentials exposes secrets in source code repositories and makes key rotation difficult, violating AWS security best practices.
3
Optimize secret retrieval latency within the Lambda execution cycle.
Implement code to retrieve the secret and cache it in a global variable declared outside the handler.
Caching the secret ensures the Lambda function only calls the Secrets Manager service during cold starts, reducing latency and cost for subsequent warm starts.

Key Concept

AWS Lambda execution context reuse and secure credential management using AWS Secrets Manager.
Question 40Question

A developer is designing a real-time inventory management microservice that uses an Amazon DynamoDB table. The application needs to support the following operations during peak traffic:

* 1010 `TransactWriteItems` operations per second. Each transaction contains two write actions: one writes a new item of 3.5 KB3.5\text{ KB}, and another updates an existing item resulting in a final size of 1.5 KB1.5\text{ KB}.
* 1515 standard `PutItem` operations per second, with an average item size of 4.5 KB4.5\text{ KB}.
* 4040 `TransactGetItems` operations per second. Each transaction reads a single item of 6 KB6\text{ KB}.

To ensure optimal performance, scalability, and security under the AWS shared responsibility model, which capacity provisioning and development strategy should the developer implement?

Show answer & explanation

Answer: Provision 195195 Write Capacity Units (WCUs) and 160160 Read Capacity Units (RCUs). Configure the application to use the default credential provider chain and retrieve items using Query or TransactGetItems operations instead of Scan.

Answer

Provision 195195 Write Capacity Units (WCUs) and 160160 Read Capacity Units (RCUs). Configure the application to use the default credential provider chain and retrieve items using Query or TransactGetItems operations instead of Scan.
The correct strategy provisions 195195 WCUs and 160160 RCUs, uses the default credential provider chain for secure authentication, and retrieves specific items efficiently via Query or TransactGetItems instead of Scan. The Write Capacity Unit (WCU) calculation is as follows: The TransactWriteItems workload consists of 1010 operations/second. Each operation has two write actions: a new item of 3.5 KB3.5\text{ KB} (rounded up to 4 KB4\text{ KB}, costing 4 WCUs×24\text{ WCUs} \times 2 for transactional writes = 8 WCUs8\text{ WCUs}) and an update resulting in a 1.5 KB1.5\text{ KB} item (rounded up to 2 KB2\text{ KB}, costing 2 WCUs×22\text{ WCUs} \times 2 for transactional writes = 4 WCUs4\text{ WCUs}). This totals 12 WCUs12\text{ WCUs} per transaction, or 120 WCUs120\text{ WCUs} for 1010 transactions/second. The standard PutItem workload consists of 1515 operations/second of 4.5 KB4.5\text{ KB} (rounded up to 5 KB5\text{ KB}, costing 5 WCUs5\text{ WCUs}). This consumes 75 WCUs75\text{ WCUs}. Summing these values gives 195 WCUs195\text{ WCUs}. The Read Capacity Unit (RCU) calculation is as follows: The TransactGetItems workload consists of 4040 operations/second. Each transaction reads one 6 KB6\text{ KB} item (rounded up to the nearest 4 KB4\text{ KB} boundary, which is 8 KB8\text{ KB}, consuming 2 RCUs2\text{ RCUs}). Since transactional reads consume double the RCUs of strongly consistent reads, each transaction costs 4 RCUs4\text{ RCUs}, totaling 160 RCUs160\text{ RCUs} for 4040 operations/second.

Step-by-Step Solution

1
Calculate the Write Capacity Units (WCUs) required for the 1010 TransactWriteItems operations per second.
120120 WCUs
Each transaction contains two write actions. Action 1 (3.5 KB3.5\text{ KB}) is rounded up to 4 KB4\text{ KB} and multiplied by 22 for transaction writes, yielding 8 WCUs8\text{ WCUs}. Action 2 (1.5 KB1.5\text{ KB}) is rounded up to 2 KB2\text{ KB} and multiplied by 22, yielding 4 WCUs4\text{ WCUs}. Total per transaction is 12 WCUs12\text{ WCUs}. For 10 operations/sec10\text{ operations/sec}, this consumes 10×12=120 WCUs10 \times 12 = 120\text{ WCUs}.
2
Calculate the WCUs required for the 1515 standard PutItem operations per second.
7575 WCUs
Each standard write of 4.5 KB4.5\text{ KB} is rounded up to 5 KB5\text{ KB} and consumes 5 WCUs5\text{ WCUs}. For 15 operations/sec15\text{ operations/sec}, this consumes 15×5=75 WCUs15 \times 5 = 75\text{ WCUs}.
3
Sum the WCU requirements to find the total provisioned WCU.
195195 WCUs
Combining the transactional writes (120 WCUs120\text{ WCUs}) and standard writes (75 WCUs75\text{ WCUs}) yields a total required write capacity of 195 WCUs195\text{ WCUs}.
4
Calculate the Read Capacity Units (RCUs) required for the 4040 TransactGetItems operations per second.
160160 RCUs
Transactional reads are strongly consistent and consume double the capacity of standard strongly consistent reads. Reading a 6 KB6\text{ KB} item requires rounding up to the nearest 4 KB4\text{ KB} boundary (8 KB8\text{ KB}), consuming 2 RCUs2\text{ RCUs} for a standard strongly consistent read. Doubling this for the transaction results in 4 RCUs4\text{ RCUs} per operation. For 40 operations/sec40\text{ operations/sec}, this consumes 40×4=160 RCUs40 \times 4 = 160\text{ RCUs}.
5
Evaluate the architectural and security configurations.
Use the default credential provider chain and query/retrieve items directly rather than scanning.
Hardcoding credentials violates security best practices, and using Scan operations instead of Query or specific read APIs is highly inefficient and consumes excess RCUs.

Key Concept

DynamoDB capacity calculation for transactional and standard operations combined with security and query optimization
Estimated Time:3m 0s
PreviousPage 2 / 78Next
All practice questions — AWS Certified Developer - Associate | Examkin