¿Cómo cambio el modo de capacidad de varias tablas de Amazon DynamoDB al mismo tiempo?
Quiero cambiar el modo de capacidad de varias tablas de Amazon DynamoDB al mismo tiempo.
Descripción corta
Al cambiar el modo de capacidad de varias tablas de DynamoDB, debes especificar el modo de capacidad aprovisionada o el modo de capacidad bajo demanda. Antes de cambiar el modo de capacidad, consulta Consideraciones al cambiar los modos de capacidad en DynamoDB.
Para cambiar el modo de capacidad de varias tablas de DynamoDB al mismo tiempo, utiliza uno de los métodos siguientes:
- Interfaz de la línea de comandos de AWS (AWS CLI)
- AWS CloudFormation
- Python
Resolución
Prácticas recomendadas
Cuando cambies el modo de capacidad de varias tablas de DynamoDB, utiliza las siguientes prácticas recomendadas:
- Antes de iniciar el cambio, configura las credenciales de la AWS CLI adecuadas.
- Asegúrate de tener los permisos de AWS Identity and Access Management (IAM) adecuados.
- Implementa primero los cambios en un entorno que no sea de producción.
- Espera varios minutos para que cada tabla pueda completar el cambio.
- Cambia los modos de capacidad en cada tabla solo una vez cada 24 horas.
- Analiza los patrones de uso para seleccionar el modo de capacidad adecuado y ajustarlo a los requisitos regionales de AWS.
- Supervisa los costes después del cambio para asegurarte de que tienes la capacidad aprovisionada adecuada.
AWS CLI
Nota: Si se muestran errores al ejecutar comandos de la Interfaz de la línea de comandos de AWS (AWS CLI), consulta Solución de problemas de AWS CLI. Además, asegúrate de utilizar la versión más reciente de AWS CLI.
Modo aprovisionado
Para usar AWS CLI para cambiar el modo de capacidad de varias tablas de DynamoDB al modo aprovisionado, sigue estos pasos:
-
Abre el editor de texto e introduce el siguiente código para crear un nuevo script de shell:
#!/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 "----------------------------------------" donePara cambiar el modo de capacidad de todas las tablas de DynamoDB al modo bajo demanda, elimina la siguiente sección del código:
#OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3")Para cambiar el modo de capacidad de tablas específicas de DynamoDB al modo bajo demanda, sustituye ** “tabla1” “tabla2” “tabla3”** por los nombres de las tablas. A continuación, elimine la siguiente sección del código:
#OPTION2: Get all table names in the account TABLES=$(aws dynamodb list-tables —query 'TableNames[]' —output text)**Nota:**Sustituye READ_CAPACITY_VALUE y WRITE_CAPACITY_VALUE por tus valores de capacidad de lectura y escritura.
-
Guarda el archivo con el nombre switch-all-tables-with-gsi-to-provisioned.sh.
-
Para que el archivo sea ejecutable, abre el terminal y ejecuta el siguiente comando:
chmod +x switch-all-tables-with-gsi-to-provisioned.sh -
Para ejecutar el script de shell en el terminal, ejecuta el siguiente comando:
./switch-all-tables-with-gsi-to-provisioned.sh
Modo bajo demanda
Para usar AWS CLI para cambiar el modo de capacidad de varias tablas de DynamoDB al modo bajo demanda, sigue estos pasos:
-
Abre el editor de texto e introduce el siguiente código para crear un nuevo script de shell:
#!/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 "----------------------------------------" donePara cambiar el modo de capacidad de todas las tablas de DynamoDB al modo bajo demanda, elimina la siguiente sección del código:
#OPTION1: List of table names you want to switch TABLES=("table1" "table2" "table3")Para cambiar el modo de capacidad de tablas específicas de DynamoDB al modo bajo demanda, sustituye ** “tabla1” “tabla2” “tabla3”** por los nombres de las tablas. A continuación, elimine la siguiente sección del código:
`#OPTION2: Get all table names in the account` TABLES=$(aws dynamodb list-tables —region $AWS\_REGION —query 'TableNames\[\]' —output text)Nota: Sustituye REGION por tu región. Usa el código de la región, como us-east-1.
-
Para que el archivo sea ejecutable, abre el terminal y ejecuta el comando:
chmod +x switch-all-tables-with-gsi-to-ondemand.sh -
Para ejecutar el script de shell en el terminal, ejecuta el comando:
./switch-all-tables-with-gsi-to-ondemand.sh
CloudFormation
Sigue estas prácticas recomendadas:
- Configura las plantillas de AWS Lambda para usar la versión ejecutable de Python 3.9.
- Supervisa los registros de Amazon CloudWatch para realizar un seguimiento del progreso de la función de Lambda.
Nota: Antes de empezar, configura tus credenciales de AWS. Ejecuta el siguiente comando configure de AWS CLI:
aws configure
Modo aprovisionado
Para usar CloudFormation para cambiar el modo de capacidad de varias tablas de DynamoDB al modo aprovisionado, sigue estos pasos:
-
Abre el editor de texto e introduce el siguiente código para crear un nuevo archivo YAML:
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: '*' -
Guarda el archivo con el nombre switch-to-provisioned.yaml.
-
Ejecuta el siguiente comando create-stack de AWS CLI:
# 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]Nota: Sustituye “Tabla1,Tabla2,Table3” por los nombres de las tablas, RCU_VALUE y WCU_VALUE por tus valores de RCU y WCU, y REGION por tu región, como us-east-1.
Modo bajo demanda
Para usar CloudFormation para cambiar el modo de capacidad de varias tablas de DynamoDB al modo bajo demanda, sigue estos pasos:
-
Abre el editor de texto e introduce el siguiente código para crear un nuevo archivo YAML:
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: '*' -
Guarda el archivo con el nombre switch-to-ondemand.yaml.
-
Ejecuta el siguiente comando create-stack de AWS CLI:
# 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"**Nota:**Sustituye “Tabla1,Tabla2,Tabla3” por los nombres de las tablas y REGION por tu región.
Python
Puedes usar una instancia de Amazon Elastic Compute Cloud (EC2), Lambda o tu propio escritorio para ejecutar un script de Python. Antes de cambiar el modo de capacidad, asegúrate de haber instalado Python, pip y boto3.
Antes de empezar, configura tus credenciales de AWS. Ejecuta el siguiente comando configure de AWS CLI:
aws configure
Modo aprovisionado
Para usar un script de Python para cambiar el modo de capacidad de todas las tablas de DynamoDB de una región específica al modo aprovisionado, sigue estos pasos:
-
Abre Python e introduce el siguiente código para crear un archivo nuevo:
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 )Nota: Sustituye RCU_VALUE y WCU_VALUE por tus valores de RCU Y WCU y REGION por tu región, como us-east-1.
-
Guarda el archivo con el nombre switch_to_provisioned.py.
-
Abre el terminal y ejecuta el siguiente comando para ejecutar el script de Python:
python switch_to_provisioned.py
Modo bajo demanda
Para usar un script de Python para cambiar el modo de capacidad de todas las tablas de DynamoDB de una región específica al modo bajo demanda, sigue estos pasos:
-
Abre Python e introduce el siguiente código para crear un archivo nuevo:
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)Nota: Sustituye REGION por tu región.
-
Guarda el archivo con el nombre switch_to_ondemand.py.
-
Abre el terminal y ejecuta el siguiente comando para ejecutar el script de Python:
python switch_to_ondemand.py
Información relacionada
- Temas
- Database
- Etiquetas
- Amazon DynamoDB
- Idioma
- Español

Contenido relevante
- preguntada hace un mes
- Respuesta aceptadapreguntada hace 9 meses
- preguntada hace 10 meses
OFICIAL DE AWSActualizada hace un año
OFICIAL DE AWSActualizada hace 2 años
OFICIAL DE AWSActualizada hace 2 meses