All practice questions

1542 questions

Question 101Question

A developer is attempting to deploy a serverless application using a template file named template.yaml. The file contains the following code:

yaml
Resources:
ProcessOrderFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs18.x
CodeUri: ./src
Events:
PostOrder:
Type: Api
Properties:
Path: /orders
Method: post

When deploying this template directly via AWS CloudFormation, the deployment fails with the error message: `Template format error: Unrecognized resource type: AWS::Serverless::Function`.

Which of the following additions to the template will resolve this error?

Show answer & explanation

Answer: Add `Transform: AWS::Serverless-2016-10-31` at the root level of the template.

Answer

To resolve the unrecognized resource type error, the `Transform: AWS::Serverless-2016-10-31` declaration must be added at the root level of the template. This declaration tells AWS CloudFormation to process the template using the AWS SAM translator, which converts serverless-specific resources like `AWS::Serverless::Function` into standard AWS CloudFormation resources.
The template contains an `AWS::Serverless::Function` resource, which is a custom resource type extension provided by the AWS Serverless Application Model (SAM). AWS CloudFormation does not natively recognize this resource type. To enable CloudFormation to parse and translate this template into standard resources, the `Transform: AWS::Serverless-2016-10-31` line must be included at the root level of the template. Adding this declaration resolves the parsing error.

Step-by-Step Solution

1
Analyze the error message returned during template deployment.
The error indicates that the resource type `AWS::Serverless::Function` is unrecognized by AWS CloudFormation.
This tells us that the parser is treating the template as standard CloudFormation and does not know how to translate SAM resources.
2
Check the root level of the template for the required transform declaration.
The template only has a `Resources` block and is missing the `Transform` declaration.
AWS CloudFormation requires a macro to process the SAM template format into standard CloudFormation resources.
3
Add the transform statement to the template.
Inserting `Transform: AWS::Serverless-2016-10-31` at the root allows CloudFormation to parse the SAM resources.
This macro transforms the serverless resource declarations into their underlying AWS CloudFormation resources (like `AWS::Lambda::Function` and `AWS::IAM::Role`) during deployment.

Key Concept

AWS SAM templates extend AWS CloudFormation. To deploy SAM resources using CloudFormation, the template must include the `Transform: AWS::Serverless-2016-10-31` declaration. This triggers the CloudFormation transform macro to parse and compile SAM-specific resources into standard CloudFormation resources.
Question 102Question

A logistics company is designing a REST API in Amazon API Gateway to allow partner clients to retrieve shipment data. Partners authenticate against an external OAuth 2.0 Identity Provider (IdP) and receive a JWT access token containing custom scopes like `shipments:read`. The developer wants to authenticate the tokens and enforce access control using these custom scopes at the API Gateway level with minimal custom code. Which two configuration steps should the developer perform to meet these requirements? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Create and configure an Amazon Cognito User Pool with the external IdP as a federated provider, then create a Cognito User Pool authorizer in API Gateway.; Associate the Cognito authorizer with the API method, and specify the required custom scopes in the OAuth Scopes field of the Method Request configuration.

Answer

To secure the REST API with minimal custom code, the developer should create and configure an Amazon Cognito User Pool federated with the external IdP, set up a Cognito User Pool authorizer, and then specify the required custom scopes in the Method Request configuration.
The correct options involve configuring an Amazon Cognito User Pool federated with the external Identity Provider and creating a Cognito User Pool authorizer. This allows API Gateway to handle JWT signature validation natively. By configuring the method request with the required OAuth scopes, API Gateway natively verifies that the token contains the matching scope claims, preventing unauthorized traffic from reaching the backend with zero custom code.

Step-by-Step Solution

1
Integrate the external Identity Provider with Amazon Cognito.
Amazon Cognito User Pool is created and configured with the external IdP as a federated provider, allowing API Gateway to recognize the external tokens via a Cognito User Pool authorizer.
This establishes trust and allows API Gateway to natively validate the JWT token structure and signature without custom validation code.
2
Configure the Cognito User Pool authorizer in API Gateway.
A Cognito User Pool authorizer is added to the API Gateway REST API and linked to the created Cognito User Pool.
This registers the authorizer with the API Gateway deployment so it can be associated with individual methods.
3
Enable scope validation on the API methods.
The Cognito authorizer is associated with the target method, and custom scopes (such as 'shipments:read') are added to the OAuth Scopes field in the Method Request configuration.
This configures API Gateway to automatically inspect the incoming token for the required scopes and reject unauthorized requests before they reach the backend.

Key Concept

API Gateway integration with Amazon Cognito User Pools for federated authentication and native OAuth scope validation.
Estimated Time:1m 30s
Question 103Question

A developer is deploying a Python application to Amazon ECS on AWS Fargate. The application uses the AWS SDK for Python (Boto3) to upload objects to an Amazon S3 bucket. During local testing, the developer initialized the S3 client by passing a specific profile name from their local AWS CLI configuration file. In production, the Fargate task is assigned an ECS Task Role with the required S3 permissions, but the application fails to start due to a client initialization error. Which action should the developer take to resolve this issue?

Show answer & explanation

Answer: Initialize the S3 client using the default constructor (for example, `boto3.client('s3')`) without specifying any profile name or credentials, allowing the SDK to use the default credential provider chain to retrieve credentials from the ECS container.

Answer

Initialize the S3 client using the default constructor without specifying any profile name or credentials, allowing the SDK to use the default credential provider chain to retrieve credentials from the ECS container.
Initializing the S3 client using the default constructor (for example, `boto3.client('s3')`) allows the AWS SDK to use the default credential provider chain. In an ECS container environment on AWS Fargate, this chain automatically retrieves temporary credentials via the ECS container agent using the ECS Task Role. This eliminates the need to specify a profile name (which is only present in the developer's local AWS CLI configuration) or to manage static credentials in code.

Step-by-Step Solution

1
Remove the explicit profile configuration or credentials from the Boto3 client initialization code.
The client is initialized using the default constructor, enabling the default credential provider chain.
The default credential provider chain dynamically looks for credentials in environment variables, shared credentials files, and ECS container metadata/agent endpoints in a specific order of precedence.
2
Ensure the ECS Task has the appropriate IAM Task Role assigned.
The container agent exposes a credentials endpoint for the task.
Fargate tasks use ECS Task Roles to grant containerized applications permission to interact with other AWS services.
3
Deploy the updated application container to AWS Fargate.
The SDK automatically queries the ECS container agent endpoint and retrieves temporary credentials, granting S3 access.
This matches the AWS security best practice of using temporary, IAM role-based credentials rather than static or hardcoded credentials.

Key Concept

AWS SDK Default Credential Provider Chain and ECS Task Roles
Question 104Question

A developer is building a serverless web application. The frontend, hosted on a static website in an Amazon S3 bucket, needs to call a secure backend API hosted on Amazon API Gateway. The API has a resource with `OPTIONS` and `POST` methods. The `POST` method is integrated with an AWS Lambda function using a Lambda custom integration (`AWS` integration type). To secure the API, the developer configures an Amazon Cognito User Pool authorizer and applies it to both the `OPTIONS` and `POST` methods. During testing, the frontend application fails to make requests, and the browser console displays a CORS error during the preflight phase. Additionally, the developer notes that the Lambda function cannot access the Cognito group membership claims of the authenticated user to perform fine-grained authorization. How should the developer resolve these issues?

Show answer & explanation

Answer: Set the authorization type of the `OPTIONS` method to `NONE`. In the request mapping template for the `POST` method integration request, map the `$context.authorizer.claims['cognito:groups']` context variable to a JSON property in the payload sent to the Lambda function.

Answer

Set the authorization type of the `OPTIONS` method to `NONE`. In the request mapping template for the `POST` method integration request, map the `$context.authorizer.claims['cognito:groups']` context variable to a JSON property in the payload sent to the Lambda function.
Setting the authorization type of the OPTIONS method to NONE allows the browser to perform the preflight CORS handshake without authorization tokens. Additionally, because the API uses a custom integration, request mapping templates are required to transform the incoming request and pass context variables such as `$context.authorizer.claims['cognito:groups']` to the Lambda function.

Step-by-Step Solution

1
Address the CORS preflight authorization failure.
Identify that browsers do not include credentials in CORS preflight (OPTIONS) requests, causing the authorizer on the OPTIONS method to fail. Set the OPTIONS method authorization type to NONE.
This allows the browser's preflight check to complete successfully without requiring authentication.
2
Configure the custom integration to forward user claims to the backend.
Recognize that Lambda custom integrations (unlike proxy integrations) do not forward the full request context or Cognito claims by default. Define an API Gateway request mapping template for the POST method.
The mapping template extracts the claims from `$context.authorizer.claims['cognito:groups']` and injects them into the JSON payload sent to the Lambda function, giving the function access to the group membership details.

Key Concept

Handling CORS preflight authorization and mapping Cognito authorizer context in API Gateway custom integrations
Estimated Time:3m 0s
Question 105Question

An operations team manages a production application infrastructure stack deployed via AWS CloudFormation. The stack consists of an Amazon ECS service, an Application Load Balancer (ALB), and an Amazon DynamoDB table. During a previous template update, a resource configuration error caused a failure, leaving the stack stuck in the `UPDATE_ROLLBACK_FAILED` state. Additionally, a drift detection scan indicates that another team member manually modified the ALB's security group out-of-band to allow traffic from a new partner IP range. The team must successfully deploy the new application updates while preserving the manual security group modifications. Which combination of actions should the team take to meet these requirements? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Run the `continue-update-rollback` command on the stack to return it to the `UPDATE_ROLLBACK_COMPLETE` state.; Update the CloudFormation template definition for the security group to match the manually allowed IP ranges before initiating the next stack update.

Answer

To resolve this issue, the team must run the `continue-update-rollback` command on the stack to return it to the `UPDATE_ROLLBACK_COMPLETE` state, and update the CloudFormation template definition for the security group to match the manually allowed IP ranges before initiating the next stack update.
To successfully deploy new updates while preserving the manual security group configurations, the team must first stabilize the stack by running `continue-update-rollback`, which moves it from `UPDATE_ROLLBACK_FAILED` to `UPDATE_ROLLBACK_COMPLETE`. Secondly, they must update the template code to match the manually added IP range rules. This reconciles the drift and prevents CloudFormation from overwriting the manual changes during the subsequent update.

Step-by-Step Solution

1
Address the failed rollback state
The stack transitions to the `UPDATE_ROLLBACK_COMPLETE` state.
CloudFormation stacks in the `UPDATE_ROLLBACK_FAILED` state do not accept updates. Running `continue-update-rollback` retries or bypasses the failed rollback actions to bring the stack back to a stable state.
2
Reconcile the configuration drift
The template definition is aligned with the live configuration of the security group.
Since the security group has been manually modified out-of-band, the template code must be updated to match these live settings. Otherwise, the next stack update would overwrite these manual rules or fail due to drift.
3
Perform the stack update
The stack is updated with the new template changes without losing the security group rules.
Once the stack is in a stable state and the template has been updated to reflect the drift, the stack update can proceed safely.

Key Concept

CloudFormation Stack Recovery and Drift Reconciliation
Question 106Question

A developer is building a high-security microservice that processes sensitive transaction payloads. The application uses client-side envelope encryption with an AWS KMS customer managed key. The developer must ensure that:

1. The encrypted transaction payloads are cryptographically bound to a specific TransactionIDTransactionID and VaultRegionVaultRegion to prevent decryption under any other context.
2. All cryptographic operations are logged in AWS CloudTrail with these context details for compliance auditing.

Which two actions must the developer take to implement this encryption workflow?

Select all that apply

Show answer & explanation

Answer: Call the GenerateDataKey API with the EncryptionContext parameter containing the TransactionID and VaultRegion as key-value pairs.; Pass the identical EncryptionContext key-value pairs in the Decrypt API call when decrypting the encrypted data key.

Answer

To implement this client-side envelope encryption workflow, the developer must call the GenerateDataKey API with the EncryptionContext parameter containing the TransactionID and VaultRegion as key-value pairs, and pass the identical EncryptionContext key-value pairs in the Decrypt API call when decrypting the encrypted data key.
The correct options describe the standard AWS KMS envelope encryption workflow using Encryption Context. The EncryptionContext parameter in the GenerateDataKey API call cryptographically binds the key-value pair metadata (TransactionID and VaultRegion) to the encrypted data key. During decryption, passing the identical EncryptionContext map is mandatory; otherwise, AWS KMS cannot decrypt the data key. Both calls are logged in AWS CloudTrail with the encryption context in plaintext.

Step-by-Step Solution

1
Generate a unique data key with context.
The application calls the GenerateDataKey API on AWS KMS, passing the Customer Managed Key ARN and an EncryptionContext map containing the TransactionID and VaultRegion.
This cryptographically binds the metadata to the encrypted version of the data key and records it in AWS CloudTrail.
2
Encrypt the payload locally.
The application uses the plaintext data key to encrypt the transaction payload locally, then discards the plaintext data key from memory.
This completes the client-side envelope encryption process safely without exposing the plaintext key.
3
Decrypt the data key using the identical context.
When decrypting the payload, the application calls the Decrypt API, passing the ciphertext data key and the identical EncryptionContext map.
AWS KMS validates the context against the cryptographic signature in the ciphertext. If they match, it returns the plaintext data key to decrypt the payload.

Key Concept

AWS KMS Encryption Context in Envelope Encryption
Question 107Question

A developer is implementing Attribute-Based Access Control (ABAC) in an AWS account. The developer configures an IAM role named `ProjectRunnerRole` with the following trust policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:user/AppDeveloper"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"aws:RequestTag/Project": "Phoenix",
"aws:RequestTag/CostCenter": "1001"
}
}
}
]
}

An IAM user named `AppDeveloper` in the same account attempts to assume this role by calling the `sts:AssumeRole` API and passing the session tags `Project=Phoenix` and `CostCenter=1001`. The request fails with an `AccessDenied` error. Which TWO of the following configurations are required to resolve this error and successfully allow the user to assume the role?

Select all that apply

Show answer & explanation

Answer: Update the Action element of the trust policy in ProjectRunnerRole to allow both sts:AssumeRole and sts:TagSession.; Attach an identity-based policy to the AppDeveloper user that grants both sts:AssumeRole and sts:TagSession permissions targeting the ARN of ProjectRunnerRole.

Answer

To allow the IAM user to assume the role with session tags, the trust policy of the role must include both the sts:AssumeRole and sts:TagSession actions, and the identity-based policy attached to the user must grant permissions for both actions targeting the role's ARN.
To successfully assume an IAM role while passing session tags, both the trust policy of the target role and the identity-based policy of the calling principal must explicitly allow the sts:TagSession action alongside sts:AssumeRole. The trust policy in the scenario only permits sts:AssumeRole, which causes the API call to fail with AccessDenied when tags are passed. Therefore, updating the trust policy to include sts:TagSession and attaching an identity-based policy to the caller with both permissions solves the issue.

Step-by-Step Solution

1
Analyze the error message and the trust policy structure.
The error is AccessDenied during sts:AssumeRole while trying to pass session tags, and the trust policy only permits sts:AssumeRole.
AWS STS requires explicit permission for the sts:TagSession action in the trust policy to allow callers to pass session tags.
2
Evaluate the caller's permissions.
The caller (AppDeveloper) must also have permissions to perform both sts:AssumeRole and sts:TagSession in their identity-based policy.
AWS security requires authorization on both the resource (the role trust policy) and the caller (identity-based policy) for session tag operations.
3
Differentiate between aws:RequestTag and aws:PrincipalTag.
Confirm that aws:RequestTag is the correct key because tags are passed in the request, not already attached to the user.
aws:RequestTag evaluates the tags that are passed in the API call request, whereas aws:PrincipalTag evaluates the tags attached to the calling principal.

Key Concept

IAM Session Tags and sts:TagSession Authorization
Question 108Question

A developer is configuring a release pipeline in AWS CodePipeline. The pipeline must retrieve a database password that requires automatic weekly rotation, and it must assume an IAM role in a target AWS account to deploy resources. Which of the following configuration steps are correct? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Store the database password in AWS Secrets Manager, which natively supports automatic rotation of database credentials.; Configure the trust policy of the target IAM role to allow the CodePipeline service role to assume it.

Answer

Store the database password in AWS Secrets Manager, which natively supports automatic rotation of database credentials, and configure the trust policy of the target IAM role to allow the CodePipeline service role to assume it.
Storing database credentials in AWS Secrets Manager is correct because it natively handles secrets and supports automatic weekly rotation. Additionally, configuring the trust policy of the target IAM role allows CodePipeline to assume the role and execute deployment actions in the target account.

Step-by-Step Solution

1
Determine the appropriate service for storing database credentials requiring rotation.
AWS Secrets Manager is chosen because it natively supports rotating secrets automatically.
This meets the requirement of storing a database password with automatic rotation.
2
Determine the proper method for establishing cross-account access.
Configure the trust policy of the target IAM role to allow the source account's CodePipeline service role to assume it.
Trust policies define who can assume an IAM role, which is required for cross-account execution.

Key Concept

AWS CodePipeline integrates with Secrets Manager for secret retrieval and uses cross-account IAM role assumptions defined via trust policies to perform deployments.
Question 109Question

An organization is deploying a Node.js web application to a single-instance environment on AWS Elastic Beanstalk. The application must store local application log files in a custom directory on the host Amazon EC2 instance. Additionally, the application needs to retrieve database credentials dynamically at runtime from AWS Systems Manager Parameter Store.

Which two actions must a developer take to meet these requirements?

Select all that apply

Show answer & explanation

Answer: Create a directory named `.ebextensions` at the root of the application source bundle, and place a configuration file inside it to create the custom log directory.; Attach an IAM policy with `ssm:GetParameters` permissions to the IAM role associated with the Elastic Beanstalk EC2 instance profile, and retrieve the parameters using the application code.

Answer

Create a directory named `.ebextensions` at the root of the application source bundle to place the configuration file, and attach an IAM policy with `ssm:GetParameters` permissions to the IAM role associated with the EC2 instance profile.
The correct options are creating the `.ebextensions` directory at the root to contain the configuration file, and granting Systems Manager permissions to the EC2 instance profile role. The `.ebextensions` directory is the standard location for environment customization files, and the EC2 instance profile role provides permissions to the application code running on the EC2 instances.

Step-by-Step Solution

1
Configure instance initialization using Beanstalk configuration files.
Create a directory named `.ebextensions` at the root of the source bundle and place configuration files (e.g., `.config`) inside it.
Elastic Beanstalk platform engine detects and processes configuration files only when they are placed in a folder named `.ebextensions` with a leading dot at the root level of the application zip archive.
2
Establish secure permissions for Parameter Store access.
Add `ssm:GetParameters` permissions to the EC2 instance profile role used by the environment.
Since the application code running on the EC2 instances needs to call the Systems Manager API, the instance profile role provides the necessary temporary credentials via the EC2 Instance Metadata Service.

Key Concept

AWS Elastic Beanstalk environment customization and application permissions using instance profiles.
Question 110Question

An enterprise web application requires external partner users to authenticate using their corporate SAML Identity Provider (IdP). Once authenticated, users must be able to invoke private API endpoints hosted on Amazon API Gateway and upload large log files directly to a specific folder in an Amazon S3 bucket. The S3 folder path must be isolated per partner organization based on a SAML assertion attribute named `partnerId`.

Which combination of configuration steps should a developer implement to meet these requirements with the least operational overhead? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Configure an Amazon Cognito User Pool to federate with the corporate SAML IdP, mapping the SAML partnerId assertion to a custom attribute. Set up a Cognito User Pool Authorizer on the API Gateway REST API to secure the private endpoints.; Establish an Amazon Cognito Identity Pool using the User Pool as an identity provider. Use the 'Attributes for access control' feature to map the custom partnerId attribute to a principal tag, and apply an IAM policy on the authenticated role that restricts S3 access using a ${aws:PrincipalTag/partnerId} policy variable.

Answer

Configure an Amazon Cognito User Pool federated with the SAML IdP using a Cognito User Pool Authorizer on API Gateway, and use an Amazon Cognito Identity Pool with Attributes for access control to map the custom partnerId attribute to a principal tag for dynamic S3 path restriction using the policy variable.
The correct solution involves combining Cognito User Pools and Cognito Identity Pools. The User Pool handles SAML federation and custom attribute mapping, allowing API Gateway to natively authorize requests using a Cognito User Pool Authorizer. The Identity Pool exchanges the User Pool tokens for temporary AWS credentials, utilizing the 'Attributes for access control' (ABAC) feature to securely map custom attributes to session principal tags. This lets a single IAM policy restrict S3 bucket paths dynamically using the policy variable, eliminating custom middleware.

Step-by-Step Solution

1
Set up authentication federation using an Amazon Cognito User Pool mapped to the SAML Identity Provider, mapping incoming assertions like partnerId to custom attributes.
Users can authenticate via their corporate credentials, receiving Cognito ID and access JWTs containing their partnerId custom attribute.
Provides a managed directory and token-based identity mechanism without managing credentials.
2
Configure the API Gateway endpoints with an Amazon Cognito User Pool Authorizer that validates the incoming ID/Access token directly.
Requests containing valid tokens are permitted to invoke the backend service, while invalid requests are blocked at the API Gateway layer without invoking backend compute.
Minimizes development effort and compute costs by avoiding custom Lambda validation logic.
3
Create an Amazon Cognito Identity Pool, configure the User Pool as the authentication provider, and enable 'Attributes for access control' mapping the custom partnerId attribute to the principal tag.
The identity pool returns temporary AWS credentials with the principal tag attached to the IAM session.
Allows AWS IAM to evaluate permissions dynamically based on user-specific attributes.
4
Write an IAM policy for the authenticated role referencing the dynamic principal tag variable inside the S3 resource ARN.
A single policy permits uploads only to the folder corresponding to the user's partner ID.
Enforces fine-grained authorization to S3 dynamically with zero-code IAM policy logic.

Key Concept

Federating identities with Cognito User Pools and Identity Pools, using User Pools for API Gateway authorization and Identity Pools with attribute-based access control (ABAC) for temporary AWS credentials.
Question 111Question

A developer is configuring a continuous delivery pipeline in AWS CodePipeline within AWS Account A (Tooling Account). The pipeline must build and deploy a serverless application to AWS Account B (Production Account) using AWS CloudFormation. The deployment process requires a sensitive API authentication token that is generated during the build stage and must be rotated automatically on a weekly schedule. The deployment must adhere to the principle of least privilege. Which combination of configuration steps will meet these requirements?

Show answer & explanation

Answer: Store the API token in AWS Secrets Manager in Account B and configure a weekly rotation schedule. In Account B, create an IAM role for the pipeline action with a permissions policy allowing AWS CloudFormation deployments and retrieval of the Secrets Manager secret. Edit the trust policy of this IAM role in Account B to allow the CodePipeline service role from Account A to perform sts:AssumeRole. In Account A, configure the pipeline by setting the RoleArn of the CloudFormation deploy action to the ARN of the IAM role in Account B.

Answer

Store the API token in AWS Secrets Manager in Account B, configure a weekly rotation schedule, configure the trust policy of the IAM role in Account B to allow CodePipeline in Account A to assume it, and reference this role ARN in the pipeline deploy action.
The correct option correctly identifies that AWS Secrets Manager is required for secrets needing native automatic rotation. It also correctly structures the cross-account deployment permissions: the IAM role in the target deployment account (Account B) must have a trust policy allowing the Tooling Account (Account A) pipeline service role to assume it, and this cross-account role ARN must be specified in the pipeline's deploy action configuration.

Step-by-Step Solution

1
Select the appropriate storage service for a sensitive token that requires automatic rotation.
AWS Secrets Manager is chosen because it natively supports automatic rotation (via AWS Lambda), whereas Systems Manager Parameter Store does not.
Ensures rotation requirements are met natively and cost-effectively without building custom rotation scripts.
2
Configure the cross-account IAM role in Account B (Production Account).
The role is created with permissions to deploy resources via CloudFormation and read the Secrets Manager secret. The trust policy of the role is edited to trust Account A's CodePipeline service role.
To allow cross-account access, the target account's role must trust the source account's principal to perform the sts:AssumeRole action.
3
Configure the CodePipeline action in Account A (Tooling Account).
The CloudFormation deploy action is updated to specify the RoleArn pointing to the IAM role in Account B.
This tells CodePipeline to assume the specified cross-account IAM role in Account B when executing the deploy stage.

Key Concept

Cross-account AWS CodePipeline deployments and secret management with native rotation.
Question 112Question

A developer is configuring a continuous release pipeline in AWS CodePipeline for a web application. The pipeline must include a manual approval stage before deploying the application to production, which should notify the operations team. Additionally, the subsequent build and deployment stage in AWS CodeBuild requires a database API key that must be rotated automatically every 30 days. Which combination of steps should the developer perform to meet these requirements securely? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Create an Amazon SNS topic, subscribe the operations team's email addresses, and associate the SNS topic ARN with the manual approval action in CodePipeline.; Store the database API key in AWS Secrets Manager, enable automatic rotation, and retrieve the secret in the CodeBuild buildspec file using the Secrets Manager integration.

Answer

Create an Amazon SNS topic, subscribe the operations team's email addresses, and associate it with the manual approval action; and store the database API key in AWS Secrets Manager with automatic rotation enabled, retrieving it during the build phase.
To satisfy the requirements, the developer must use an Amazon SNS topic subscribed to the operations team's email addresses and link it to the manual approval action. For the secret requiring rotation, storing the key in AWS Secrets Manager with automatic rotation enabled satisfies the 30-day rotation requirement and can be securely retrieved by CodeBuild at runtime.

Step-by-Step Solution

1
Determine the mechanism to notify the operations team of manual approvals in CodePipeline.
Identify Amazon SNS as the supported service for manual approval action notifications.
CodePipeline manual approval actions natively integrate with Amazon SNS to publish notification messages.
2
Evaluate secret storage options for the database API key requiring automatic rotation.
Select AWS Secrets Manager as the appropriate service for secret rotation.
Secrets Manager provides native automatic rotation capabilities, unlike Systems Manager Parameter Store.
3
Configure the build execution step to retrieve the secret securely.
Reference the Secrets Manager secret dynamically inside the buildspec.yml file.
Retrieving the secret at runtime prevents hardcoding sensitive credentials in source code or project settings.

Key Concept

AWS CodePipeline manual approvals and secure secret rotation integration with CodeBuild
Question 113Question

A developer is writing a backup utility that must encrypt database export files, each approximately 500 MB500\text{ MB} in size, before uploading them to an Amazon S3 bucket. The utility must use client-side envelope encryption with an AWS Key Management Service (AWS KMS) customer managed key.

Which two steps must the developer implement in the utility's code to encrypt the files securely and prepare them for storage?

Select all that apply

Show answer & explanation

Answer: Call the AWS KMS GenerateDataKey API operation by passing the customer managed key identifier to obtain both a plaintext data key and a ciphertext data key.; Encrypt the database export file locally using the plaintext data key with a symmetric encryption algorithm, and then delete the plaintext data key from memory.

Answer

Call the AWS KMS GenerateDataKey API operation by passing the customer managed key identifier to obtain both a plaintext data key and a ciphertext data key, and encrypt the database export file locally using the plaintext data key with a symmetric encryption algorithm, and then delete the plaintext data key from memory.
The correct answer combines calling the AWS KMS GenerateDataKey API to retrieve both key formats and performing the symmetric encryption locally before deleting the plaintext key from memory. Since the database export file is 500 MB500\text{ MB}, direct encryption via the AWS KMS Encrypt API is impossible due to its 4 KB4\text{ KB} payload limit. Locally encrypting with the plaintext data key and then immediately destroying it ensures maximum security.

Step-by-Step Solution

1
Generate a unique data key pair using AWS KMS.
Obtained a plaintext data key and a ciphertext data key via the GenerateDataKey API call.
The file size (500 MB500\text{ MB}) exceeds the direct encryption payload limit of 4 KB4\text{ KB} for AWS KMS, so envelope encryption must be initiated.
2
Encrypt the file locally.
The file is encrypted using a symmetric cipher (such as AES-GCM) with the plaintext data key.
Envelope encryption requires the actual data to be encrypted client-side using the generated plaintext data key.
3
Secure the encryption keys.
The plaintext data key is discarded from memory, and the ciphertext data key is saved for future decryption.
This prevents exposure of the plaintext key and allows future decryption by sending the ciphertext data key back to AWS KMS.

Key Concept

AWS KMS client-side envelope encryption workflow and payload limits
Question 114Question

A developer has configured an AWS Lambda function in Account A (111111111111111111111111) to retrieve configuration files from a secured Amazon S3 bucket in the same account. The developer created an IAM role named `LambdaS3ReaderRole` with the following trust policy and permissions policy, and assigned it as the function's execution role:

Trust Policy:

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

Permissions Policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": "arn:aws:s3:::app-config-bucket-1111/*"
}
]
}

During local testing, the developer used their own IAM user access keys, which had administrative privileges. Before deploying to the Lambda environment, the developer committed the following code:

python
import boto3
import os

def lambda_handler(event, context):
# Initialize the S3 client
s3_client = boto3.client(
's3',
aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', 'AKIAIOSFODNN7EXAMPLE'),
aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY')
)

try:
response = s3_client.get_object(
Bucket='app-config-bucket-1111',
Key='settings.json'
)
return response['Body'].read().decode('utf-8')
except Exception as e:
print(f"Error: {str(e)}")
raise e

After deploying the Lambda function, the execution fails with an `AccessDenied` error when trying to retrieve the S3 object. The developer verifies that the environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` are not set in the Lambda function's configuration.

Which of the following options explains the cause of this authorization failure, and describes the correct way to resolve it?

Show answer & explanation

Answer: The SDK client is initialized with the fallback dummy credentials because the environment variables are not set. This explicit credential initialization bypasses the default credential provider chain, preventing the Lambda function from using the temporary security credentials provided by its execution role. To resolve this, initialize the client using `boto3.client('s3')` without passing explicit credentials.

Answer

The authorization failure is caused by the explicit initialization of the boto3 client with fallback dummy credentials, which bypasses the default credential provider chain. To resolve this, initialize the client using `boto3.client('s3')` without passing explicit credentials.
The correct answer explains that explicitly initializing the SDK client with credentials (in this case, fallback dummy values because the environment variables were unset) bypasses the default credential provider chain. In a Lambda environment, the execution role's temporary credentials are automatically made available to the SDK via standard environment variables. By removing the explicit credential parameters, the SDK successfully falls back to the default provider chain and automatically retrieves the correct execution role credentials.

Step-by-Step Solution

1
Analyze the boto3 client initialization code.
The code uses `os.environ.get()` with fallback hardcoded dummy credentials ('AKIAIOSFODNN7EXAMPLE' and 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY') for the `aws_access_key_id` and `aws_secret_access_key` arguments.
To determine how the SDK is obtaining authentication credentials.
2
Evaluate the execution environment state.
The `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables are not set in the Lambda configuration, causing the SDK to use the fallback dummy strings.
To verify if the environment overrides the hardcoded fallback credentials.
3
Understand the default credential provider chain behavior in AWS Lambda.
Explicitly passing credentials to `boto3.client()` overrides the default provider chain. Normally, the SDK would automatically resolve the execution role's temporary credentials injected by the Lambda service.
To identify why the function is not using the assigned `LambdaS3ReaderRole` permissions.
4
Apply the resolution by removing the hardcoded fallback parameters.
Initializing the client as `boto3.client('s3')` allows the default credential provider chain to retrieve the role's temporary credentials, resolving the AccessDenied error.
To restore standard IAM role execution credentials usage.

Key Concept

AWS SDK Default Credential Provider Chain and Lambda Execution Roles
Estimated Time:3m 0s
Question 115Question

A developer is testing a Java application locally on their workstation. The application publishes messages to an Amazon SNS topic using the AWS SDK for Java v2. The SDK client is initialized as follows:

java
SnsClient snsClient = SnsClient.builder()
.region(Region.US_EAST_1)
.build();

The developer's workstation has a shared AWS credentials file (`~/.aws/credentials`) containing a `[default]` profile with expired credentials and a `[dev]` profile with valid credentials. In the local IDE run configuration, the environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` are set to temporary credentials from an older session that has since expired. When the application runs, it fails with an expired token error.

Which of the following configuration steps must the developer perform to ensure the application successfully authenticates using the valid credentials from the `[dev]` profile? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Remove the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables from the IDE run configuration.; Set the AWS_PROFILE environment variable to dev in the IDE run configuration.

Answer

Remove the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables from the IDE run configuration, and set the AWS_PROFILE environment variable to dev in the IDE run configuration.
The default credential provider chain in the AWS SDK for Java v2 evaluates credentials sources in a specific order: Java system properties, Environment variables, then the Shared credentials file. Because environment variables have higher precedence, the SDK uses the expired environment variables and throws an error instead of using the shared credentials file. Removing these environment variables allows the SDK to check the shared credentials file. Specifying the profile environment variable directs the SDK to load the valid credentials from the 'dev' profile instead of falling back to the expired 'default' profile.

Step-by-Step Solution

1
Analyze the credentials lookup precedence of the default credential provider chain.
The SDK checks environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) before checking the shared credentials file (~/.aws/credentials).
Since the expired credentials are set in the environment variables, the SDK uses them and fails, never reaching the profiles in the shared credentials file.
2
Unset/remove the expired credential environment variables from the IDE run configuration.
The SDK credentials provider chain falls back to checking the shared credentials file.
This allows the SDK to read profiles defined in ~/.aws/credentials.
3
Configure the SDK to use the non-default 'dev' profile.
The AWS_PROFILE environment variable is set to dev, guiding the SDK to load credentials from the [dev] profile.
Without setting AWS_PROFILE, the SDK default credentials provider will attempt to use the [default] profile, which contains expired credentials.

Key Concept

AWS SDK Credential Provider Chain Precedence and Profiles
Question 116Question

An HR management application named StaffSync records employee clock-in and clock-out events to an Amazon DynamoDB table. During the start of a morning shift, hundreds of employees clock in at the exact same minute. The application code makes direct write requests using a custom HTTP client without retry logic. This results in unhandled ProvisionedThroughputExceededException errors and application crashes, even though the table's total provisioned write capacity is not fully exhausted.

Which of the following is the most effective developer-centric solution to resolve these application crashes during brief write spikes?

Show answer & explanation

Answer: Configure the client application to retry failed writes using the AWS SDK's built-in retry mechanism with exponential backoff and jitter.

Answer

Configure the client application to retry failed writes using the AWS SDK's built-in retry mechanism with exponential backoff and jitter.
The correct option is to configure the client application to retry failed writes using the AWS SDK's built-in retry mechanism with exponential backoff and jitter. When DynamoDB throws a ProvisionedThroughputExceededException, it is often a transient error due to a brief spike in traffic. Implementing client-side retries with exponential backoff and jitter allows the client to pause, back off, and retry the request, which successfully handles the throttling event without requiring database schema changes or capacity increases.

Step-by-Step Solution

1
Identify the cause of the application failures.
The application crashes due to ProvisionedThroughputExceededException errors from transient burst traffic without any retry handling.
Understanding the transient nature of the spike explains why the client-side configuration needs adjustment rather than database re-provisioning.
2
Implement the retry strategy in the client code.
The client application automatically pauses and retries requests when throttled, spacing them out using exponential backoff and jitter.
This prevents the client from overwhelming the database with immediate retries and allows transient traffic spikes to clear.

Key Concept

Handling ProvisionedThroughputExceededException with Client-Side Retry Policies
Question 117Question

A developer is deploying a Go web application to Amazon ECS using the EC2 launch type. The application is instrumented with the AWS X-Ray SDK for Go to trace incoming HTTP requests and downstream calls to Amazon DynamoDB. The ECS task definition is configured with the awsvpc network mode and currently contains only the application container. During testing, no trace data is appearing in the AWS X-Ray console. When inspecting the container logs, the developer finds multiple errors stating that the application is unable to connect to the X-Ray daemon at 127.0.0.1:2000. Which of the following actions should the developer take to resolve this issue? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Add a sidecar container to the ECS task definition using the official AWS X-Ray daemon image.; Attach the AWSXRayWriteOnlyAccess policy to the IAM role specified as the ECS Task Role (taskRoleArn).

Answer

To resolve the tracing issue, the developer must add a sidecar container running the official AWS X-Ray daemon image to the ECS task definition and attach the AWSXRayWriteOnlyAccess policy to the ECS Task Role.
The correct actions are to add the AWS X-Ray daemon container as a sidecar and to grant the task role write access to X-Ray. In Amazon ECS with awsvpc network mode, containers in the same task share the network namespace, allowing them to communicate via localhost (127.0.0.1). Adding the daemon container enables the application to reach it over port 2000. Additionally, the daemon container requires the correct IAM permissions via the ECS Task Role to write traces to the X-Ray service.

Step-by-Step Solution

1
Analyze the log error message pointing to UDP connection refused at 127.0.0.1:2000.
Identify that the X-Ray daemon is not running or accessible within the task's network namespace.
The X-Ray SDK sends trace segments to the daemon via UDP port 2000 by default, which requires the daemon to be running locally.
2
Add the AWS X-Ray daemon container to the ECS task definition.
The daemon container starts in the same task network namespace and binds to port 2000, resolving the connection refused errors.
In awsvpc mode, all containers in a task share the localhost network interface, allowing direct communication.
3
Assign write permissions to the ECS Task Role.
Attach the AWSXRayWriteOnlyAccess policy to the Task Role so the daemon container can upload segments to the AWS X-Ray backend.
The task requires IAM authorization to authenticate with and send trace data to the X-Ray API.

Key Concept

ECS sidecar pattern deployment of the AWS X-Ray daemon and task role permission requirements.
Question 118Question

An agricultural IoT platform named AgriGrow records hourly soil telemetry data from millions of sensors deployed across global farms. The data is written to an Amazon DynamoDB table with a partition key of `FarmID` (UUID) and a sort key of `Timestamp` (ISO 8601 string). During a sudden regional weather event, the platform experiences a massive surge in sensor writes. The application starts receiving `ProvisionedThroughputExceededException` errors. CloudWatch metrics indicate that the table's total consumed Write Capacity Units (WCUs) are far below the total provisioned write capacity. The developer finds that a single large farm has thousands of active sensors writing simultaneously, creating a hot partition. The telemetry client currently fails immediately when a write is throttled. Which TWO actions should the developer take to resolve the write throttling and minimize client-side errors? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Append a random numeric suffix to the `FarmID` partition key during write operations to distribute the write volume across multiple physical partitions.; Configure the application client's AWS SDK to implement exponential backoff and jitter for request retries.

Answer

The developer should append a random numeric suffix to the partition key during write operations to distribute the write traffic, and configure the application SDK client to use exponential backoff and jitter for retrying throttled requests.
The correct actions are to append a random numeric suffix to the partition key (write sharding) and configure exponential backoff and jitter in the SDK client. In DynamoDB, each physical partition has a maximum write limit of 10001000 WCUs per second. When writes to a single partition key exceed this threshold, the requests are throttled, generating a ProvisionedThroughputExceededException. Appending a random suffix distributes the write traffic across multiple partition keys and physical partitions. Concurrently, configuring the client SDK with exponential backoff and jitter prevents immediate client-side failures by spreading out retries over randomized intervals during traffic spikes.

Step-by-Step Solution

1
Analyze the error metrics and root cause.
Identify that the ProvisionedThroughputExceededException is occurring due to a hot partition (a single FarmID key receiving excessive write throughput) rather than the overall table-level capacity being exceeded.
DynamoDB partitions have a hard limit of 10001000 WCUs per second for writes. If this limit is exceeded on a single partition key, throttling occurs even if the table has spare capacity.
2
Select a strategy to distribute the write load.
Implement write sharding by appending a random integer suffix (e.g., from 11 to NN) to the FarmID partition key when writing data.
This spreads writes across NN distinct partition keys, distributing the workload across multiple physical partitions and bypassing the 10001000 WCU single-partition limit.
3
Configure the client retry behavior.
Modify the AWS SDK client settings to use exponential backoff and jitter.
Since the client currently fails immediately upon throttling, enabling backoff and jitter allows the client to retry requests after a randomized, increasing delay, which handles transient spikes gracefully.

Key Concept

DynamoDB partition write limitations and write sharding techniques
Estimated Time:2m 0s
Question 119Question

A developer is configuring an AWS CodeBuild project to package a web application. The build process requires retrieving a database connection string from AWS Systems Manager Parameter Store and using a custom IAM role to allow CodeBuild to write the build logs to an Amazon CloudWatch Logs log group. During the first build run, the build fails immediately before the install phase with an error stating that CodeBuild is not authorized to assume the service role. Additionally, the application fails to build because the connection string path is being treated as a literal string rather than retrieving the actual database connection string value. Which of the following actions should the developer take to resolve these issues? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Update the trust policy of the custom IAM role to allow the codebuild.amazonaws.com service principal to perform the sts:AssumeRole action.; In the buildspec.yml file, define the database connection string environment variable under the parameter-store mapping in the env section.

Answer

To resolve these issues, the developer must update the trust policy of the custom IAM role to allow the AWS CodeBuild service principal to assume the role, and define the parameter under the parameter-store mapping in the buildspec.yml file.
The correct actions are updating the trust policy of the custom IAM role to trust the codebuild.amazonaws.com service principal and defining the Parameter Store variables under the parameter-store block of the env section in the buildspec.yml. This allows CodeBuild to assume the service role and resolve the parameter path into the actual connection string value.

Step-by-Step Solution

1
Inspect and update the trust relationship of the custom IAM role.
The IAM role's trust policy is configured to trust 'codebuild.amazonaws.com', allowing CodeBuild to successfully assume the role.
CodeBuild needs explicit assume role permissions in the trust policy of any custom service role it uses.
2
Update the environment variable section of the buildspec.yml.
The database connection string is placed under the 'parameter-store' mapping within the 'env' section of the buildspec.
Placing the variable under 'parameter-store' instructs CodeBuild to fetch the actual value from Systems Manager Parameter Store instead of treating the path as a static string.

Key Concept

AWS CodeBuild IAM service role trust relationships and environment variable retrieval from Systems Manager Parameter Store.
Question 120Question

A developer is troubleshooting a local Node.js application that uses the AWS SDK for JavaScript (v3) to query an Amazon DynamoDB table. The local development machine has the environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` set to credentials of a retired testing account, which causes authentication failures. The developer has a local shared credentials file (`~/.aws/credentials`) with a profile named `local-dev` that contains active credentials for the development environment. The client is initialized in the code as follows:

javascript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});

Which of the following actions will resolve this credential resolution issue and ensure the application authenticates using the `local-dev` profile? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Unset the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables, and set the `AWS_PROFILE` environment variable to `local-dev`.; Import the `fromIni` credential provider from `@aws-sdk/credential-providers` and pass it to the `credentials` configuration option of the `DynamoDBClient` constructor, specifying the `local-dev` profile.

Answer

To resolve the credential resolution issue, the developer can either unset the credentials environment variables and set the profile environment variable to specify the profile, or configure the client explicitly using the `fromIni` provider from the credential providers library to load the profile.
To resolve the credential resolution issue, the developer can either clean up the environment or configure the application client explicitly. In the default credential provider chain, environment variables containing credentials have the highest precedence. Therefore, removing the retired credentials environment variables and setting the profile environment variable forces the SDK to fall back to the shared credentials file and load the specified profile. Alternatively, explicitly configuring the client constructor with the `fromIni` provider overrides the default provider chain entirely, forcing the application to load the local-dev profile credentials directly from the local configuration files.

Step-by-Step Solution

1
Analyze the AWS SDK credential provider chain precedence.
Identify that environment variables containing credentials take precedence over configuration profiles and the shared credentials file.
This explains why the application uses the retired credentials instead of the local-dev profile.
2
Determine how to modify the environment to allow profile-based authentication.
Unsetting the credentials environment variables enables the SDK to fall back to the shared credentials file, where the profile specified by the profile environment variable will be used.
This allows the default chain to resolve the local-dev profile credentials.
3
Determine how to modify the application code to explicitly bypass the default credential provider chain.
Import and use the `fromIni` provider from `@aws-sdk/credential-providers` to explicitly load credentials from the local-dev profile.
This overrides the default credential provider chain and avoids using the environment variables.

Key Concept

AWS SDK credential provider chain precedence and local profile configuration.
Estimated Time:2m 0s
PreviousPage 6 / 78Next
All practice questions — AWS Certified Developer - Associate | Examkin