Flashcards
AWS Certified Developer Associate Flashcards (DVA-C02)
AWS Certified Developer Associate Flashcards (DVA-C02)
Flashcard Deck
Card 1 of 90
Space
Flip Card
←→
Navigate
1# Synchronous invoke via CLI2aws lambda invoke \3 --function-name myFunction \4 --payload '{"key":"value"}' \5 response.json1import os2DB_HOST = os.environ['DB_HOST']3API_KEY = os.environ['API_KEY']1def handler(event, context):2 print(context.function_name)3 print(context.get_remaining_time_in_millis())4 return {"statusCode": 200, "body": "OK"}1# Lambda ARN using stage variable2arn:aws:lambda:us-east-1:123:function:myFunc:${stageVariables.lambdaAlias}1import boto32s3 = boto3.client('s3')3url = s3.generate_presigned_url(4 'get_object',5 Params={'Bucket': 'mybucket', 'Key': 'file.txt'},6 ExpiresIn=36007)1# boto3 automatically uses the Lambda execution role2import boto33s3 = boto3.client('s3')4s3.list_buckets()1sts = boto3.client('sts')2response = sts.assume_role(3 RoleArn='arn:aws:iam::123456789:role/MyRole',4 RoleSessionName='MySession'5)6creds = response['Credentials']1kms = boto3.client('kms')2response = kms.generate_data_key(3 KeyId='alias/mykey',4 KeySpec='AES_256'5)6plaintext_key = response['Plaintext']7encrypted_key = response['CiphertextBlob']1client = boto3.client('secretsmanager')2secret = client.get_secret_value(SecretId='prod/db/password')3password = secret['SecretString']1ssm = boto3.client('ssm')2param = ssm.get_parameter(3 Name='/myapp/db/password',4 WithDecryption=True5)6value = param['Parameter']['Value']1# S3 CORS config2[{"AllowedOrigins": ["https://myapp.com"],3 "AllowedMethods": ["GET","PUT"],4 "AllowedHeaders": ["*"]}]1packages:2 yum:3 git: []4 htop: []1version: 0.02os: linux3files:4 - source: /5 destination: /var/www/html6hooks:7 AfterInstall:8 - location: scripts/install_deps.sh9 ApplicationStart:10 - location: scripts/start_server.sh1version: 0.22phases:3 install:4 runtime-versions:5 nodejs: 186 build:7 commands:8 - npm install9 - npm test10 - npm run build11artifacts:12 files:13 - '**/*'14 base-directory: dist1Transform: AWS::Serverless-2016-10-312Resources:3 MyFunction:4 Type: AWS::Serverless::Function5 Properties:6 Handler: app.handler7 Runtime: python3.118 Events:9 Api:10 Type: Api11 Properties:12 Path: /hello13 Method: get1# Stack A export2Outputs:3 VpcId:4 Value: !Ref MyVPC5 Export:6 Name: MyVPC-ID7
8# Stack B import9Resources:10 MyInstance:11 Properties:12 VpcId: !ImportValue MyVPC-ID1# SAM canary deployment2AutoPublishAlias: live3DeploymentPreference:4 Type: Canary10Percent10Minutes1# Python instrument boto3 with X-Ray2from aws_xray_sdk.core import xray_recorder, patch_all3patch_all() # patches boto3, requests, etc.1import time, random2for attempt in range(5):3 try:4 response = call_aws_api()5 break6 except ThrottlingException:7 time.sleep((2 ** attempt) + random.random())1# Find Lambda errors in the last hour2fields @timestamp, @message3| filter @message like /ERROR/4| sort @timestamp desc5| limit 501$ aws configure2AWS Access Key ID: AKIA...3AWS Secret Access Key: ****4Default region name: us-east-15Default output format: json1$ aws configure --profile dev2$ aws s3 ls --profile dev3$ export AWS_PROFILE=dev1$ aws ec2 describe-instances \2 --query 'Reservations[*].Instances[*].InstanceId' \3 --output text1import boto32from botocore.config import Config3
4config = Config(5 retries={'max_attempts': 10, 'mode': 'standard'}6)7client = boto3.client('dynamodb', config=config)1paginator = boto3.client('s3').get_paginator('list_objects_v2')2for page in paginator.paginate(Bucket='mybucket'):3 for obj in page['Contents']:4 print(obj['Key'])1ec2 = boto3.client('ec2')2waiter = ec2.get_waiter('instance_running')3waiter.wait(InstanceIds=['i-1234567890abcdef0'])4print("Instance is running!")1# LocalStack local testing2s3 = boto3.client(3 's3',4 region_name='us-east-1',5 endpoint_url='http://localhost:4566'6)1import { DynamoDBClient, GetItemCommand } from "@aws-sdk/client-dynamodb";2const client = new DynamoDBClient({ region: "us-east-1" });3const response = await client.send(4 new GetItemCommand({ TableName: "Users", Key: { id: { S: "123" } } })5);1// SDK v3 with lib-dynamodb2import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb";3const docClient = DynamoDBDocumentClient.from(client);4const result = await docClient.send(5 new GetCommand({ TableName: "Users", Key: { id: "123" } })6);1try:2 table.get_item(Key={'id': '123'})3except ClientError as e:4 code = e.response['Error']['Code']5 if code == 'ProvisionedThroughputExceededException':6 time.sleep(2)1$ aws cloudformation deploy \2 --template-file template.yaml \3 --stack-name my-app \4 --capabilities CAPABILITY_IAM \5 --parameter-overrides Env=prod1from aws_cdk import Stack, aws_lambda as _lambda2class MyStack(Stack):3 def __init__(self, scope, id, **kwargs):4 super().__init__(scope, id, **kwargs)5 _lambda.Function(self, "MyFunc",6 runtime=_lambda.Runtime.PYTHON_3_11,7 handler="app.handler",8 code=_lambda.Code.from_asset("lambda"))1# boto3 handles multipart automatically with transfer config2from boto3.s3.transfer import TransferConfig3config = TransferConfig(multipart_threshold=1024*25)4s3.upload_file('largefile.zip', 'mybucket', 'largefile.zip',5 Config=config)1table.put_item(2 Item={'id': '123', 'version': 1, 'name': 'Ali'},3 ConditionExpression='attribute_not_exists(id)'4)5# Fails if item with id=123 already exists