免费 AWS 认证开发人员 - 助理级考试练习
免费的 AWS 认证开发人员 - 助理(AWS Certified Developer – Associate)练习考试有助于验证您在 AWS 上构建安全、可扩展且云原生应用程序的能力。它涵盖事件驱动和无状态设计模式、身份验证与密钥管理、持续集成/持续部署(CI/CD)与部署策略,以及使用 AWS 原生工具进行性能优化、可观测性和故障排除。
Answer: C
Why:
Designing the API to be stateless and externalizing state is correct because stateless architectures allow AWS Lambda functions to scale automatically without relying on any in-memory or execution-environment–specific data. Each request is independent, and any required state (for example, session data) is stored in an external data store such as DynamoDB or ElastiCache. This aligns with serverless best practices and enables horizontal scalability.
Why not:
Option A: Lambda environment variables are shared across invocations within the same execution environment and are not intended for request-specific or user session data.
Option B: The /tmp directory is ephemeral and tied to a specific Lambda execution environment, which can be reused or destroyed at any time, making it unsuitable for session state.
Option D: Amazon API Gateway is a regional, managed service that does not support sticky sessions (session affinity) in the way a traditional Application Load Balancer (ALB) does.
Answer: B
Why:
Amazon SQS Standard is correct because it supports asynchronous message processing with at-least-once delivery, high throughput, and no ordering guarantees. This makes it ideal for decoupling microservices where message order is not required.
Why not:
Option A: Amazon SNS is a pub/sub notification service and does not provide consumer-controlled message processing or durability guarantees in the same way as SQS.
Option C: AWS Step Functions are used for workflow orchestration, not for decoupling microservices via message queues.
Option D: Amazon EventBridge is designed for event routing and integration, not guaranteed at-least-once message processing by consumers.
Answer: B and D
Why:
Option B: Dead-letter queues (DLQs) improve resilience by capturing messages that cannot be processed successfully after retries, allowing for debugging and reprocessing without data loss.
Option D: Exponential backoff retries prevent overwhelming downstream services during failures and are a core fault-tolerant design pattern in event-driven systems.
Why not:
Option A: Reserved concurrency can prevent the database from being overwhelmed; it would cause Lambda to throttle and send messages back to the queue (or to a DLQ, if configured). It is a protective measure, but doesn’t solve the retry/recovery logic as directly as B and D.
Option C: SQS-to-Lambda is natively asynchronous. You cannot “switch” it to synchronous in this architecture, and doing so would remove the decoupling benefits.
Option E: Increasing memory helps with processing speed/CPU, but it does nothing to solve connection errors at the database level; in fact, it might make the problem worse by allowing more concurrent connections.
Code Example
1table.put_item( 2 Item=item 3)
Code Example
1table.put_item( 2 Item=item, 3 ConditionExpression="attribute_not_exists(id)" 4)
Code Example
1table.update_item( 2 Key={"id": item["id"]}, 3 UpdateExpression="SET processed = :p", 4 ExpressionAttributeValues={":p": True} 5)
Code Example
1table.put_item( 2 Item=item, 3 ReturnValues="ALL_OLD" 4)
Answer: B
Why:
Using a ConditionExpression with attribute_not_exists(id) ensures that the DynamoDB PutItem operation succeeds only if the item does not already exist. This enforces idempotency and prevents duplicate writes when Lambda retries occur due to failures or reprocessing of Kinesis records.
Why not:
Option A: This overwrites existing items and does not prevent duplicate writes.
Option C: UpdateItem modifies an existing item but does not stop duplicates from being created during retries.
Option D: ReturnValues is simply a response configuration. It instructs DynamoDB to return the attributes of the item as they appeared before the operation. It has no effect on whether the write operation itself succeeds or fails based on the existing state of the database.
Answer: A and C
Why:
Option A: Using Amazon SNS with multiple Amazon SQS subscriptions enables fanout, allowing each downstream consumer to process events independently. Failures in one consumer do not impact others.
Option C: Amazon EventBridge supports scalable, event-driven routing to multiple targets using rules, providing loose coupling and fault isolation between consumers.
Why not:
Option B: A single SQS FIFO queue limits throughput and does not support multiple independent consumers effectively.
Option D: Synchronous invocation tightly couples consumers and allows failures to propagate.
Option E: DynamoDB Streams are designed for processing table changes, not high-throughput IoT telemetry ingestion and fan-out.
Answer: C
Why:
AWS Secrets Manager is purpose-built for storing sensitive application secrets such as database credentials, API keys, and tokens. It encrypts secrets at rest using AWS KMS and provides native, automatic rotation capabilities for supported services like Amazon RDS, aligning with AWS security best practices.
Why not:
Option A: Systems Manager Parameter Store (Standard) can store encrypted values, but does not support automatic rotation without custom automation.
Option B: ACM manages the life cycle and automatic renewal (rotation) of SSL/TLS certificates; however, it cannot store arbitrary application secrets, such as database passwords, API keys, or SSH keys. It is a specialized service for public and private certificates, not a general-purpose secret vault.
Option D: AWS Key Management Service (KMS) manages encryption keys, not application secrets such as passwords or tokens.
Answer: A and B
Why:
Option A: The s3:PutObject permission is required to upload objects to an S3 bucket.
Option B: When using SSE-KMS, Amazon S3 must call AWS KMS to generate a data encryption key. This requires the kms:GenerateDataKey permission on the KMS key.
Why not:
Option C: kms:Decrypt is required to read or download encrypted objects, not to upload them.
Option D: s3:ListBucket is not required to upload objects.
Option E: kms:CreateKey is an administrative permission and is not required for object uploads.
Answer: A and C
Why:
Option A: Amazon Cognito Identity Pools exchange authenticated User Pool tokens for temporary AWS credentials, ensuring no long-term credentials are exposed to users.
Option C: IAM roles mapped to Cognito Identity Pool identities allow fine-grained, scoped S3 permissions, ensuring each user can access only their own S3 prefix and enforcing the principle of least privilege.
Why not:
Option B: Allowing public write access to an S3 bucket, even with conditions, violates security best practices.
Option D: Using IAM user access keys introduces long-term credentials, which the company explicitly wants to avoid.
Option E: Storing temporary AWS credentials in Lambda environment variables is insecure and unnecessary.
Code Example
1import boto3 2 3client = boto3.client('secretsmanager') 4secret = client.get_secret_value(SecretId='db-password') 5password = secret['SecretString']
Code Example
1import boto3 2 3session = boto3.session.Session( 4 aws_access_key_id='AKIA...', 5 aws_secret_access_key='SECRET' 6) 7client = session.client('secretsmanager') 8password = client.get_secret_value('db-password')
Code Example
1import os 2password = os.environ['DB_PASSWORD']
Code Example
1import boto3 2 3client = boto3.client('ssm') 4password = client.get_parameter( 5 Name='db-password', 6 WithDecryption=True 7)
Answer: A
Why:
This code securely retrieves the secret at runtime from AWS Secrets Manager using the Lambda function’s execution role. Secrets Manager handles encryption, access control, and auditing, making this the recommended and secure approach. Additionally, this provides permissions to the resource, not the person.
Why not:
Option B: Hardcoding AWS access keys violates security best practices and bypasses IAM role-based authentication.
Option C: Storing secrets in environment variables exposes sensitive data and does not support rotation.
Option D: This code attempts to use AWS Systems Manager Parameter Store instead of AWS Secrets Manager. Even with the parameter WithDecryption set to True, it fails the requirement because the question specifically asks to retrieve the secret from Secrets Manager.
Answer: C
Why:
AWS CloudTrail records all IAM AssumeRole events, including the source IP address. Sending CloudTrail logs to CloudWatch Logs and creating metric filters allows real-time detection and alerting when roles are assumed from IP addresses outside the corporate network range.
Why not:
Option A: AWS Config is great for checking if a resource configuration has changed (e.g., Is this S3 bucket public?). It is not designed to monitor high-volume API activity, such as AssumeRole, in real-time.
Option B: VPC Flow Logs track IP traffic (packets) entering and leaving network interfaces. They do not see IAM API calls, which are handled by the AWS Global Plane, not your VPC’s private networking.
Option D: Amazon GuardDuty is a threat detection service. Its findings are not guaranteed to trigger immediate alerts for every AssumeRole event and should not be relied on exclusively. It is also more expensive and less direct than a simple CloudWatch Filter for this specific compliance check.
Answer: A and C
Why:
Option A: Lambda aliases allow each environment (dev, staging, prod) to point to a specific Lambda version. This enables fast, safe rollbacks by simply repointing the alias without changing code.
Option C: API Gateway stage variables can dynamically reference Lambda aliases, allowing the same API configuration and SAM template to be reused across environments with no code changes.
Why not:
Option B: Separating SAM templates increases maintenance overhead and violates the requirement to reuse the same template.
Option D: Using $LATEST makes deployments unpredictable and unsafe, and it does not support controlled rollbacks.
Option E: Hardcoding environment identifiers in environment variables does not control which Lambda version is invoked and does not support safe rollbacks.
Answer: B
Why:
Canary deployment using AWS SAM DeploymentPreference gradually shifts a percentage of traffic to the new Lambda version while monitoring error rates. If errors exceed a defined threshold, the deployment automatically rolls back, making this the safest and most controlled strategy.
Why not:
Option A: All-at-once deployments send 100% of traffic to the new version immediately, increasing blast radius.
Option C: Blue/green using separate API Gateway stages does not provide automatic traffic shifting or rollback based on error thresholds.
Option D: Rolling deployments are not natively supported for Lambda traffic shifting and require custom orchestration.
Code Example
1Parameters: 2 EnvironmentName: 3 Type: String 4 5Resources: 6 MyFunction: 7 Type: AWS::Serverless::Function 8 Properties: 9 Runtime: python3.11 10 Handler: app.handler 11 Environment: 12 Variables: 13 TABLE_NAME: !Sub "orders-${EnvironmentName}"
Code Example
1sam deploy
1sam deploy --parameter-overrides EnvironmentName=staging
Code Example
1sam deploy --env staging
Code Example
1sam deploy --stack-name staging
Answer: B
Why:
Using SAM parameters and passing values at deployment time with --parameter-overrides allows the same template and Lambda code to be reused across environments while dynamically configuring environment-specific resources such as DynamoDB table names.
Why not:
Option A: Deploying without parameter overrides does not set the required environment-specific value.
Option C: --env is not a valid SAM deployment option.
Option D: Changing the stack name alone does not inject the required parameter value.
Answer: C
Why:
Lambda layers enable developers to package shared libraries and dependencies separately from function code, allowing them to be reused across multiple Lambda functions. This reduces deployment package size and simplifies dependency management.
Why not:
Option A: Downloading a large library from S3 during the Lambda function’s initialization phase significantly increases cold start latency. It also forces the developer to write complex boilerplate code to manage the download and ensure the library is correctly placed in the execution environment’s path.
Option B: Custom runtime allows you to pre-install software, it carries massive operational overhead. The team would become responsible for maintaining the OS, patching security vulnerabilities, and ensuring compatibility with future Lambda updates—tasks that AWS handles automatically with standard runtimes.
Option D: Extensions are intended for sidecar processes (e.g., monitoring agents, secret caching, or security scanning). They run in a separate process from the function handler and are not the standard or efficient way to provide application-level libraries (like NumPy or SDKs) that the code needs to import or require.
Answer: B
Why:
Using SAM Parameters with --parameter-overrides is the most straightforward way to pass simple values (like integers for memory or strings for endpoints) directly to the resource properties at the time of stack creation.
Why not:
Option A: This requires hardcoding the values into the template itself. To change the memory size, you must modify the template code. Parameters are more flexible as they are injected from the outside.
Option C: Lambda memory size is a configuration property defined at the infrastructure level. You cannot change the function’s allocated memory from inside the Python/Node.js code at runtime; it must be set during deployment.
Option D: This is an anti-pattern. Duplicating resources makes the template twice as long and much harder to maintain, which violates the goal of reducing configuration drift.
Answer: B
Why:
Amazon CloudWatch Logs Insights is designed specifically for interactive log analysis using a purpose-built query language. It allows developers to quickly search, filter, and aggregate Lambda logs to identify failing invocations and understand error patterns and root causes.
Why not:
Option A: X-Ray is excellent for seeing where a failure happened in a chain of services (tracing), but it doesn’t allow you to search through the actual text of the log messages.
Option C: Athena can query logs in S3 after exporting the logs from CloudWatch to S3. However, this adds a delay and involves more operational overhead than querying them in place with Insights.
Option E: This is a powerful solution but requires setting up a domain, managing indexing, and maintaining the cluster. It is overkill for a developer simply trying to debug a function.
Answer: B and D
Why:
Option B: SNS subscription filter policies ensure that only relevant messages are delivered to each SQS queue, reducing unnecessary message delivery.
Option D: Message attributes allow messages to be tagged with metadata that filter policies can evaluate, enabling selective fanout.
Why not:
Option A: SNS FIFO topics provide ordering and deduplication but do not reduce delivery to unnecessary consumers.
Option C: Increasing SQS visibility timeout affects message reprocessing behavior, not message delivery optimization.
Option E: Long polling reduces empty receives but does not prevent messages from being delivered to irrelevant consumers.
Answer: B
Why:
AWS Lambda allocates CPU power proportionally to the configured memory size. Increasing memory from 128MB to 512 MB increases available CPU resources, which can reduce execution time and latency, even if CPU utilization previously appeared low.
Why not:
Option A: Provisioned Concurrency keeps functions warm to eliminate cold starts, but it does not change the speed of the code after it has started.
Option C: Ephemeral storage is a separate setting (defaulting to 512 MB) and is not tied to the RAM allocation.
Option D: Architecture (x86 vs. ARM) is a manual configuration choice and does not change automatically when you adjust memory.
Answer: A and C
Why:
Option A: Enabling AWS X-Ray on both API Gateway and Lambda provides end-to-end tracing, allowing you to visualize where time is spent in the request path.
Option C: Analyzing API Gateway Latency and IntegrationLatency metrics helps distinguish whether latency is caused by API Gateway itself or by the backend integration.
Why not:
Option B: DynamoDB latency is already confirmed to be low, so additional metrics will not identify the root cause.
Option D: Increasing Lambda memory changes performance characteristics but does not help identify the existing root cause.
Option E: CloudTrail data events track API activity for auditing, not request latency.
Code Example
1import json, time 2 3def lambda_handler(event, context): 4 emf = { 5 "_aws": { 6 "Timestamp": int(time.time() * 1000), 7 "CloudWatchMetrics": [ 8 { 9 "Namespace": "OrderService", 10 "Dimensions": [["Service", "Environment"]], 11 "Metrics": [{"Name": "OrdersProcessed", "Unit": "Count"}], 12 } 13 ], 14 }, 15 "Service": "Checkout", 16 "Environment": "Prod", 17 "OrdersProcessed": 1, 18 } 19 print(json.dumps(emf)) 20 return {"ok": True}
Code Example
1import boto3 2 3def lambda_handler(event, context): 4 cw = boto3.client("cloudwatch") 5 cw.put_metric_data( 6 Namespace="OrderService", 7 MetricData=[{ 8 "MetricName": "OrdersProcessed", 9 "Value": 1, 10 "Unit": "Count" 11 }] 12 ) 13 return {"ok": True}
1import json 2 3def lambda_handler(event, context): 4 print(json.dumps({ 5 "Namespace": "OrderService", 6 "MetricName": "OrdersProcessed", 7 "Value": 1, 8 "Unit": "Count", 9 "Service": "Checkout", 10 "Environment": "Prod" 11 })) 12 return {"ok": True}
Code Example
1def lambda_handler(event, context): 2 print("OrdersProcessed=1 Service=Checkout Environment=Prod") 3 return {"ok": True}
Answer: A
Why:
This code correctly emits CloudWatch Embedded Metric Format (EMF) JSON to standard output. CloudWatch automatically extracts the metric with the specified namespace, dimensions, and unit from the logs without requiring explicit PutMetricData API calls, making it ideal for Lambda-based custom metrics.
Why not:
Option B: This explicitly calls PutMetricData, which violates the requirement to avoid direct API calls.
Option C: This JSON does not follow the EMF schema required for CloudWatch to extract metrics automatically.
Option D: Plain text logs cannot be parsed into metrics using EMF.