Troubleshooting and Optimization

271 soru

Soru 221Soru

A developer is containerizing a Go application that retrieves database credentials from AWS Secrets Manager using the AWS SDK for Go v2. During local development, the application is run in a Docker container using a non-root user (UID 1000) for security compliance. The developer mounts the host's `~/.aws` folder to `/home/appuser/.aws` inside the container. When the container starts, the application fails to authenticate with AWS and logs a credentials-not-found error.

*Security Notice: Writing plaintext credentials in code or container image definitions is strictly prohibited.*

Which action will resolve this local development credential issue?

Cevabı ve açıklamayı göster

Cevap: Ensure the mounted host `.aws` directory and files have read permissions for UID 1000, and verify the `AWS_SHARED_CREDENTIALS_FILE` environment variable in the container is set to `/home/appuser/.aws/credentials`.

Cevap

Ensure the mounted host `.aws` directory and files have read permissions for UID 1000, and verify the `AWS_SHARED_CREDENTIALS_FILE` environment variable in the container is set to `/home/appuser/.aws/credentials`.
The correct action is to ensure that the mounted host credentials directory is readable by the container's non-root user (UID 1000) and that the path to the credentials file is explicitly pointed to by the `AWS_SHARED_CREDENTIALS_FILE` environment variable. By default, host file permissions can block the non-root container user from accessing mounted credentials, causing credential resolution failures. Overriding the path via environment variables guarantees the SDK looks at the correct mount path.

Adım Adım Çözüm

1
Analyze container execution context and permissions
Identify that the application runs inside the container under UID 1000, but the mounted host `.aws` directory may have host-specific permissions restricting read access to non-root container users.
Permissions of mounted directories from the host must match the container process user ID to allow file reading.
2
Configure SDK path overrides using standard environment variables
Set `AWS_SHARED_CREDENTIALS_FILE` to `/home/appuser/.aws/credentials` to explicitly direct the SDK client configuration loader to the mounted credentials location.
Overriding the shared credentials path ensures the default provider chain looks at the volume mount path regardless of system path resolutions.

Anahtar Kavram

AWS SDK credential lookup precedence and volume mount permissions in local containerized development.
Tahmini Süre:1m 30s
Soru 222Soru

A frontend web application hosted on `https://app.company.internal` receives a `403 Forbidden` error with the message 'User is not authorized to access this resource' when sending requests to various endpoints of a private Amazon API Gateway REST API. The API uses a custom Lambda Authorizer with caching enabled. The developer notes that the client's first API call to `GET /orders` succeeds, but a subsequent call to `POST /payments` by the same user within a five-minute window fails with the `403 Forbidden` error. The CloudWatch logs show the authorizer executes successfully only for the first request. Which of the following is the most likely cause of this error?

Cevabı ve açıklamayı göster

Cevap: The Lambda Authorizer generated an IAM policy document that hardcoded the specific resource ARN of the first request (`GET /orders`) instead of using wildcards, which was then cached and applied to the subsequent request.

Cevap

The Lambda Authorizer generated an IAM policy document that hardcoded the specific resource ARN of the first request instead of using wildcards, which was then cached and applied to the subsequent request.
The correct answer is that the Lambda Authorizer generated a policy document that hardcoded the specific resource ARN of the first request instead of using wildcards, which was then cached and applied to the subsequent request. When authorization caching is enabled, API Gateway caches the policy document returned by the authorizer for the duration of the TTL. If the policy lists a specific resource ARN instead of a wildcard, subsequent requests to different resources or methods using the same cache key will be evaluated against that cached policy and denied with a 403 Forbidden error.

Adım Adım Çözüm

1
Analyze the log behavior: the authorizer only runs on the first request and caching is enabled.
Confirm that subsequent requests are authorized using the cached policy statement rather than fresh authorizer execution.
This isolates the failure to how the cached policy document is evaluated by API Gateway for subsequent endpoints.
2
Examine the mismatch between the successful request (`GET /orders`) and the failed request (`POST /payments`).
Determine that the cached policy document must lack permissions for the `POST /payments` resource ARN.
If the authorizer code dynamically generates a policy containing the exact request ARN of the initial request and caching is enabled, subsequent calls to other endpoints with the same token will fail.
3
Identify the proper resolution for this authorization caching behavior.
The authorizer must return a policy resource ARN using wildcards (e.g., `arn:aws:execute-api:region:account-id:api-id/stage/*`) to cover all potential client calls during the cache TTL.
This allows the cached authorization state to apply correctly across different endpoints of the API.

Anahtar Kavram

API Gateway Lambda Authorizer Caching and Policy Evaluation
Soru 223Soru

A developer is monitoring a web application that writes log events to an Amazon CloudWatch Logs log group in the following JSON format:

{
"requestPath": "/payment/process",
"responseCode": 502,
"responseTimeMs": 1500
}

The developer needs to configure a CloudWatch metric filter to count the occurrences of failed payment requests where the `responseCode` is 502502 and the `responseTimeMs` is greater than 10001000 milliseconds.

Which of the following configurations are valid for this metric filter or represent correct troubleshooting actions to ensure the filter works as intended? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Define the metric filter pattern as `{ .responseCode = 502 && .responseTimeMs > 1000 }` to match the JSON properties.; Ensure that all application logs are written as valid JSON objects, as the JSON filter pattern will ignore malformed JSON or plain text.

Cevap

The correct configurations are defining the metric filter pattern as `{ .responseCode = 502 && .responseTimeMs > 1000 }` and ensuring that all application logs are written as valid JSON objects.
The correct choices are using the single equals operator (`=`) inside curly braces to query JSON properties, and ensuring the log events are valid JSON. CloudWatch JSON metric filter syntax requires a single equals sign for comparison and will completely ignore log events that do not conform to valid JSON formatting.

Adım Adım Çözüm

1
Analyze the format of the incoming logs to determine the appropriate filter syntax.
The logs are structured in JSON format, which means curly brace syntax `{ ... }` must be used instead of space-delimited bracket syntax `[ ... ]`.
CloudWatch Logs treats JSON and space-delimited logs differently, and using the wrong syntax results in zero matches.
2
Review the comparison operator syntax for JSON metric filters.
Confirm that a single equals sign (`=`) is the valid comparison operator for matching property values in JSON filter patterns.
Programming-style double equals (`==`) is invalid in CloudWatch filter patterns and will prevent correct evaluation.
3
Verify log ingestion format constraints.
Ensure all log entries are valid, well-formed JSON objects.
If a log entry contains malformed JSON, CloudWatch Logs will fail to parse the fields, and the filter pattern will not match the event.

Anahtar Kavram

JSON Metric Filter Syntax and Validation in CloudWatch Logs
Tahmini Süre:2m 0s
Soru 224Soru

A developer is testing a Java application locally that uses the AWS SDK for Java v2 to retrieve objects from an Amazon S3 bucket. The application initializes the S3 client using S3Client.create(). When running the application locally, it fails with a software.amazon.awssdk.core.exception.SdkClientException stating that it is unable to load credentials from any of the providers in the default chain. The developer has configured the credentials in the local ~/.aws/credentials file under a profile named developer-local.

Which two actions should the developer take to resolve this credentials loading issue? (Select two.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Set the environment variable AWS_PROFILE to developer-local in the local command shell before running the application.; Define the JVM system property -Daws.profile=developer-local when launching the Java application.

Cevap

Setting the AWS_PROFILE environment variable to developer-local or defining the JVM system property -Daws.profile=developer-local directs the AWS SDK for Java v2 to use the credentials associated with that profile from the credentials file.
The correct options are setting the environment variable AWS_PROFILE to developer-local or using the JVM system property -Daws.profile=developer-local. The DefaultCredentialsProvider in the AWS SDK for Java v2 automatically checks the system property and the environment variable to determine which profile to use when loading credentials from the shared credentials file.

Adım Adım Çözüm

1
Analyze the client exception showing that the default credentials provider chain is unable to find any credentials.
Understand that the application uses the default S3Client.create() method, which checks standard environment variables, system properties, and profiles.
Since credentials are set under a custom profile ('developer-local') instead of the default profile, the SDK needs to be directed to look up the correct profile.
2
Evaluate mechanisms to specify the profile name to the SDK without modifying the code.
Identify that setting the environment variable AWS_PROFILE or using the system property -Daws.profile are standard methods supported by the AWS SDK for Java v2.
Both methods configure the environment so the default credentials provider reads the 'developer-local' credentials block from the credentials file.

Anahtar Kavram

AWS SDK Credential Provider Chain Resolution for Local Development Profiles
Soru 225Soru

A `502 Bad Gateway` error occurs when a locally running Electron desktop application sends an HTTP `POST` request to an Amazon API Gateway REST API. The developer also notices a CORS failure message in the application logs: 'Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin'. The API Gateway endpoint uses a Lambda proxy integration. The backend Lambda function's logs in Amazon CloudWatch show that the function completes successfully and returns the following structure:

{
"status": 200,
"body": {
"message": "Data processed successfully",
"itemId": "12345"
}
}

Which changes must the developer make to resolve both the `502 Bad Gateway` error and the CORS block? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Modify the Lambda function's output to use the key 'statusCode' instead of 'status', and convert the JSON object in 'body' into a stringified JSON format.; Add a 'headers' object containing the 'Access-Control-Allow-Origin' key set to 'http://localhost:8080' inside the Lambda function's returned JSON payload.

Cevap

To resolve the issues, the developer must modify the Lambda function to return a correctly formatted JSON response with a 'statusCode' key and a stringified JSON 'body' to resolve the 502 Bad Gateway error. The developer must also add the 'Access-Control-Allow-Origin' header to the 'headers' map in the Lambda function's response to resolve the CORS block.
To fix the 502 Bad Gateway error under a Lambda proxy integration, the Lambda function's output must contain the 'statusCode' key (rather than 'status') and the 'body' must be stringified. To resolve the CORS failure, the response payload from the Lambda function must explicitly contain the CORS headers, such as 'Access-Control-Allow-Origin', in the 'headers' object.

Adım Adım Çözüm

1
Correct the response key.
Change the key 'status' to 'statusCode' in the Lambda function's return payload.
API Gateway's parser requires the exact key name 'statusCode' to interpret the HTTP response status code in a Lambda proxy integration.
2
Stringify the body content.
Apply JSON.stringify() to the 'body' object.
Under Lambda proxy integration, API Gateway expects the 'body' property to be a raw text string, not a nested JSON object.
3
Add the CORS header to the Lambda response.
Insert 'headers': { 'Access-Control-Allow-Origin': 'http://localhost:8080' } into the Lambda return object.
Since Lambda proxy bypasses API Gateway's integration responses, the backend function must return all HTTP headers required by the client browser.

Anahtar Kavram

Lambda Proxy Integration Response Format and CORS Configuration
Soru 226Soru

A developer is troubleshooting an application locally on their workstation. They are running a Node.js application that uses the AWS SDK for JavaScript (v3) to upload objects to an Amazon S3 bucket.

The developer has configured a profile named `staging` in their local `~/.aws/credentials` file:

ini
[staging]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

They also set the following environment variables in their terminal session:

bash
export AWS_PROFILE=staging
export AWS_ACCESS_KEY_ID=AKIAIADSTESTINGEXAMPLE
export AWS_SECRET_ACCESS_KEY=mockKeyStagingExampleKey

When running the application, the developer receives access denied errors because the SDK attempts to authenticate using the `AKIAIADSTESTINGEXAMPLE` credentials (which are invalid) rather than the credentials specified in the `staging` profile.

Which action should the developer take to ensure the SDK uses the `staging` profile credentials?

Cevabı ve açıklamayı göster

Cevap: Unset the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.

Cevap

Unset the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
The correct action is to unset the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables. The AWS SDK default credential provider chain evaluates environment variables for credentials first. If AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set, they are used immediately, ignoring any configured profiles or file-based credentials. By unsetting these variables, the provider chain falls back to using the profile specified in the AWS_PROFILE environment variable, which resolves to the staging credentials.

Adım Adım Çözüm

1
Analyze the AWS SDK default credential provider chain resolution order.
Identify that the chain checks environment variables (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY) first, before shared credentials/config files or the AWS_PROFILE variable.
This explains why the invalid credentials in the environment variables are being used instead of the configuration under the 'staging' profile.
2
Determine the necessary change to make the SDK fall back to the credentials file.
Unsetting the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables removes them from the top of the provider chain.
Once the explicit credentials variables are cleared, the default chain falls back to looking at the AWS_PROFILE environment variable and the credentials file.

Anahtar Kavram

AWS SDK credential provider chain precedence
Soru 227Soru

A developer is troubleshooting an application deployed on Amazon ECS that writes logs to an Amazon CloudWatch Logs log group. The developer created a CloudWatch subscription filter to route log events containing the phrase `CRITICAL_ERROR` to an AWS Lambda function for real-time alerting. Although the developer verified that `CRITICAL_ERROR` is present in the log streams, the Lambda function is never invoked. Which two configurations or troubleshooting steps should the developer verify to resolve this issue?

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Verify that the resource-based policy of the target Lambda function allows the CloudWatch Logs service principal (`logs.amazonaws.com`) to perform the `lambda:InvokeFunction` action.; Confirm that the subscription filter pattern matches the exact casing of `CRITICAL_ERROR`, as CloudWatch Logs filter patterns are case-sensitive.

Cevap

Verify that the resource-based policy of the target Lambda function allows the CloudWatch Logs service principal to perform the invoke action, and confirm that the subscription filter pattern matches the exact casing of the error keyword, as CloudWatch Logs filter patterns are case-sensitive.
The correct options state that the Lambda resource-based policy must allow the CloudWatch Logs service principal to invoke the function, and that the filter pattern casing must be verified due to case sensitivity. CloudWatch Logs invokes Lambda asynchronously using a push model. For this invocation to succeed, the Lambda function must have a resource-based policy that explicitly allows 'logs.amazonaws.com' to call 'lambda:InvokeFunction'. Furthermore, CloudWatch subscription filters perform case-sensitive matching on term literals, meaning any casing mismatch will prevent matches and invocations.

Adım Adım Çözüm

1
Analyze the log delivery model of CloudWatch subscription filters.
CloudWatch Logs uses a push-model to invoke target Lambda functions, which requires resource-based permissions on the target Lambda function.
Since CloudWatch Logs is initiating the invocation, it must have the lambda:InvokeFunction permission granted to logs.amazonaws.com in the Lambda resource-based policy.
2
Examine the filter pattern matching characteristics.
CloudWatch Logs filter patterns are case-sensitive when evaluating text patterns.
If the subscription filter pattern is defined with incorrect casing, it will not match the log messages containing 'CRITICAL_ERROR'.

Anahtar Kavram

CloudWatch Logs subscription filters push events to target destinations like AWS Lambda using resource-based policies for authorization, and evaluate log streams using case-sensitive pattern matching.
Soru 228Soru

A CORS preflight blocked error is displayed in the browser console when a client-side SvelteKit application hosted on https://manager.fleet-ops.net sends a POST request to an Amazon API Gateway REST API. The request includes a custom HTTP header named X-Client-Session-ID. The developer had previously enabled CORS on the API Gateway resource, which created an OPTIONS method returning the standard headers Access-Control-Allow-Origin and Access-Control-Allow-Methods. Which action must the developer take to resolve this CORS validation error?

Cevabı ve açıklamayı göster

Cevap: Update the API Gateway OPTIONS method integration response to include X-Client-Session-ID in the Access-Control-Allow-Headers header value, and redeploy the API.

Cevap

Update the OPTIONS method integration response in API Gateway to include the custom header in the Access-Control-Allow-Headers list, then deploy the API.
When a client application includes a custom HTTP header such as X-Client-Session-ID, the browser automatically sends a preflight OPTIONS request before the actual POST request. The OPTIONS method is typically configured in API Gateway using a Mock integration. To allow the request to proceed, the OPTIONS method's integration response must include the custom header name in its Access-Control-Allow-Headers value. The API must then be redeployed to apply the configuration change.

Adım Adım Çözüm

1
Identify the stage of the failure.
The failure occurs during the preflight (OPTIONS) request, before the actual POST request is sent.
Since the client application includes a custom header, the browser initiates a preflight request which must pass CORS validation first.
2
Identify the required header parameter for custom headers.
The response to the preflight OPTIONS request must include the Access-Control-Allow-Headers header containing the name of the custom header.
Browsers reject requests with custom headers unless the destination server explicitly lists those headers as allowed.
3
Apply the configuration change and deploy.
Add the custom header to the OPTIONS method integration response in API Gateway and deploy the API to push changes to the active stage.
Changes made to the API Gateway configuration do not take effect until the API is deployed to a stage.

Anahtar Kavram

CORS preflight request handling with custom headers in API Gateway
Soru 229Soru

A developer is building a mobile application that needs to upload user-generated files directly to a private Amazon S3 bucket. The developer has configured an Amazon Cognito User Pool to handle user registration and sign-in. After successfully logging in, users receive JSON Web Tokens (JWTs), but the application receives an Access Denied error (HTTP 403) when attempting to upload files using the AWS SDK. Which two actions should the developer take to resolve this authorization failure? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Create and configure an Amazon Cognito Identity Pool, specifying the Cognito User Pool as the authentication provider.; Attach an IAM policy to the Cognito Identity Pool's authenticated IAM role that allows the s3:PutObject action on the target S3 bucket.

Cevap

Create and configure an Amazon Cognito Identity Pool with the User Pool as the authentication provider, and attach an IAM policy allowing the s3:PutObject action to the authenticated IAM role associated with the Identity Pool.
To resolve the authorization failure for direct S3 uploads, the application needs to use an Amazon Cognito Identity Pool to exchange Cognito User Pool tokens for temporary AWS credentials, and the authenticated IAM role associated with the Identity Pool must have an IAM policy attached that grants the s3:PutObject permission.

Adım Adım Çözüm

1
Integrate Cognito Identity Pools
The application can now exchange authentication tokens for temporary AWS security credentials.
Cognito User Pools only authenticate users (providing identity tokens), but Cognito Identity Pools are required to authorize users to access AWS services directly by providing temporary AWS credentials.
2
Define permissions for authenticated users
The authenticated IAM role is configured with write permissions to the S3 bucket.
Once the identity pool is established, AWS assigns an IAM role to authenticated users. This role must carry the specific permissions (such as s3:PutObject) required to perform actions on the target AWS resource.

Anahtar Kavram

Federated identities in Cognito require both a User Pool for authentication and an Identity Pool for authorizing direct access to AWS resources using IAM roles.
Tahmini Süre:2m 0s
Soru 230Soru

A client-side Angular dashboard hosted on https://dashboard.cloudflow.net is integrated with an Amazon API Gateway REST API. When sending a PUT request to update user preferences, the browser console displays a CORS preflight blocked error. The API Gateway is configured with a Lambda proxy integration. Which two actions must the developer perform to resolve this issue? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Configure the API Gateway resource to handle the OPTIONS preflight request and return the appropriate Access-Control-Allow-Methods and Access-Control-Allow-Origin headers.; Update the backend Lambda function response payload to include the Access-Control-Allow-Origin header in the headers map.

Cevap

Configure the API Gateway resource to handle the OPTIONS preflight request and return the appropriate Access-Control headers, and update the backend Lambda function response payload to include the Access-Control-Allow-Origin header in the headers map.
Resolving a CORS issue with a Lambda proxy integration requires addressing two parts of the request cycle: the preflight handshake and the actual request. First, the OPTIONS preflight request must be enabled on the API Gateway resource to return the allowed methods, headers, and origin. Second, because it is a proxy integration, the backend Lambda function itself must return the Access-Control-Allow-Origin header in the response payload of the actual request.

Adım Adım Çözüm

1
Configure the OPTIONS method in API Gateway.
The API Gateway OPTIONS method handles the preflight handshake, returning Access-Control-Allow-Methods, Access-Control-Allow-Origin, and Access-Control-Allow-Headers to satisfy browser preflight checks.
Before sending non-simple HTTP requests (such as PUT), browsers send a preflight OPTIONS request to verify permissions.
2
Modify the backend Lambda function code to return CORS headers.
The Lambda function's return payload now includes the Access-Control-Allow-Origin header within its headers block, alongside the statusCode and body fields.
With Lambda proxy integrations, API Gateway does not modify the integration response headers; the backend integration itself must supply the required CORS headers for the actual request.

Anahtar Kavram

Handling CORS in API Gateway with Lambda Proxy Integration
Soru 231Soru

A developer has deployed a Java application on an Amazon EC2 instance. The application logs details, including multi-line stack traces, to a local file at `/var/log/app/output.log`. The developer has configured the unified Amazon CloudWatch agent on the instance to stream these logs to a CloudWatch Logs log group. However, when viewing the logs in the CloudWatch console, each line of a single Java stack trace appears as a separate log event, making troubleshooting difficult. Which action should the developer take to group each multi-line stack trace into a single log event?

Cevabı ve açıklamayı göster

Cevap: Configure the `multi_line_start_pattern` parameter in the Amazon CloudWatch agent configuration file to define a regular expression matching the start of each logical log message.

Cevap

Configure the `multi_line_start_pattern` parameter in the Amazon CloudWatch agent configuration file to define a regular expression matching the start of each logical log message.
Configuring the `multi_line_start_pattern` parameter in the CloudWatch agent configuration file allows the agent to identify the start of a new log event using a regular expression (e.g., matching a timestamp). Any subsequent lines that do not match the pattern are treated as part of the current log event, ensuring that multi-line stack traces are correctly grouped and ingested as a single event.

Adım Adım Çözüm

1
Identify where the log grouping needs to occur.
Determine that log grouping must happen at ingestion time on the source instance (EC2) rather than inside CloudWatch Logs.
Once logs are transmitted as separate events, CloudWatch Logs does not provide a feature to merge them back into a single event.
2
Locate the Amazon CloudWatch agent configuration file on the EC2 instance.
Access the JSON configuration file, typically located at `/opt/aws/amazon-cloudwatch-agent/bin/config.json`.
The agent configuration controls how log files are read and streamed.
3
Add the `multi_line_start_pattern` setting to the log file configuration section.
Specify a regex pattern (e.g., matching the timestamp format of the log) that indicates the beginning of a new log entry.
The agent will group all lines that do not match the start pattern into the current log entry, maintaining the integrity of the stack trace.

Anahtar Kavram

Handling multi-line log events with the CloudWatch Agent configuration
Tahmini Süre:1m 30s
Soru 232Soru

A developer is deploying a containerized application to Amazon ECS on AWS Fargate. The application code is designed to use the AWS SDK to retrieve database credentials from AWS Secrets Manager at startup.

The ECS task definition is configured with the following parameters:
- taskRoleArn set to ecs-app-task-role
- executionRoleArn set to ecs-app-execution-role

The developer attached an IAM policy allowing secretsmanager:GetSecretValue to the ecs-app-execution-role. However, when the container starts, the application throws an AccessDeniedException when executing the GetSecretValue SDK call.

What should the developer do to resolve this authorization failure?

Cevabı ve açıklamayı göster

Cevap: Attach the IAM policy allowing secretsmanager:GetSecretValue to the ecs-app-task-role.

Cevap

Attach the IAM policy allowing secretsmanager:GetSecretValue to the ecs-app-task-role.
The correct action is to attach the permission policy allowing secretsmanager:GetSecretValue to the ECS Task Role (ecs-app-task-role). When an application runs inside an ECS container and makes calls to AWS services using the AWS SDK, the SDK retrieves credentials from the task's credential provider, which are associated with the ECS Task Role. The ECS Task Execution Role is only used by the ECS container agent to perform lifecycle tasks on behalf of the container, such as pulling container images from Amazon ECR or writing logs to Amazon CloudWatch.

Adım Adım Çözüm

1
Analyze the source of the API call.
The application code itself is using the AWS SDK at runtime to execute the GetSecretValue action.
This determines whether the task role or the execution role needs the permission.
2
Differentiate between the ECS Task Role and the ECS Task Execution Role.
The Task Role (taskRoleArn) provides permissions for the application container's SDK calls. The Task Execution Role (executionRoleArn) provides permissions for the ECS agent (e.g., pulling images, logging, or injecting secrets into environment variables).
Correctly routing permissions requires understanding which IAM entity is executing the action.
3
Reassign the permission policy.
Move or attach the IAM policy allowing secretsmanager:GetSecretValue to the ecs-app-task-role.
This resolves the authorization failure because the SDK client will assume the task role and successfully authenticate.

Anahtar Kavram

Distinction between ECS Task Role and ECS Task Execution Role for resolving runtime SDK authorization failures.
Soru 233Soru

A React Single Page Application (SPA) hosted on `https://portal.dev-ops-metrics.net` attempts to retrieve project status reports by sending an HTTP `GET` request to an Amazon API Gateway REST API. The API uses a Lambda proxy integration. Although the Lambda function executes successfully and returns a payload, the client application receives an HTTP `502 Bad Gateway` error with a response body of `{"message": "Internal server error"}`. The API Gateway CloudWatch execution logs display: `Execution failed due to configuration error: Malformed Lambda proxy response`. Which modification to the Lambda function's return payload will resolve this error?

Cevabı ve açıklamayı göster

Cevap: Return a JSON object containing the `statusCode` key with an integer value and the `body` key containing a stringified JSON representation of the data.

Cevap

The Lambda function must return a JSON object containing the `statusCode` key with an integer value and the `body` key containing a stringified JSON representation of the data.
In an Amazon API Gateway REST API with Lambda Proxy integration, the backend Lambda function is responsible for constructing the complete HTTP response. The response returned by the Lambda function must be a JSON object (or dictionary) with specific keys, including `statusCode` (which must be an integer or string representing one) and `body` (which must be a string, often a stringified JSON object). Returning a response in this exact format allows API Gateway to successfully parse the result and return a valid HTTP response to the client application.

Adım Adım Çözüm

1
Analyze the CloudWatch execution log error: `Execution failed due to configuration error: Malformed Lambda proxy response`.
Identify that the integration type is Lambda Proxy, which expects a specific JSON format from the backend Lambda function.
API Gateway requires the backend response to match a strict schema in proxy integrations to automatically construct the HTTP response.
2
Review the output structure required by API Gateway Lambda Proxy integration.
The output must contain the keys `statusCode` (an integer or stringified integer) and `body` (a stringified representation of the response data).
If these specific keys are missing or formatted incorrectly, API Gateway cannot parse the response and throws an HTTP 502 error.
3
Modify the Lambda function response return statement to conform to the required JSON schema.
Construct a response dictionary containing `statusCode` and a serialized JSON string in `body`, then return it.
This satisfies the API Gateway proxy schema, allowing it to correctly construct and return an HTTP 200 response to the client.

Anahtar Kavram

Lambda Proxy Integration Response Format
Tahmini Süre:1m 30s
Soru 234Soru

A developer is troubleshooting an application where an Amazon API Gateway REST API is secured using a custom Lambda authorizer. The authorizer validates a JSON Web Token (JWT) in the request header and returns an IAM policy. The Lambda authorizer has caching enabled with a Time to Live (TTL) of 300300 seconds, using the client's `Authorization` header as the cache key.

A client application makes a request to `GET /orders/1` with a valid token and successfully retrieves the resource. Immediately afterward, the same client sends a request to `POST /orders` using the same token. The client receives a HTTP 403 Forbidden response with the message `{"message":"User is not authorized to access this resource"}`. The CloudWatch logs show that the Lambda authorizer was not invoked for the second request.

Which of the following actions should the developer take to resolve this authorization failure? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Update the Lambda authorizer function to return an IAM policy that specifies a wildcard in the resource path (e.g., `arn:aws:execute-api:region:account:apiId/stage/*`) to cover all methods and resources the client is permitted to access.; Disable authorization caching by setting the TTL to 00 seconds in the API Gateway console for the Lambda authorizer.

Cevap

Update the Lambda authorizer function to return an IAM policy with a wildcard in the resource path, and disable authorization caching by setting the TTL to 00 seconds in the API Gateway console.
The correct options are to update the Lambda authorizer function to use a wildcard in the resource path of the returned IAM policy, and to disable authorization caching by setting the TTL to 00 seconds. When caching is enabled, API Gateway caches the policy matching the cache key (the token). If the policy restricts access to the exact resource path of the first request (`GET /orders/1`), subsequent requests to other endpoints will fail with a 403 error because the cached policy does not authorize access to the new path. Using a wildcard in the resource path allows the cached policy to authorize other paths, while disabling caching altogether forces API Gateway to run the authorizer for every request.

Adım Adım Çözüm

1
Analyze the HTTP 403 response and the CloudWatch logs.
The 403 Forbidden error indicates an authorization failure, and the logs show that the Lambda authorizer was not invoked for the second request, meaning API Gateway is using a cached policy from the first request.
Since the first request succeeded and caching is enabled with a TTL of 300300 seconds, API Gateway cached the policy generated for the `GET /orders/1` resource.
2
Identify why the cached policy blocks the second request.
The cached policy restricts access to the resource of the first request (`GET /orders/1`). When the client attempts to access `POST /orders`, API Gateway evaluates the cached policy and blocks the request because the resource does not match.
By default, API Gateway caches the entire policy for the configured TTL under the specified cache key (the `Authorization` header).
3
Select the correct remediation strategies.
Updating the authorizer code to return a wildcard resource ARN (e.g., `arn:aws:execute-api:region:account:apiId/stage/*`) or disabling caching (setting TTL to 00) resolves the issue.
Wildcards allow the cached policy to apply to all resources in the stage, while disabling caching forces API Gateway to evaluate each request dynamically.

Anahtar Kavram

API Gateway Lambda Authorizer Caching Behavior
Tahmini Süre:2m 0s
Soru 235Soru

An application running on Amazon EC2 writes log events to a local file in a space-delimited text format. The CloudWatch agent is configured to send these logs to an Amazon CloudWatch Logs log group. A typical log event looks like this:

`2026-07-14 WARN req-8812 450 502`

The positions of the values represent `[timestamp, log_level, request_id, latency_ms, status_code]`.

A developer wants to create a metric filter to capture the latency of requests that result in either a `WARN` or `ERROR` log level. The metric filter must extract the `latency_ms` value to publish a custom metric. The developer's initial attempt at configuring the metric filter pattern is `{ .loglevel=="WARN".log_level == "WARN" || .log_level == "ERROR" }` with a metric value of `$.latency_ms`. This configuration does not match any log events and fails to publish the metric.

Which of the following changes must the developer make to the metric filter configuration to correctly parse the logs and extract the latency metric? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Define the filter pattern using square brackets to name the fields, such as: `[timestamp, log_level = "WARN" || log_level = "ERROR", request_id, latency_ms, status_code]`; Specify the metric value as `$latency_ms` to reference the extracted field.

Cevap

The filter pattern must be defined using square brackets to map the fields of the space-delimited log, and the metric value must reference the extracted variable using a dollar sign prefix.
To create a metric filter for space-delimited text logs (non-JSON), the filter pattern must use square brackets `[]` to define the positions of the fields, rather than curly braces `{}` which are reserved for JSON log formats. Additionally, when extracting a value to publish as a custom metric, the metric value field must reference the defined field name using a dollar sign prefix (e.g., `latencyms)insteadofJSONpathdotnotation(e.g.,latency_ms`) instead of JSON path dot notation (e.g., `.latency_ms`).

Adım Adım Çözüm

1
Identify the format of the application logs.
The log event is space-delimited, not JSON.
Understanding the log format determines whether to use JSON syntax (curly braces) or space-delimited syntax (square brackets).
2
Formulate the correct filter pattern syntax.
The filter pattern must use square brackets and single equal signs, resulting in `[timestamp, log_level = "WARN" || log_level = "ERROR", request_id, latency_ms, status_code]`.
Square brackets instruct CloudWatch to parse the log line as space-delimited tokens, and a single equals sign is used for comparison.
3
Determine the correct metric value reference syntax.
The metric value must be specified as `$latency_ms`.
For space-delimited logs, CloudWatch Logs requires variable references to be prefixed with a dollar sign to distinguish them from literal strings.

Anahtar Kavram

CloudWatch Logs Metric Filter pattern syntax differences between JSON and space-delimited log formats
Tahmini Süre:2m 0s
Soru 236Soru

A developer has deployed a Java application on an Amazon EC2 instance. The application is designed to retrieve database credentials from AWS Secrets Manager using the AWS SDK. The credentials are encrypted using a customer managed AWS KMS key. The EC2 instance is associated with an IAM instance profile that has the following IAM policy attached:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:ProductionDatabaseSecret-xyz789"
}
]
}

When the application attempts to retrieve the secret value, it receives an `AccessDeniedException` error. Which two actions should the developer take to resolve this authorization failure? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Add the `kms:Decrypt` permission to the IAM policy attached to the EC2 instance's IAM role for the customer managed KMS key.; Update the key policy of the customer managed KMS key to grant the EC2 instance's IAM role permission to perform the `kms:Decrypt` action.

Cevap

To resolve the authorization failure, the developer must grant decrypt permissions on the KMS key to the EC2 instance's IAM role, and update the KMS key's key policy to trust the EC2 instance's IAM role to perform the decryption.
When a secret in AWS Secrets Manager is encrypted with a customer managed KMS key, any entity attempting to retrieve that secret must have permissions for both `secretsmanager:GetSecretValue` and `kms:Decrypt`. Because the encryption key is customer managed, authorization requires a union of permissions from both the caller's identity policy (the EC2 instance's IAM role policy) and the resource-based policy of the KMS key (the KMS key policy). The correct options ensure that the EC2 role is granted decrypt permissions in both policy locations.

Adım Adım Çözüm

1
Identify the encryption key used by the Secrets Manager secret.
Confirm that the secret is encrypted with a customer managed KMS key rather than the default `aws/secretsmanager` key.
Default keys automatically allow the account's roles to perform decrypt operations, but customer managed KMS keys require explicit policy definitions on both the IAM role and the KMS key policy.
2
Update the IAM policy of the EC2 instance's role.
Add the `kms:Decrypt` action targeting the ARN of the customer managed KMS key.
This grants the EC2 instance application permission to execute the decryption operation through the AWS SDK when calling Secrets Manager.
3
Update the KMS key policy.
Modify the key policy to allow the ARN of the EC2 instance's role to perform `kms:Decrypt`.
KMS key policies act as resource-based boundaries; without permission in the key policy, IAM policies alone cannot grant access to a customer managed KMS key.

Anahtar Kavram

Resolving Access Denied errors in Secrets Manager when customer managed KMS keys are used by ensuring permissions exist on both the client IAM policy and the resource-based KMS key policy.
Soru 237Soru

A developer is monitoring a serverless application where the Lambda functions write structured JSON log events to Amazon CloudWatch Logs. A sample log event is shown below:

{
"request_id": "req-98765",
"status": "Failure",
"http_status": 504
}

The developer attempts to create a CloudWatch Metric Filter to count the occurrences of gateway timeouts where the request has a status of "Failure" and an http_status of 504. The developer configures the following filter pattern:

`{ .status == "Failure" && .http_status == 504 }`

After applying this filter, the metric is not populated even though log events matching these criteria are present in the log group. Which of the following explains why the metric filter is failing to match the log events?

Cevabı ve açıklamayı göster

Cevap: The metric filter pattern uses double equal signs for comparison, which is invalid syntax; the pattern must use a single equal sign for equality comparison.

Cevap

The metric filter pattern uses double equal signs for comparison, which is invalid syntax; the pattern must use a single equal sign for equality comparison.
The correct option is correct because Amazon CloudWatch Logs JSON metric filters utilize a single equal sign (=) for matching field values. The use of a double equal sign (==) is unsupported and results in the filter failing to match the JSON log events, leaving the metric unpopulated.

Adım Adım Çözüm

1
Analyze the log format and the proposed CloudWatch Metric Filter pattern.
The log format is structured JSON, and the filter pattern uses JSON path syntax: `{ .status == "Failure" && .http_status == 504 }`.
This helps determine the correct filtering rules (curly braces for JSON structures).
2
Evaluate the syntax of the comparison operators within the filter pattern.
The developer specified `==` to verify equality for both `status` and `http_status` fields.
The syntax rules of CloudWatch Metric Filters dictate which symbols are allowed for logical and comparison operators.
3
Compare the query operator with CloudWatch specifications.
CloudWatch Logs metric filter syntax uses a single `=` for equality comparisons. The double equal sign `==` is not recognized, resulting in zero matches.
Correcting the syntax to `{ .status = "Failure" && .http_status = 504 }` allows CloudWatch to correctly parse and match the JSON log fields.

Anahtar Kavram

CloudWatch Logs Metric Filter JSON Syntax and Operators
Tahmini Süre:1m 30s
Soru 238Soru

An application running on AWS Fargate writes structured JSON logs to an Amazon CloudWatch Logs log group. A developer needs to track the frequency of database connection errors. A sample log event is shown below:

{
"timestamp": "2026-07-14T12:00:00Z",
"event_type": "database_connect",
"status": "error",
"latency_ms": 2500
}

Which actions must the developer take to configure the metric filter correctly? (Select TWO.)

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Define the metric filter pattern as `{ (.event_type = "database_connect") && (.status = "error") }`; Set the metric value of the metric transformation to `1`

Cevap

Define the metric filter pattern as `{ (.event_type = "database_connect") && (.status = "error") }` and set the metric value of the metric transformation to 1.
To create a metric filter for structured JSON logs, the pattern must follow CloudWatch's JSON syntax which utilizes curly braces `{}` and dot notation (`$.property`) to reference nested keys. The logical operator `&&` is used to join the two conditions. Additionally, since the goal is to count the frequency of occurrences of these errors, the metric value must be set to `1` so that the custom metric increments by 1 for every match.

Adım Adım Çözüm

1
Determine the log event format to apply the correct filter pattern syntax.
Since the logs are structured in JSON, the filter pattern must use the JSON metric filter syntax (curly braces `{}` and `$.property` notation) instead of space-delimited or SQL-like syntax.
Applying the wrong filter syntax will result in zero matches and a failure to trigger metrics/alarms.
2
Construct the conditional expression for the filter pattern.
The correct pattern is `{ (.event_type = "database_connect") && (.status = "error") }` to target specific properties and require both conditions to be met.
This isolates the exact database connection failures needed for the metric.
3
Configure the metric transformation properties to count the events.
Set the metric value to `1` in the transformation configuration.
Using a value of 1 increments the metric count by 1 for each occurrence of the error. Using a variable field like latency would record response times rather than counting error frequency.

Anahtar Kavram

Creating CloudWatch metric filters for JSON logs to track frequency of events
Soru 239Soru

A developer is troubleshooting a mobile web application hosted on https://cargo.freight-flow.io that interacts with a backend REST API. The API is hosted on Amazon API Gateway and routes requests to an AWS Lambda function using a Lambda Proxy Integration. When the application sends a POST request to create a shipment, the browser console displays a CORS preflight blocked error, and the client receives a 502 Bad Gateway error. The developer inspects the Amazon CloudWatch logs for the Lambda function and confirms that the function executed successfully and returned the following raw dictionary:

{
"message": "Shipment created successfully",
"shipmentId": "12345"
}

Which two actions should the developer take to resolve these errors?

Geçerli olan tümünü seçin

Cevabı ve açıklamayı göster

Cevap: Configure CORS on the API Gateway resource to create an OPTIONS method that returns the required Access-Control-Allow-Origin and Access-Control-Allow-Methods headers for the preflight request.; Modify the Lambda function response to return a formatted JSON object containing statusCode, headers with Access-Control-Allow-Origin, and a stringified body.

Cevap

Configure CORS on the API Gateway resource to create an OPTIONS method for the preflight request, and modify the Lambda function response to return a formatted JSON object containing statusCode, headers with Access-Control-Allow-Origin, and a stringified body.
To resolve the CORS preflight blocked and 502 Bad Gateway errors, the developer must address two things. First, the OPTIONS preflight request must be handled by enabling CORS on the API Gateway resource, which configures a Mock integration to return the correct headers. Second, because the API uses a Lambda Proxy Integration, the backend Lambda function must return a properly structured JSON object that includes the statusCode, headers (including Access-Control-Allow-Origin), and a stringified JSON body. The current raw dictionary response format is not recognized by the proxy integration, resulting in a 502 Bad Gateway error.

Adım Adım Çözüm

1
Enable CORS on the target API Gateway resource in the AWS Console or via Infrastructure as Code.
An OPTIONS method is created on the resource with a Mock Integration that returns the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers for browser preflight checks.
This satisfies the browser's initial CORS preflight request.
2
Modify the backend Lambda function code to wrap the response payload in a standardized integration response schema.
The function now returns a JSON structure containing 'statusCode', 'headers' (with 'Access-Control-Allow-Origin' value matching the origin), and 'body' (as a stringified JSON representation of the payload).
This satisfies the response contract required by API Gateway Lambda Proxy integrations and prevents the 502 Bad Gateway error on the actual request.
3
Deploy the API Gateway stage to apply the resource and method modifications.
The changes become active, allowing the client application to successfully complete both the preflight and the actual POST requests.
API Gateway updates do not take effect until the API is deployed to a stage.

Anahtar Kavram

CORS and Lambda Proxy Integration response contracts in Amazon API Gateway.
Tahmini Süre:1m 30s
Soru 240Soru

A client-side Vue.js application hosted on `https://portal.health-insights.com` receives a `403 Forbidden` error with the message 'User is not authorized to access this resource' when attempting to fetch a user's health report. The application interacts with an Amazon API Gateway REST API secured by a custom Lambda Authorizer. The authorizer has caching enabled with a TTL of 300 seconds and is configured with `method.request.header.Authorization` as the identity source. The authorizer function dynamically builds an IAM policy that sets the `Resource` element to the incoming request's `event.methodArn` (for example, `arn:aws:execute-api:us-east-1:123456789012:apiId/prod/GET/user/profile`). A user successfully logs in and views their profile (`GET /user/profile`), but immediately receives the `403 Forbidden` error when navigating to view their reports page (`GET /user/reports`). How should the developer resolve this issue?

Cevabı ve açıklamayı göster

Cevap: Modify the Lambda Authorizer to return an IAM policy with a wildcard resource path (such as `arn:aws:execute-api:us-east-1:123456789012:apiId/prod/*/*`) instead of the specific `event.methodArn` value.

Cevap

Modify the Lambda Authorizer to return an IAM policy with a wildcard resource path (such as `arn:aws:execute-api:us-east-1:123456789012:apiId/prod/*/*`) instead of the specific `event.methodArn` value.
When caching is enabled on an API Gateway Lambda Authorizer, API Gateway uses the cached IAM policy for subsequent requests with the same token. If the policy specifies the exact `event.methodArn` (e.g., `/GET/user/profile`), any subsequent request to a different path (e.g., `/GET/user/reports`) using the same token will fail because the cached policy does not grant permission to that path. Replacing the specific path with a wildcard resource path allows the cached policy to authorize other paths during the cache TTL period.

Adım Adım Çözüm

1
Analyze the cause of the `403 Forbidden` response.
The custom Lambda Authorizer has caching enabled for 300 seconds, keyed by the Authorization header.
This means that after the first call to `GET /user/profile`, API Gateway caches the returned policy for subsequent calls with the same token.
2
Examine the policy's Resource element.
The authorizer generates a policy scoped strictly to the current request's `event.methodArn` (which is `GET /user/profile`).
Since the cached policy only grants access to `GET /user/profile`, the subsequent request to `GET /user/reports` is evaluated against this cached policy and denied.
3
Update the policy generation logic.
Modify the authorizer to use wildcards in the Resource ARN (e.g., `/prod/*/*` or `/*`) so the cached policy allows access to multiple paths under the API.
This ensures the cached policy is broad enough to permit or deny other authorized routes for the same user within the cache TTL.

Anahtar Kavram

API Gateway Lambda Authorizer Caching and Policy Scope
ÖncekiSayfa 12 / 14Sonraki