Ongoing service disruptions
For the most recent update on ongoing service disruptions affecting the AWS Middle East (UAE) Region (ME-CENTRAL-1), refer to the AWS Health Dashboard. For information on AWS Service migration, see How do I migrate my services to another region?
Wie ändere ich den Kapazitätsmodus für mehrere Amazon-DynamoDB-Tabellen gleichzeitig?
Ich möchte den Kapazitätsmodus für mehrere Amazon-DynamoDB-Tabellen gleichzeitig ändern.
Kurzbeschreibung
Wenn du den Kapazitätsmodus mehrerer DynamoDB-Tabellen änderst, musst du entweder den bereitgestellten Kapazitätsmodus oder den On-Demand-Kapazitätsmodus angeben. Bevor du den Kapazitätsmodus änderst, siehe Überlegungen beim Wechseln des Kapazitätsmodus in DynamoDB.
Verwende eine der folgenden Methoden, um den Kapazitätsmodus mehrerer DynamoDB-Tabellen gleichzeitig zu ändern:
- AWS Command Line Interface (AWS CLI)
- AWS CloudFormation
- Python
Lösung
Bewährte Methoden
Wenn du den Kapazitätsmodus mehrerer DynamoDB-Tabellen änderst, verwende die folgenden Best Practices:
- Bevor du die Änderung einleitest, konfiguriere die entsprechenden AWS-CLI-Anmeldeinformationen.
- Stelle sicher, dass du über die entsprechenden AWS Identity and Access Management (IAM)-Berechtigungen verfügst.
- Stelle deine Änderungen zunächst in einer Umgebung bereit, die nichts mit der Produktion zu tun hat.
- Warte einige Minuten, bis jede Tabelle den Wechsel abgeschlossen hat.
- Wechsle für jede Tabelle nur einmal alle 24 Stunden zwischen den Kapazitätsmodi.
- Analysiere die Nutzungsmuster, um den geeigneten Kapazitätsmodus auszuwählen, und passe ihn an die regionalen AWS-Anforderungen an.
- Überwache die Kosten nach dem Wechsel, um sicherzustellen, dass du über die entsprechende bereitgestellte Kapazität verfügst.
AWS CLI
Hinweis: Wenn du beim Ausführen von AWS Command Line Interface (AWS CLI)-Befehlen Fehlermeldungen erhältst, findest du weitere Informationen dazu unter Problembehandlung bei der AWS CLI. Stelle außerdem sicher, dass du die neueste Version von AWS CLI verwendest.
Bereitgestellter Modus
Gehe wie folgt vor, um mithilfe der AWS CLI den Kapazitätsmodus mehrerer DynamoDB-Tabellen in den Bereitstellungsmodus zu ändern:
-
Öffne deinen Texteditor und gib den folgenden Code ein, um ein neues Shell-Skript zu erstellen:
#!/bin/bash # Set the AWS region AWS_REGION=[REGION] # Change this to your desired region # OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3") # OPTION2: Get all table names in the account TABLES=$(aws dynamodb list-tables —region $AWS_REGION —query 'TableNames[]' —output text) # Default provisioned capacity units READ_CAPACITY=READ_CAPACITY_VALUE WRITE_CAPACITY=WRITE_CAPACITY_VALUE echo "Using AWS Region: $AWS_REGION" for TABLE_NAME in $TABLES do # Check current billing mode CURRENT_MODE=$(aws dynamodb describe-table —region $AWS_REGION —table-name $TABLE_NAME —query 'Table.BillingModeSummary.BillingMode' —output text) if [ "$CURRENT_MODE" = "PAY_PER_REQUEST" ]; then echo "Processing table: $TABLE_NAME" # Get GSI configurations GSI_CONFIG="" GSI_LIST=$(aws dynamodb describe-table —region $AWS_REGION —table-name $TABLE_NAME —query 'Table.GlobalSecondaryIndexes[*].IndexName' —output text) if [ ! -z "$GSI_LIST" ]; then echo "Found GSIs: $GSI_LIST" # Build GSI provisioned throughput configuration GSI_CONFIG="—global-secondary-index-updates“ for GSI_NAME in $GSI_LIST do if [ -z "$FIRST_GSI" ]; then GSI_CONFIG="$GSI_CONFIG [{\"Update\":{\"IndexName\":\"$GSI_NAME\",\"ProvisionedThroughput\":{\"ReadCapacityUnits\":$READ_CAPACITY,\"WriteCapacityUnits\":$WRITE_CAPACITY}}}" FIRST_GSI="false" else GSI_CONFIG="$GSI_CONFIG,{\"Update\":{\"IndexName\":\"$GSI_NAME\",\"ProvisionedThroughput\":{\"ReadCapacityUnits\":$READ_CAPACITY,\"WriteCapacityUnits\":$WRITE_CAPACITY}}}" fi done GSI_CONFIG="$GSI_CONFIG]" fi # Update table and GSIs if [ ! -z "$GSI_CONFIG" ]; then echo "Updating table and GSIs..." aws dynamodb update-table \ --region $AWS_REGION \ --table-name $TABLE_NAME \ --billing-mode PROVISIONED \ --provisioned-throughput ReadCapacityUnits=$READ_CAPACITY,WriteCapacityUnits=$WRITE_CAPACITY \ $GSI_CONFIG else echo "Updating table (no GSIs)..." aws dynamodb update-table \ --region $AWS_REGION \ --table-name $TABLE_NAME \ --billing-mode PROVISIONED \ --provisioned-throughput ReadCapacityUnits=$READ_CAPACITY,WriteCapacityUnits=$WRITE_CAPACITY fi echo "Request submitted for $TABLE_NAME" else echo "Skipping $TABLE_NAME - already in PROVISIONED mode" fi # Reset GSI tracking for next table FIRST_GSI="" echo "----------------------------------------" doneUm den Kapazitätsmodus aller DynamoDB-Tabellen in den On-Demand-Modus zu ändern, entferne den folgenden Code-Abschnitt:
#OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3")Um den Kapazitätsmodus bestimmter DynamoDB-Tabellen in den On-Demand-Modus zu ändern, ersetze „table1“ „table2“ „table3“ durch deine Tabellennamen. Entferne dann den folgenden Code-Abschnitt:
#OPTION2: Get all table names in the account TABLES=$(aws dynamodb list-tables —query 'TableNames[]' —output text)**Hinweis:**Ersetze READ_CAPACITY_VALUE und WRITE_CAPACITY_VALUE durch deine Lese- und Schreibkapazitätswerte.
-
Speichere die Datei mit dem Namen switch-all-tables-with-gsi-to-provisioned.sh.
-
Um die Datei ausführbar zu machen, öffne das Terminal und führe den folgenden Befehl aus:
chmod +x switch-all-tables-with-gsi-to-provisioned.sh -
Um das Shell-Skript im Terminal auszuführen, führe den folgenden Befehl aus:
./switch-all-tables-with-gsi-to-provisioned.sh
On-Demand-Modus
Gehe wie folgt vor, um mithilfe der AWS CLI den Kapazitätsmodus mehrerer DynamoDB-Tabellen in den On-Demand-Modus zu ändern:
-
Öffne deinen Texteditor und gib dann den folgenden Code ein, um ein neues Shell-Skript zu erstellen:
#!/bin/bash # Set the AWS region AWS_REGION=[REGION] # Change this to your desired region # OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3") # OPTION2: Get all table names in the account #TABLES=$(aws dynamodb list-tables --region $AWS_REGION --query 'TableNames[]' --output text) for TABLE_NAME in $TABLES do # Check current billing mode CURRENT_MODE=$(aws dynamodb describe-table --region $AWS_REGION --table-name $TABLE_NAME --query 'Table.BillingModeSummary.BillingMode' --output text) if [ "$CURRENT_MODE" = "PROVISIONED" ]; then echo "Processing table: $TABLE_NAME" # Check if table has any GSIs GSI_LIST=$(aws dynamodb describe-table --region $AWS_REGION --table-name $TABLE_NAME --query 'Table.GlobalSecondaryIndexes[*].IndexName' --output text) if [ ! -z "$GSI_LIST" ]; then echo "Table has GSIs: $GSI_LIST" echo "Note: GSIs will automatically switch to On-Demand with the table" fi # Update table to On-Demand echo "Switching $TABLE_NAME to PAY_PER_REQUEST mode..." aws dynamodb update-table \ --region $AWS_REGION \ --table-name $TABLE_NAME \ --billing-mode PAY_PER_REQUEST echo "Request submitted for $TABLE_NAME" else echo "Skipping $TABLE_NAME - already in PAY_PER_REQUEST mode" fi echo "----------------------------------------" doneUm den Kapazitätsmodus aller DynamoDB-Tabellen in den On-Demand-Modus zu ändern, entferne den folgenden Code-Abschnitt:
#OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3")Um den Kapazitätsmodus bestimmter DynamoDB-Tabellen in den On-Demand-Modus zu ändern, ersetze „table1“ „table2“ „table3“ durch deine Tabellennamen. Entferne dann den folgenden Code-Abschnitt:
`#OPTION2: Get all table names in the account` TABLES=$(aws dynamodb list-tables —region $AWS\_REGION —query 'TableNames\[\]' —output text)Hinweis: Ersetze REGION durch deine Region. Verwende den Code der Region, z. B. us-east-1.
-
Um die Datei ausführbar zu machen, öffne das Terminal und führe den folgenden Befehl aus:
chmod +x switch-all-tables-with-gsi-to-ondemand.sh -
Um das Shell-Skript im Terminal auszuführen, führe den folgenden Befehl aus:
./switch-all-tables-with-gsi-to-ondemand.sh
CloudFormation
Verwende die folgenden bewährten Methoden:
- Stelle die AWS-Lambda-Vorlagen so ein, dass sie die Python 3.9-Laufzeit verwenden.
- Überwache Amazon CloudWatch Logs, um den Fortschritt der Lambda-Funktion zu verfolgen.
**Hinweis:**Bevor du beginnst, konfiguriere deine AWS-Anmeldeinformationen. Führe den folgenden AWS-CLI-Befehl configure aus:
aws configure
Bereitgestellter Modus
Gehe wie folgt vor, um mithilfe von CloudFormation den Kapazitätsmodus mehrerer DynamoDB-Tabellen in den Bereitstellungsmodus zu ändern:
-
Öffne deinen Texteditor und gib den folgenden Code ein, um eine neue YAML-Datei zu erstellen:
AWSTemplateFormatVersion: '2010-09-09' Description: 'Switch specific DynamoDB tables from On-Demand to Provisioned capacity mode' Parameters: ReadCapacityUnits: Type: Number Default: 5 Description: Read Capacity Units for tables and GSIs WriteCapacityUnits: Type: Number Default: 5 Description: Write Capacity Units for tables and GSIs TableNames: Type: CommaDelimitedList Description: Comma-separated list of DynamoDB table names to update Resources: DynamoDBTableUpdates: Type: Custom::DynamoDBTableUpdates Properties: ServiceToken: !GetAtt UpdateTablesFunction.Arn ReadCapacityUnits: !Ref ReadCapacityUnits WriteCapacityUnits: !Ref WriteCapacityUnits TableNames: !Ref TableNames UpdateTablesFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.9 Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: | import boto3 import cfnresponse def handler(event, context): try: if event['RequestType'] in ['Create', 'Update']: dynamodb = boto3.client('dynamodb') # Get parameters read_capacity = event['ResourceProperties']['ReadCapacityUnits'] write_capacity = event['ResourceProperties']['WriteCapacityUnits'] table_names = event['ResourceProperties']['TableNames'] for table_name in table_names: try: # Get table details table = dynamodb.describe_table(TableName=table_name)['Table'] current_mode = table.get('BillingModeSummary', {}).get('BillingMode', '') if current_mode == 'PAY_PER_REQUEST': # Prepare GSI updates if any gsi_updates = [] if 'GlobalSecondaryIndexes' in table: for gsi in table['GlobalSecondaryIndexes']: gsi_updates.append({ 'Update': { 'IndexName': gsi['IndexName'], 'ProvisionedThroughput': { 'ReadCapacityUnits': int(read_capacity), 'WriteCapacityUnits': int(write_capacity) } } }) # Update table update_params = { 'TableName': table_name, 'BillingMode': 'PROVISIONED', 'ProvisionedThroughput': { 'ReadCapacityUnits': int(read_capacity), 'WriteCapacityUnits': int(write_capacity) } } if gsi_updates: update_params['GlobalSecondaryIndexUpdates'] = gsi_updates dynamodb.update_table(**update_params) print(f"Switching {table_name} to PROVISIONED mode") else: print(f"Table {table_name} is not in PAY_PER_REQUEST mode. Skipping.") except Exception as e: print(f"Error processing table {table_name}: {str(e)}") continue cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) else: cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) except Exception as e: print(f"Error: {str(e)}") cfnresponse.send(event, context, cfnresponse.FAILED, {}) LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Policies: - PolicyName: DynamoDBAccess PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:DescribeTable - dynamodb:UpdateTable Resource: '*' -
Speichere die Datei unter dem Namen switch-to-provisioned.yaml.
-
Führe den folgenden AWS-CLI-Befehl create-stack aus:
# For Provisioned mode aws cloudformation create-stack \ --stack-name switch-to-provisioned \ --template-body file://switch-to-provisioned.yaml \ --capabilities CAPABILITY_IAM \ --region [REGION] \ --parameters ParameterKey=TableNames,ParameterValue="Table1,Table2,Table3" \ ParameterKey=ReadCapacityUnits,ParameterValue=[RCU_VALUE] \ ParameterKey=WriteCapacityUnits,ParameterValue=[WCU_VALUE]Hinweis: Ersetze „Table1,Table2,Table3“ durch deine Tabellennamen, RCU_VALUE und WCU_VALUE durch deine RCU- und WCU-Werte und REGION durch deine Region, z. B. us-east-1.
On-Demand-Modus
Gehe wie folgt vor, um mithilfe von CloudFormation den Kapazitätsmodus mehrerer DynamoDB-Tabellen in den On-Demand-Modus zu ändern:
-
Öffne deinen Texteditor und gib den folgenden Code ein, um eine neue YAML-Datei zu erstellen:
AWSTemplateFormatVersion: '2010-09-09' Description: 'Switch specific DynamoDB tables from Provisioned to On-Demand capacity mode' Parameters: TableNames: Type: CommaDelimitedList Description: Comma-separated list of DynamoDB table names to update Resources: DynamoDBTableUpdates: Type: Custom::DynamoDBTableUpdates Properties: ServiceToken: !GetAtt UpdateTablesFunction.Arn TableNames: !Ref TableNames UpdateTablesFunction: Type: AWS::Lambda::Function Properties: Runtime: python3.9 Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: | import boto3 import cfnresponse def handler(event, context): try: if event['RequestType'] in ['Create', 'Update']: dynamodb = boto3.client('dynamodb') # Get table names from the event table_names = event['ResourceProperties']['TableNames'] for table_name in table_names: try: # Get table details table = dynamodb.describe_table(TableName=table_name)['Table'] current_mode = table.get('BillingModeSummary', {}).get('BillingMode', '') if current_mode == 'PROVISIONED': # Update table to On-Demand dynamodb.update_table( TableName=table_name, BillingMode='PAY_PER_REQUEST' ) print(f"Switching {table_name} to PAY_PER_REQUEST mode") else: print(f"Table {table_name} is not in PROVISIONED mode. Skipping.") except Exception as e: print(f"Error processing table {table_name}: {str(e)}") continue cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) else: cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) except Exception as e: print(f"Error: {str(e)}") cfnresponse.send(event, context, cfnresponse.FAILED, {}) LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Policies: - PolicyName: DynamoDBAccess PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:DescribeTable - dynamodb:UpdateTable Resource: '*' -
Speichere die Datei mit dem Namen switch-to-ondemand.yaml.
-
Führe den folgenden AWS-CLI-Befehl create-stack aus:
# For On-Demand mode aws cloudformation create-stack \ --stack-name switch-to-ondemand \ --template-body file://switch-to-ondemand.yaml \ --capabilities CAPABILITY_IAM \ --region [REGION] \ --parameters ParameterKey=TableNames,ParameterValue="Table1,Table2,Table3"Hinweis: Ersetze „Table1,Table2,Table3“ durch deine Tabellennamen und REGION durch deine Region.
Python
Du kannst eine Amazon Elastic Compute Cloud (EC2)-Instance, Lambda oder deinen eigenen Desktop verwenden, um ein Python-Skript auszuführen. Bevor du den Kapazitätsmodus änderst, stelle sicher, dass du Python, pip und boto3 installiert hast.
Bevor du beginnst, konfiguriere deine AWS-Anmeldeinformationen. Führe den folgenden AWS-CLI-Befehl configure aus:
aws configure
Bereitgestellter Modus
Gehe wie folgt vor, um mithilfe eines Python-Skripts den Kapazitätsmodus aller DynamoDB-Tabellen in einer bestimmten Region in den Bereitstellungsmodus zu ändern:
-
Öffne Python und gib den folgenden Code ein, um eine neue Datei zu erstellen:
import boto3 import time from botocore.exceptions import ClientError def switch_to_provisioned(read_capacity=5, write_capacity=5, region=None): """ Switch all DynamoDB tables from On-Demand to Provisioned capacity mode """ # Initialize DynamoDB client dynamodb = boto3.client('dynamodb', region_name=region) # Get all table names tables = [] paginator = dynamodb.get_paginator('list_tables') for page in paginator.paginate(): tables.extend(page['TableNames']) print(f"Found {len(tables)} tables") for table_name in tables: try: # Get table details response = dynamodb.describe_table(TableName=table_name) table = response['Table'] current_mode = table.get('BillingModeSummary', {}).get('BillingMode', '') if current_mode == 'PAY_PER_REQUEST': print(f"\nProcessing table: {table_name}") # Prepare GSI updates if any gsi_updates = [] if 'GlobalSecondaryIndexes' in table: print(f"Found GSIs for table {table_name}") for gsi in table['GlobalSecondaryIndexes']: gsi_updates.append({ 'Update': { 'IndexName': gsi['IndexName'], 'ProvisionedThroughput': { 'ReadCapacityUnits': read_capacity, 'WriteCapacityUnits': write_capacity } } }) # Prepare update parameters update_params = { 'TableName': table_name, 'BillingMode': 'PROVISIONED', 'ProvisionedThroughput': { 'ReadCapacityUnits': read_capacity, 'WriteCapacityUnits': write_capacity } } if gsi_updates: update_params['GlobalSecondaryIndexUpdates'] = gsi_updates # Update table print(f"Switching {table_name} to PROVISIONED mode...") dynamodb.update_table(**update_params) print(f"Update request submitted for {table_name}") else: print(f"\nSkipping {table_name} - already in PROVISIONED mode") except ClientError as e: if e.response['Error']['Code'] == 'LimitExceededException': print(f"\nError: Cannot update {table_name}. You can only switch between billing modes once per 24 hours.") else: print(f"\nError processing table {table_name}: {str(e)}") continue except Exception as e: print(f"\nUnexpected error processing table {table_name}: {str(e)}") continue # Small delay to avoid API throttling time.sleep(1) if __name__ == "__main__": # You can modify these values READ_CAPACITY = [RCU_VALUE] WRITE_CAPACITY = [WCU_VALUE] REGION = [REGION] # Change to your desired region switch_to_provisioned( read_capacity=READ_CAPACITY, write_capacity=WRITE_CAPACITY, region=REGION )**Hinweis:**Ersetze RCU_VALUE und WCU_VALUE durch deine RCU- UND WCU-Werte und REGION durch deine Region, z. B. us-east-1.
-
Speichere die Datei mit dem Namen switch_to_provisioned.py.
-
Öffne das Terminal und führe den folgenden Befehl aus, um das Python-Skript auszuführen:
python switch_to_provisioned.py
On-Demand-Modus
Gehe wie folgt vor, um mithilfe eines Python-Skripts den Kapazitätsmodus aller DynamoDB-Tabellen in einer bestimmten Region in den On-Demand-Modus zu ändern:
-
Öffne Python und gib den folgenden Code ein, um eine neue Datei zu erstellen:
import boto3 import time from botocore.exceptions import ClientError def switch_to_ondemand(region=None): """ Switch all DynamoDB tables from Provisioned to On-Demand capacity mode """ # Initialize DynamoDB client dynamodb = boto3.client('dynamodb', region_name=region) # Get all table names tables = [] paginator = dynamodb.get_paginator('list_tables') for page in paginator.paginate(): tables.extend(page['TableNames']) print(f"Found {len(tables)} tables") for table_name in tables: try: # Get table details response = dynamodb.describe_table(TableName=table_name) table = response['Table'] current_mode = table.get('BillingModeSummary', {}).get('BillingMode', '') if current_mode == 'PROVISIONED': print(f"\nProcessing table: {table_name}") # Check for GSIs if 'GlobalSecondaryIndexes' in table: print(f"Table {table_name} has GSIs - they will automatically switch to On-Demand") # Update table print(f"Switching {table_name} to PAY_PER_REQUEST mode...") dynamodb.update_table( TableName=table_name, BillingMode='PAY_PER_REQUEST' ) print(f"Update request submitted for {table_name}") else: print(f"\nSkipping {table_name} - already in PAY_PER_REQUEST mode") except ClientError as e: if e.response['Error']['Code'] == 'LimitExceededException': print(f"\nError: Cannot update {table_name}. You can only switch between billing modes once per 24 hours.") else: print(f"\nError processing table {table_name}: {str(e)}") continue except Exception as e: print(f"\nUnexpected error processing table {table_name}: {str(e)}") continue # Small delay to avoid API throttling time.sleep(1) def check_table_status(table_name, region=None): """ Check the current billing mode of a specific table """ dynamodb = boto3.client('dynamodb', region_name=region) try: response = dynamodb.describe_table(TableName=table_name) mode = response['Table'].get('BillingModeSummary', {}).get('BillingMode', 'Unknown') print(f"Table {table_name} is in {mode} mode") return mode except Exception as e: print(f"Error checking table {table_name}: {str(e)}") return None if __name__ == "__main__": REGION = [REGION] # Change to your desired region switch_to_ondemand(region=REGION)Hinweis: Ersetze REGION durch deine Region.
-
Speichere die Datei mit dem Namen switch_to_ondemand.py.
-
Öffne das Terminal und führe den folgenden Befehl aus, um das Python-Skript auszuführen:
python switch_to_ondemand.py
Ähnliche Informationen
- Themen
- Database
- Tags
- Amazon DynamoDB
- Sprache
- Deutsch

Relevanter Inhalt
AWS OFFICIALAktualisiert vor 3 Jahren
AWS OFFICIALAktualisiert vor 10 Monaten