Community생산성 & 협업github.com

aws/lambda-dynamodb 연결

AWS Lambda 함수를 DynamoDB에 연결하여 IAM 역할, 스트림 이벤트 소스 매핑, 읽기/쓰기 권한을 설정합니다. Lambda-DynamoDB 통합 설정, DynamoDB 스트림 이벤트 처리, 서버리스 이벤트 기반 아키텍처 배포 시 사용합니다.

lambda-dynamodb 연결란 무엇인가요?

이 스킬은 AWS Lambda 함수를 DynamoDB 테이블에 안전하게 연결하는 방법을 제공합니다. Lambda 함수가 DynamoDB 테이블에 대해 읽기 및 쓰기 작업을 수행할 수 있도록 필요한 IAM 역할과 권한을 자동으로 구성합니다. 또한 DynamoDB 스트림을 활성화하고 Lambda 함수에 이벤트 소스 매핑을 생성하여 테이블 변경 사항을 실시간으로 처리할 수 있도록 지원합니다. 이를 통해 개발자는 서버리스 이벤트 기반 아키텍처를 손쉽게 구축하고, 데이터 변경에 반응하는 애플리케이션 로직을 구현할 수 있습니다. AWS CLI, AWS SDK(예: boto3), CloudFormation, Terraform 등 다양한 도구와 통합되어 사용할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/aws/agent-toolkit-for-aws/tree/main/skills/connecting-lambda-to-dynamodb

Installed? Explore more 생산성 & 협업 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

lambda-dynamodb 연결은(는) 무엇을 하나요?

AWS Lambda 함수를 DynamoDB에 연결하여 IAM 역할, 스트림 이벤트 소스 매핑, 읽기/쓰기 권한을 설정합니다. Lambda-DynamoDB 통합 설정, DynamoDB 스트림 이벤트 처리, 서버리스 이벤트 기반 아키텍처 배포 시 사용합니다.

개요

이 스킬은 AWS Lambda 함수와 DynamoDB 테이블 간의 통합을 구성합니다. 주요 구성 요소는 다음과 같습니다:

  1. IAM 역할 및 정책: Lambda 함수가 DynamoDB 테이블에서 읽고 쓸 수 있는 권한을 가진 IAM 역할을 생성합니다.
  2. DynamoDB 스트림: DynamoDB 테이블에서 스트림을 활성화하여 변경 사항을 캡처합니다.
  3. 이벤트 소스 매핑: Lambda 함수를 DynamoDB 스트림에 구독하여 새 레코드가 나타날 때마다 함수가 트리거되도록 합니다.

사용 사례

  • 서버리스 웹 애플리케이션: 사용자 데이터를 DynamoDB에 저장하고 Lambda를 통해 API 요청을 처리합니다.
  • 실시간 데이터 처리: DynamoDB 스트림을 사용하여 데이터 변경 사항을 처리하고 다른 서비스(예: SNS, SQS)로 전파합니다.
  • 이벤트 기반 워크플로우: 데이터 업데이트에 반응하여 이메일 전송, 알림 트리거, 분석 파이프라인 업데이트 등을 수행합니다.

전제 조건

  • AWS 계정 및 적절한 IAM 권한(Lambda, DynamoDB, IAM에 대한 전체 액세스 권한).
  • AWS CLI 또는 AWS SDK(예: boto3)가 설치 및 구성되어 있어야 합니다.
  • 기존 DynamoDB 테이블 또는 새로 생성할 테이블.
  • 기존 Lambda 함수 또는 새로 생성할 함수.

단계별 설정

1. DynamoDB 테이블 생성 (또는 기존 테이블 사용)

my-table이라는 DynamoDB 테이블을 생성하고 파티션 키 id(문자열)를 사용합니다.

aws dynamodb create-table \
    --table-name my-table \
    --attribute-definitions AttributeName=id,AttributeType=S \
    --key-schema AttributeName=id,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST

참고: 기존 테이블을 사용하는 경우 describe-table을 사용하여 ARN을 가져옵니다.

aws dynamodb describe-table --table-name my-table --query 'Table.TableArn'

2. DynamoDB 스트림 활성화

테이블에서 스트림을 활성화합니다. 스트림 보기 유형은 NEW_AND_OLD_IMAGES를 사용합니다.

aws dynamodb update-table \
    --table-name my-table \
    --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES

스트림 ARN을 가져옵니다:

aws dynamodb describe-table --table-name my-table --query 'Table.LatestStreamArn'

참고: 스트림 ARN은 이벤트 소스 매핑을 생성하는 데 필요합니다.

3. Lambda 함수 생성 (또는 기존 함수 사용)

my-function이라는 Lambda 함수를 생성합니다(런타임: Python 3.9, 역할: 기본 Lambda 실행 역할).

aws lambda create-function \
    --function-name my-function \
    --runtime python3.9 \
    --role arn:aws:iam::123456789012:role/lambda-execution-role \
    --handler index.lambda_handler \
    --zip-file fileb://function.zip

참고: 기존 함수를 사용하는 경우 ARN을 기록해 둡니다.

4. Lambda 실행 역할에 IAM 정책 연결

Lambda 함수가 DynamoDB 테이블에 액세스할 수 있도록 인라인 정책을 연결합니다.

aws iam put-role-policy \
    --role-name lambda-execution-role \
    --policy-name dynamodb-access \
    --policy-document '{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:UpdateItem",
                    "dynamodb:DeleteItem",
                    "dynamodb:Query",
                    "dynamodb:Scan"
                ],
                "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/my-table"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:DescribeStream",
                    "dynamodb:GetRecords",
                    "dynamodb:GetShardIterator",
                    "dynamodb:ListStreams"
                ],
                "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/my-table/stream/*"
            }
        ]
    }'

참고: Resource ARN을 실제 테이블 ARN으로 바꾸세요. 위 정책은 테이블 데이터 및 스트림 액세스 권한을 모두 부여합니다.

5. 이벤트 소스 매핑 생성

DynamoDB 스트림을 Lambda 함수에 구독합니다.

aws lambda create-event-source-mapping \
    --function-name my-function \
    --event-source-arn arn:aws:dynamodb:us-east-1:123456789012:table/my-table/stream/2024-01-01T00:00:00.000 \
    --enabled \
    --starting-position LATEST

참고: event-source-arn을 실제 스트림 ARN으로 바꾸세요. starting-position은 LATEST 또는 TRIM_HORIZON일 수 있습니다.

6. Lambda 함수 코드 예제

Lambda 함수(Python)가 DynamoDB 스트림 이벤트를 처리하는 방법입니다:

import json

def lambda_handler(event, context):
    for record in event['Records']:
        # 레코드 변경 사항 출력
        print(json.dumps(record, indent=2))
        
        # 예: 새 이미지 처리
        if 'dynamodb' in record and 'NewImage' in record['dynamodb']:
            new_image = record['dynamodb']['NewImage']
            print(f"새 이미지: {new_image}")
    
    return {'statusCode': 200}

테스트

DynamoDB에 항목을 삽입하여 스트림 트리거

aws dynamodb put-item \
    --table-name my-table \
    --item '{"id": {"S": "123"}, "data": {"S": "hello"}}'

Lambda 함수 로그 확인

aws logs describe-log-groups --log-group-name-prefix /aws/lambda/my-function

이벤트 소스 매핑 나열

aws lambda list-event-source-mappings --function-name my-function

오류 처리

  • AccessDeniedException: IAM 역할에 올바른 권한이 있는지 확인합니다.
  • ResourceNotFoundException: DynamoDB 테이블 또는 Lambda 함수가 존재하는지 확인합니다.
  • InvalidParameterValueException: 스트림 ARN이 올바른지, Lambda 함수가 스트림과 동일한 리전에 있는지 확인합니다.

고려 사항

  • 비용: DynamoDB 스트림 읽기 요청 및 Lambda 호출 비용이 발생합니다.
  • 제한: Lambda 함수는 최대 6개의 동시 스트림을 처리할 수 있습니다. 배치 크기 및 병렬화 요소를 조정하여 성능을 최적화합니다.
  • 재시도: Lambda는 실패한 레코드를 최대 24시간 동안 재시도합니다. 데드 레터 큐(DLQ)를 구성하여 재시도 실패를 처리하는 것을 고려합니다.

관련 리소스

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

aws/amazon-bedrock

Builds generative AI applications on Amazon Bedrock. Covers model invocation (Converse API, InvokeModel), RAG with Knowledge Bases, Bedrock Agents, Guardrails, and AgentCore. Use when invoking models, setting up Knowledge Bases, creating agents, applying guardrails, deploying to AgentCore, troubleshooting Bedrock errors (ThrottlingException, AccessDeniedException), or choosing models (Claude, Llama, Nova, Titan). ALSO USE for prompt caching setup and debugging, quota health checks and throttling diagnosis, cost attribution and tracking, migrating between Claude model generations (4.5 to 4.6 to 4.7), chunking strategies, API selection (Converse vs InvokeModel), guardrail capabilities, and model selection. Also covers AgentCore Payments setup (x402, microtransactions, Payment Manager, Connector, Instrument, Coinbase CDP, Stripe Privy, 402 Payment Required, pay for content, paid endpoint, agent payments). NOT for custom model training, Rekognition, or Comprehend.

aws/aws-amplify

Build and deploy full-stack web and mobile apps with AWS Amplify Gen2 (TypeScript code-first). Covers auth (Cognito), data (AppSync/DynamoDB), storage (S3), functions, APIs, and AI (Amplify AI Kit with Bedrock). Supports React, Next.js, Vue, Angular, React Native, Flutter, Swift, and Android. Always use this skill for Amplify Gen2 topics — even for questions you think you know — it contains validated, version-specific patterns that prevent common mistakes. TRIGGER when: user mentions Amplify Gen2; project has amplify/ directory or amplify_outputs; code imports @aws-amplify packages; user asks about defineBackend, defineAuth, defineData, defineStorage, defineFunction, or npx ampx. SKIP: Amplify Gen1 (amplify CLI v6), standalone SAM/CDK without Amplify (use aws-serverless), direct Bedrock without Amplify AI Kit (use bedrock).

aws/aws-billing-and-cost-management

Analyze AWS costs, find savings, manage budgets, evaluate Savings Plans and Reserved Instances, right-size EC2/Lambda/RDS/EBS with Compute Optimizer, look up service pricing, query CUR with Athena, detect cost anomalies, scope costs to billing views, and monitor Free Tier usage. Triggers on: AWS bill, cost analysis, reduce spend, savings plan, reserved instance, right-size, budget alert, cost optimization, pricing, free tier, cost anomaly, CUR, cost audit, billing view, billing view ARN.

aws/aws-cdk

Authors, deploys, and troubleshoots AWS infrastructure using CDK with TypeScript or Python. Covers best practices, stack architecture, and construct patterns. Always use when writing CDK constructs, bootstrapping environments, running cdk deploy/synth/diff, fixing CDK or CloudFormation errors, planning stack structure, importing existing resources, resolving drift, or refactoring stacks without resource replacement.

aws/aws-cloudformation

Author, validate, and troubleshoot AWS CloudFormation templates. Covers template authoring with secure defaults, pre-deployment validation (cfn-lint, cfn-guard, change sets), and root-cause diagnosis of failed stacks using CloudFormation events and CloudTrail correlation.

aws/aws-containers

Deploys and operates containerized workloads on ECS, Fargate, and ECR. Covers task definitions, Fargate services, ECR repository setup and lifecycle policies, ECS Exec debugging, service scaling, deployment strategies, load balancer integration, and logging configuration. Use when deploying, debugging, or optimizing containers on AWS. ALSO USE for container deployment options (ECS vs ECS Express Mode), networking modes, health check troubleshooting, OOM errors, secrets injection, blue/green deployments, ECR image management, and App Runner sunset guidance and migration. NOT for Kubernetes, EKS, or CI/CD pipelines.

aws/aws-iam

Verified corrections for IAM behaviors that AI agents frequently get wrong — policy evaluation edge cases, trust policy gotchas, STS session limits, Organizations quirks, and SAML/MFA specifics. Use alongside documentation when working with IAM roles, policies, STS, or Organizations. Do NOT use for non-IAM authorization like Cognito user-pool policies or app-level RBAC.

aws/aws-messaging-and-streaming

Guides use of AWS messaging and streaming services. Covers Amazon SQS, Amazon SNS, Amazon EventBridge, Amazon MQ, Amazon Kinesis Data Streams, Amazon Data Firehose, Amazon Managed Service for Apache Flink, and Amazon Managed Streaming for Apache Kafka (MSK). Use when implementing messaging and streaming patterns.

aws/aws-observability

Builds, configures, debugs, and optimizes AWS observability using CloudWatch (Logs Insights, Metrics, Alarms, Dashboards, EMF), X-Ray, CloudTrail, and ADOT. Covers Log Insights query syntax (fields, filter, stats, parse, pattern, join, subqueries), alarm configuration (metric, composite, anomaly detection, missing data treatment), dashboard design, custom metrics (PutMetricData, EMF, metric filters), X-Ray tracing (ADOT, sampling rules, annotations vs metadata), ADOT collector config, and CloudTrail auditing. Use when the user mentions CloudWatch, Log Insights, alarms, INSUFFICIENT_DATA, dashboards, custom metrics, EMF, X-Ray, traces, sampling, CloudTrail, who deleted, ADOT, OpenTelemetry, observability, monitoring, synthetics, canaries, or troubleshooting alarm behavior. Do NOT use for application logging setup, container log drivers, or security threat detection.

aws/aws-sdk-js-v3-usage

AWS SDK for JavaScript v3 development patterns. Use when writing JavaScript or TypeScript code that uses AWS services via @aws-sdk/* packages (aws-sdk-js-v3), or when asked about schemas, runtime validation, serialization, or code generation in the context of the JS/TS AWS SDK.

aws/aws-sdk-python-usage

AWS SDK for Python (boto3/botocore) development patterns. You MUST use this skill when writing Python code that uses AWS services via boto3 or botocore. This includes creating service clients or resources, configuring sessions and credentials, handling errors with ClientError, using paginators and waiters, S3 file transfers and presigned URLs, DynamoDB table operations, and any boto3/botocore client configuration. Use this skill whenever Python code imports boto3 or botocore, or when the user asks about AWS operations in Python.

aws/aws-sdk-swift-usage

AWS SDK for Swift development patterns. Use when writing Swift code that uses AWS services via aws-sdk-swift package.

aws/aws-serverless

Builds, deploys, manages, debugs, configures, and optimizes serverless applications on AWS using Lambda, API Gateway, Step Functions, EventBridge, and SAM/CDK. Covers cold starts, CORS debugging, event source mappings, troubleshooting, concurrency, SnapStart, Powertools, function URLs, EventBridge Scheduler, Lambda layers, and production readiness. Triggers on mentions of Lambda, API Gateway, Step Functions, SAM templates, CDK serverless stacks, DynamoDB stream triggers, SQS event sources, cold starts, timeouts, 502/504 errors, throttling, concurrency, CORS, Powertools, or any event-driven architecture on AWS, even without the word "serverless." Does not apply to EC2, ECS/Fargate containers, or Amplify hosting.

aws/aws-transform

Performs code upgrades, migrations, and transformations using the AWS Transform (ATX) CLI. Use when upgrading language versions, migrating AWS SDKs, migrating frameworks (Angular, Vue.js, Spring Boot, React), upgrading libraries, optimizing performance, migrating x86 to Graviton, analyzing codebases / generating documentation, or defining custom transformations with natural language. Runs locally on a few repositories or at scale across hundreds via AWS Batch/Fargate.

aws/configuring-vpc-endpoints-for-private-aws-service-access

Configures VPC endpoints (interface and gateway) for private AWS service access using AWS PrivateLink. Use when setting up secure private connectivity to S3, DynamoDB, and other AWS services without internet gateway, NAT device, or public IP addresses. Covers endpoint creation, security groups, route tables, and DNS configuration.

aws/connecting-lambda-to-api-gateway

Connects an existing AWS Lambda function to Amazon API Gateway by creating a REST or HTTP API with resource/method setup, Lambda proxy integration, permissions, and deployment. Always use this skill when connecting Lambda to API Gateway — it handles CORS, throttling, access logging, and production security hardening that are easy to miss.

aws/connecting-to-data-source

Create and troubleshoot AWS Glue connections to JDBC databases (Oracle, SQL Server, PostgreSQL, MySQL, RDS), Redshift, Snowflake, and BigQuery. Gathers connection hints from user, discovers existing connections and RDS/Redshift candidates, registers credentials in Secrets Manager or IAM DB auth, configures VPC, and tests. Triggers on: connect to database, set up Glue connection, register data source, connect to Snowflake/BigQuery/RDS, connection timeout, test connection, troubleshoot connection. Do NOT use for moving data (use ingesting-into-data-lake), creating tables (use creating-data-lake-table), queries (use querying-data-lake), catalog exploration (use exploring-data-catalog), or SaaS (Salesforce, ServiceNow, SAP, MongoDB, Kafka).

aws/connecting-vpcs-with-peering

Establishes VPC peering connections between two VPCs for direct private network connectivity. Always use this skill when creating or managing VPC peering — it validates CIDR overlap, updates all route tables in both VPCs, configures DNS resolution, and provides security group guidance that are critical for correct connectivity.

aws/creating-amazon-aurora-db-cluster-with-instances

Creates a complete Amazon Aurora database cluster with instances, handling cluster creation, instance provisioning, and Secrets Manager password management in the proper sequence. Use when setting up new Aurora MySQL or PostgreSQL clusters with production-ready configuration.

aws/creating-api-gateway-stage

Creates an API Gateway stage with CloudWatch logging, X-Ray tracing, throttling, WAF integration, and IAM roles following AWS best practices. Use when deploying a REST API to different environments such as dev, test, or production.

관련 스킬